scip-query 0.21.1 → 0.23.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 +317 -0
- package/README.md +11 -0
- package/dist/augment-vue-worker.js +1 -1
- package/dist/by-kind-XI2CSWEY.js +2 -0
- package/dist/call-graph-UONR6JR5.js +2 -0
- package/dist/{chunk-JGMD6JGB.js → chunk-2E7CX53V.js} +2 -2
- package/dist/chunk-2GRUZAQF.js +43 -0
- package/dist/{chunk-RSUH7G5T.js → chunk-2LDBDR6J.js} +2 -2
- package/dist/{chunk-4SZJF4GK.js → chunk-2OOY75BW.js} +2 -2
- package/dist/{chunk-3YETOKNO.js → chunk-2R3V3PSD.js} +2 -2
- package/dist/chunk-2WC2OEDO.js +4 -0
- package/dist/{chunk-O4PZFAXA.js → chunk-3AF4TUFK.js} +2 -2
- package/dist/{chunk-I2LY3KN7.js → chunk-3D3QG236.js} +2 -2
- package/dist/{chunk-DXEJ4FLZ.js → chunk-3FHOF22C.js} +8 -8
- package/dist/{chunk-BCTCADNB.js → chunk-3JKSW6LJ.js} +2 -2
- package/dist/chunk-3L2ZBPEX.js +133 -0
- package/dist/{chunk-4HQYNZ3P.js → chunk-3PJABJSU.js} +2 -2
- package/dist/{chunk-GBZCVYWA.js → chunk-3SVF22I5.js} +2 -2
- package/dist/{chunk-TP2X2C2Y.js → chunk-3WR4E3A3.js} +2 -2
- package/dist/chunk-4FTZ4P5G.js +2 -0
- package/dist/{chunk-LJMWILX6.js → chunk-4ILJCCXV.js} +2 -2
- package/dist/chunk-4UX2F3JX.js +2 -0
- package/dist/chunk-4WNW27SX.js +2 -0
- package/dist/chunk-5ENOG4VP.js +61 -0
- package/dist/{chunk-YKHL4J3G.js → chunk-64BFSI5I.js} +2 -2
- package/dist/chunk-66DVSJQG.js +455 -0
- package/dist/{chunk-BYXWXLKM.js → chunk-6HFCYNYE.js} +2 -2
- package/dist/{chunk-UBETC3Q2.js → chunk-6I6L7Z62.js} +2 -2
- package/dist/{chunk-IZKJQQCQ.js → chunk-6PQNKL3G.js} +2 -2
- package/dist/{chunk-ITF3CWS5.js → chunk-6V5CNXL6.js} +2 -2
- package/dist/chunk-6VVV4WRR.js +4 -0
- package/dist/{chunk-ZQUNCTEZ.js → chunk-7BWFZPPZ.js} +2 -2
- package/dist/{chunk-5QM7QT5B.js → chunk-7CYG22FH.js} +2 -2
- package/dist/chunk-7F45LJKI.js +2 -0
- package/dist/{chunk-QN2AI3D2.js → chunk-7IWV2EG3.js} +2 -2
- package/dist/{chunk-5KIJMEPC.js → chunk-AFHTBORT.js} +2 -2
- package/dist/chunk-AVRYW5OZ.js +2 -0
- package/dist/chunk-B3PYOSCX.js +2 -0
- package/dist/{chunk-YF25RQER.js → chunk-B5D7QPBE.js} +2 -2
- package/dist/{chunk-PU6XDQ2X.js → chunk-BBCIS4DX.js} +5 -5
- package/dist/chunk-BDUVI7TO.js +3 -0
- package/dist/{chunk-UXNXOMXJ.js → chunk-BE7ZZTMC.js} +2 -2
- package/dist/{chunk-527HV7JY.js → chunk-BHVUJOCQ.js} +2 -2
- package/dist/{chunk-4IASLUOP.js → chunk-BJT7LSPK.js} +2 -2
- package/dist/chunk-BKVWUP7Y.js +2 -0
- package/dist/{chunk-QZCACNV5.js → chunk-BQGB4HBD.js} +2 -2
- package/dist/{chunk-QH5Q6M5C.js → chunk-BRV7PIFF.js} +2 -2
- package/dist/chunk-CEEZJXEF.js +2 -0
- package/dist/{chunk-X5MWO4DM.js → chunk-CIYLO6SI.js} +2 -2
- package/dist/chunk-CJZXN4NU.js +2 -0
- package/dist/{chunk-V6XENWOF.js → chunk-CNO7TOKL.js} +2 -2
- package/dist/{chunk-FUUDUAKM.js → chunk-COF23M5F.js} +2 -2
- package/dist/{chunk-GTZFKDP3.js → chunk-CWFP7GM5.js} +2 -2
- package/dist/chunk-D2DHWI3D.js +2 -0
- package/dist/{chunk-SBFDPHKH.js → chunk-D4N5SQ2M.js} +2 -2
- package/dist/{chunk-FCGMQETU.js → chunk-DBRSYFXR.js} +2 -2
- package/dist/{chunk-47WX6UC4.js → chunk-DHUIOLDT.js} +2 -2
- package/dist/{chunk-KGKCJFWZ.js → chunk-DIRJWYBM.js} +2 -2
- package/dist/{chunk-QGVUPYBC.js → chunk-DIUFNHRJ.js} +2 -2
- package/dist/{chunk-YLNCTPOI.js → chunk-DTZCKZEU.js} +2 -2
- package/dist/{chunk-O3EX5STE.js → chunk-DULC3QFP.js} +2 -2
- package/dist/{chunk-B3AREUQK.js → chunk-DYGHBZ2N.js} +2 -2
- package/dist/{chunk-AAOEROT3.js → chunk-E5R6AQ73.js} +2 -2
- package/dist/{chunk-UM56ZET4.js → chunk-E73UNJTF.js} +2 -2
- package/dist/{chunk-6QN4FYQW.js → chunk-EG2CPZMJ.js} +2 -2
- package/dist/{chunk-OMVNRPST.js → chunk-EKV5HX33.js} +2 -2
- package/dist/{chunk-27OUNZW5.js → chunk-EQHFIL6T.js} +2 -2
- package/dist/{chunk-ZGDHC5AT.js → chunk-ESIQ66Z7.js} +2 -2
- package/dist/chunk-EVFUMY4R.js +3 -0
- package/dist/{chunk-WZRNEVYC.js → chunk-F7DY272B.js} +2 -2
- package/dist/chunk-FBN2FGXG.js +2 -0
- package/dist/{chunk-HR5JYLVV.js → chunk-FDLOBR6P.js} +2 -2
- package/dist/chunk-FESCRNVV.js +5 -0
- package/dist/{chunk-MLTKGHD2.js → chunk-FFRKR4EQ.js} +2 -2
- package/dist/chunk-FGA2U4OR.js +8 -0
- package/dist/{chunk-3KXFB2FM.js → chunk-FIQRSHVM.js} +2 -2
- package/dist/{chunk-ZP2WUVZ5.js → chunk-FPYLNQPT.js} +2 -2
- package/dist/{chunk-EPLE5O5O.js → chunk-FRUSVINH.js} +2 -2
- package/dist/chunk-GAS2LJMP.js +3 -0
- package/dist/{chunk-4TOU7HHQ.js → chunk-GSP44ENC.js} +2 -2
- package/dist/{chunk-DXYMTQZ4.js → chunk-GUFSG5TX.js} +2 -2
- package/dist/chunk-GYIZ4NXB.js +2 -0
- package/dist/{chunk-CQVDALWQ.js → chunk-GZIUDL6G.js} +2 -2
- package/dist/chunk-HCXEQRFF.js +18 -0
- package/dist/{chunk-2LJLEM5B.js → chunk-HEHOQQKH.js} +2 -2
- package/dist/{chunk-RNKRYK6B.js → chunk-HKGFPJ4T.js} +2 -2
- package/dist/chunk-HLZTEXRA.js +2 -0
- package/dist/{chunk-T2PBOVDI.js → chunk-HOENASQM.js} +2 -2
- package/dist/{chunk-PX6QNUYF.js → chunk-HVF5VBG6.js} +2 -2
- package/dist/{chunk-K2DZCH2K.js → chunk-HYO3NP5Q.js} +2 -2
- package/dist/{chunk-MRXBLYRE.js → chunk-I55I7XXP.js} +2 -2
- package/dist/{chunk-AQF35NGT.js → chunk-IDFEUFKS.js} +2 -2
- package/dist/{chunk-7G2WIVIX.js → chunk-IHGQTTVW.js} +2 -2
- package/dist/{chunk-P3UFF22M.js → chunk-IICPE7B2.js} +2 -2
- package/dist/{chunk-NT4NVEHU.js → chunk-IL676XCC.js} +2 -2
- package/dist/{chunk-OU6SDWAM.js → chunk-ILTDAWEF.js} +2 -2
- package/dist/chunk-IW5XQG5G.js +2 -0
- package/dist/chunk-IZDPJ2QI.js +2 -0
- package/dist/{chunk-J4HUBIVF.js → chunk-J66VOFW6.js} +2 -2
- package/dist/chunk-JFMEXGFE.js +2 -0
- package/dist/{chunk-DGM2RJ3I.js → chunk-JGKUET5J.js} +2 -2
- package/dist/{chunk-BM4OTGSY.js → chunk-JS4PGXMV.js} +2 -2
- package/dist/{chunk-OG5UK2K7.js → chunk-JTQVMR42.js} +2 -2
- package/dist/chunk-JWTGMPIT.js +80 -0
- package/dist/{chunk-3XQLJG7V.js → chunk-JYR66JN5.js} +2 -2
- package/dist/chunk-KLFEXGQA.js +2 -0
- package/dist/chunk-KYSDI3GE.js +5 -0
- package/dist/{chunk-LIWIV26I.js → chunk-L6PJPETJ.js} +2 -2
- package/dist/{chunk-6DO3VBLV.js → chunk-LDVT66YM.js} +2 -2
- package/dist/chunk-LEECKFCJ.js +2 -0
- package/dist/{chunk-BVR44XXB.js → chunk-LMZ5PRUV.js} +2 -2
- package/dist/{chunk-KFFQURUZ.js → chunk-LQRQN2XA.js} +2 -2
- package/dist/{chunk-YR7VRWNX.js → chunk-LXABEJX3.js} +2 -2
- package/dist/{chunk-ARGPDW2Y.js → chunk-M2O5NY6W.js} +2 -2
- package/dist/{chunk-7YZGSLW6.js → chunk-MNV5FSBW.js} +2 -2
- package/dist/{chunk-XFRHBAIT.js → chunk-MPQ4OTBM.js} +2 -2
- package/dist/{chunk-PJBYDCBQ.js → chunk-MV3CDXPI.js} +2 -2
- package/dist/{chunk-DK6MB565.js → chunk-MWN53KRN.js} +2 -2
- package/dist/chunk-N2ZSIIGR.js +117 -0
- package/dist/chunk-N5B2NILC.js +5 -0
- package/dist/{chunk-HW7FASEL.js → chunk-NJITK2GP.js} +2 -2
- package/dist/{chunk-DUDUIT5P.js → chunk-NOGJXYFO.js} +2 -2
- package/dist/chunk-NOYBFVJA.js +554 -0
- package/dist/chunk-NWQXSFFU.js +3 -0
- package/dist/chunk-ODDUPDP7.js +13 -0
- package/dist/chunk-OLIWTZI3.js +3 -0
- package/dist/{chunk-JO6FK3Q5.js → chunk-OLNV6I6U.js} +2 -2
- package/dist/{chunk-CXT3GZSQ.js → chunk-OR2E3AGZ.js} +2 -2
- package/dist/chunk-OSR2GEHQ.js +2 -0
- package/dist/{chunk-7MUHSZGN.js → chunk-OSSESPDX.js} +2 -2
- package/dist/{chunk-ND3BWIVN.js → chunk-OWOOWNJ5.js} +2 -2
- package/dist/{chunk-UEQORB2A.js → chunk-P42EIXTA.js} +2 -2
- package/dist/{chunk-PWEQ6CZZ.js → chunk-PJFGPYTU.js} +2 -2
- package/dist/{chunk-CNT4ND5O.js → chunk-PP7KNN7L.js} +2 -2
- package/dist/{chunk-C52Q3JEQ.js → chunk-PU7T5QYQ.js} +2 -2
- package/dist/{chunk-OY7PCALC.js → chunk-PWWAJSKV.js} +2 -2
- package/dist/{chunk-LXMW6ZAX.js → chunk-PZL5T7SU.js} +2 -2
- package/dist/{chunk-G47MFF47.js → chunk-QBE3YX64.js} +2 -2
- package/dist/{chunk-SGSPCEFC.js → chunk-QGVTFRY2.js} +2 -2
- package/dist/chunk-QOJONDS7.js +2 -0
- package/dist/chunk-QU5XRYB5.js +4 -0
- package/dist/{chunk-4ZCLDH6T.js → chunk-QUU5OBVK.js} +2 -2
- package/dist/{chunk-N4EFQIRX.js → chunk-RBLQNW26.js} +2 -2
- package/dist/chunk-RTQ7NEKG.js +81 -0
- package/dist/{chunk-XNF5T4T2.js → chunk-SQXRS7BG.js} +2 -2
- package/dist/chunk-SSK6LDPC.js +2 -0
- package/dist/chunk-SZHGTCPP.js +7 -0
- package/dist/chunk-T4N4P2K5.js +16 -0
- package/dist/{chunk-LFWB7TOJ.js → chunk-TA3QKLLU.js} +2 -2
- package/dist/chunk-TEBQMNVI.js +43 -0
- package/dist/chunk-TPFHAQ2G.js +2 -0
- package/dist/chunk-TQPCBMWT.js +5 -0
- package/dist/chunk-TQZV7KV4.js +2 -0
- package/dist/{chunk-FOP7HD6H.js → chunk-TRNAEQ6P.js} +2 -2
- package/dist/chunk-TY7CRN3Z.js +2 -0
- package/dist/{chunk-XDOEHEET.js → chunk-UHFYCMZO.js} +2 -2
- package/dist/{chunk-E6N6YTVM.js → chunk-UICY4GTQ.js} +2 -2
- package/dist/{chunk-AFRS7WJU.js → chunk-UVGEWT4Y.js} +2 -2
- package/dist/{chunk-IHGK3SZ7.js → chunk-UXW33INU.js} +2 -2
- package/dist/{chunk-RZWBTKXO.js → chunk-VMPRET3I.js} +2 -2
- package/dist/{chunk-DZA7MQMU.js → chunk-VNLGKHS6.js} +2 -2
- package/dist/chunk-VQILFTEH.js +2 -0
- package/dist/chunk-VUPHCS7Y.js +57 -0
- package/dist/{chunk-K63CAPS2.js → chunk-VVZSBTSU.js} +2 -2
- package/dist/{chunk-IH3K5J6K.js → chunk-VZRNID6A.js} +2 -2
- package/dist/{chunk-NSDPPUDY.js → chunk-W5OXRYGE.js} +2 -2
- package/dist/chunk-W6STWDQI.js +57 -0
- package/dist/chunk-W7CXK74K.js +2 -0
- package/dist/chunk-WB3WYIRE.js +4 -0
- package/dist/{chunk-WV6R37XV.js → chunk-WDNVY4E7.js} +2 -2
- package/dist/{chunk-Z2QB75BS.js → chunk-WIWY3CRX.js} +2 -2
- package/dist/chunk-WK46TNUM.js +3 -0
- package/dist/chunk-WNTFFKAX.js +12 -0
- package/dist/{chunk-U2MNECDU.js → chunk-WOIKCX6A.js} +2 -2
- package/dist/{chunk-5BJPJUXF.js → chunk-WUN6KBHV.js} +2 -2
- package/dist/chunk-WYCTJDVR.js +2 -0
- package/dist/chunk-WYPL7GF7.js +2 -0
- package/dist/{chunk-OFZVFIDF.js → chunk-XBGWL66K.js} +2 -2
- package/dist/{chunk-3T5U2EQ2.js → chunk-XDQMU3BT.js} +2 -2
- package/dist/{chunk-BZCRHP46.js → chunk-XFA4SSO3.js} +2 -2
- package/dist/{chunk-4KIPF45P.js → chunk-XGZEP6GR.js} +2 -2
- package/dist/chunk-XPDPNWTQ.js +368 -0
- package/dist/chunk-XRYABF57.js +8 -0
- package/dist/{chunk-KBIC6JHJ.js → chunk-YBGKCQIS.js} +2 -2
- package/dist/{chunk-5J3A6RBZ.js → chunk-YEN6CYC7.js} +2 -2
- package/dist/{chunk-OA2BO4DR.js → chunk-YF5IB2LF.js} +2 -2
- package/dist/{chunk-Q4MRRB3C.js → chunk-YI2AWIHC.js} +2 -2
- package/dist/{chunk-YCXQQ3YB.js → chunk-YPWBKGFU.js} +2 -2
- package/dist/{chunk-EJHNTAEE.js → chunk-YPWHBBIS.js} +2 -2
- package/dist/{chunk-FIO44MVK.js → chunk-YSH6U3L4.js} +2 -2
- package/dist/{chunk-HYU4W353.js → chunk-YU5DZUZI.js} +2 -2
- package/dist/chunk-YWO5DDRC.js +16 -0
- package/dist/{chunk-5Z2H76VD.js → chunk-YXPUP5G2.js} +2 -2
- package/dist/{chunk-H2RBDP5S.js → chunk-Z4CDXYNQ.js} +2 -2
- package/dist/{chunk-VJAD5WX5.js → chunk-ZF5KHH7C.js} +2 -2
- package/dist/chunk-ZOHS7AQV.js +21 -0
- package/dist/{chunk-YT4IQBET.js → chunk-ZTI4SBFV.js} +2 -2
- package/dist/cli-main.js +2 -2
- package/dist/code-MI6F2TTU.js +2 -0
- package/dist/code-result-json-FXALY4HE.js +2 -0
- package/dist/{command-descriptors-6INSCKLW.js → command-descriptors-P34VABY5.js} +144 -143
- package/dist/dataflow-4KEMJPC6.js +2 -0
- package/dist/dependence-slice-R7FPWD5M.js +2 -0
- package/dist/deps-7EMQUYUT.js +2 -0
- package/dist/direct-navigation-6YO234F2.js +3 -0
- package/dist/entry-map-KOOLR26E.js +2 -0
- package/dist/files-OPIPJIGZ.js +2 -0
- package/dist/hierarchy-QPD2CAER.js +2 -0
- package/dist/imports-M6HUXRXC.js +2 -0
- package/dist/index.js +1 -1
- package/dist/members-I5MEFOCT.js +2 -0
- package/dist/methods-5JYGGHXA.js +2 -0
- package/dist/output-continuation-command-UPQAAKBP.js +3 -0
- package/dist/postinstall.js +1 -1
- package/dist/project-reindex-UKKQ5PLS.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.d.ts +11 -0
- 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.d.ts +9 -0
- 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/query-service-fastpath.js +5 -5
- package/dist/query-service-server.js +3 -3
- package/dist/refs-PSU4JZZW.js +2 -0
- package/dist/refs-pagination-JG6CJMRC.js +2 -0
- package/dist/reindex-worker.js +64 -22
- package/dist/reindex.d.ts +3 -2
- package/dist/reindex.js +74 -32
- package/dist/runtime.d.ts +34 -2
- package/dist/runtime.js +4 -4
- 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/{scip-cli-H-n59izO.d.ts → scip-cli-DOerTq-R.d.ts} +42 -4
- package/dist/slice-HYRATV64.js +2 -0
- package/dist/surface-VTGDYWF5.js +2 -0
- package/dist/symbol-resolution-WD5EU5JE.js +2 -0
- package/dist/system-LRQNFOR2.js +2 -0
- package/dist/trace-F4B6OLL4.js +2 -0
- package/dist/typescript-mailbox-worker.js +1 -1
- package/dist/value-flow-VRPZY72V.js +2 -0
- package/dist/watch-server.js +3 -3
- package/package.json +1 -1
- package/dist/by-kind-XXGZGNZ6.js +0 -2
- package/dist/call-graph-VGY3R4L3.js +0 -2
- package/dist/chunk-3XZELASU.js +0 -2
- package/dist/chunk-63TFRBMB.js +0 -2
- package/dist/chunk-67FK5KGV.js +0 -3
- package/dist/chunk-6LS3IG2I.js +0 -13
- package/dist/chunk-6X4KO5A7.js +0 -11
- package/dist/chunk-743MEVFJ.js +0 -8
- package/dist/chunk-7Z4GMCHM.js +0 -117
- package/dist/chunk-ANCHW2R4.js +0 -57
- package/dist/chunk-BMKTDJI6.js +0 -16
- package/dist/chunk-BZYSGZRK.js +0 -2
- package/dist/chunk-C7WSQA6A.js +0 -21
- package/dist/chunk-CTO3TRX7.js +0 -2
- package/dist/chunk-DNPETNXT.js +0 -2
- package/dist/chunk-DZNWXJN2.js +0 -18
- package/dist/chunk-E7CJ6O72.js +0 -2
- package/dist/chunk-FLSVYEPL.js +0 -2
- package/dist/chunk-FSPENGSU.js +0 -4
- package/dist/chunk-FYCH2EYQ.js +0 -2
- package/dist/chunk-G6VV7ROY.js +0 -2
- package/dist/chunk-GSHTVE56.js +0 -3
- package/dist/chunk-IGBQVEHE.js +0 -2
- package/dist/chunk-IM23CSG5.js +0 -2
- package/dist/chunk-IQMGNIGY.js +0 -2
- package/dist/chunk-JLZWYDCZ.js +0 -4
- package/dist/chunk-JSHDCVUM.js +0 -81
- package/dist/chunk-L7WRUNKJ.js +0 -2
- package/dist/chunk-LGVTIZPV.js +0 -61
- package/dist/chunk-MFBVUQJZ.js +0 -2
- package/dist/chunk-MLTSTKXD.js +0 -5
- package/dist/chunk-MR4ZKWO6.js +0 -57
- package/dist/chunk-NODZYYGC.js +0 -2
- package/dist/chunk-NP4JFCLE.js +0 -133
- package/dist/chunk-NQXWWE6S.js +0 -8
- package/dist/chunk-O2VY47Y5.js +0 -325
- package/dist/chunk-PAZSBPJR.js +0 -3
- package/dist/chunk-PRLU3I7G.js +0 -79
- package/dist/chunk-QLWZUFDT.js +0 -2
- package/dist/chunk-SIGVQT43.js +0 -2
- package/dist/chunk-SRIZDEWX.js +0 -4
- package/dist/chunk-U7DOYZDH.js +0 -2
- package/dist/chunk-UAQQR55F.js +0 -2
- package/dist/chunk-VRJG7N3I.js +0 -453
- package/dist/chunk-W7HN6V4E.js +0 -7
- package/dist/chunk-WCIKJ2E3.js +0 -3
- package/dist/chunk-WEXQYJY3.js +0 -5
- package/dist/chunk-WOPZX5GM.js +0 -2
- package/dist/chunk-WZ7V4BQV.js +0 -2
- package/dist/chunk-XDQX6LDT.js +0 -4
- package/dist/chunk-XIPGCT3D.js +0 -5
- package/dist/chunk-XKM5D2XS.js +0 -16
- package/dist/chunk-Y2S4YNLH.js +0 -3
- package/dist/chunk-YA72ZUKO.js +0 -2
- package/dist/chunk-YBWE6J32.js +0 -43
- package/dist/chunk-YDTK77JP.js +0 -43
- package/dist/chunk-Z2KGMIL4.js +0 -2
- package/dist/chunk-Z67JOKRE.js +0 -554
- package/dist/chunk-ZMS4YCY7.js +0 -2
- package/dist/chunk-ZNW5A5VX.js +0 -3
- package/dist/code-AXLJBZ6T.js +0 -2
- package/dist/code-result-json-CTZHAQXJ.js +0 -2
- package/dist/dataflow-AFXY423Q.js +0 -2
- package/dist/dependence-slice-2G4X6VSJ.js +0 -2
- package/dist/deps-LMCAV5DO.js +0 -2
- package/dist/direct-navigation-2ONV22Y2.js +0 -3
- package/dist/entry-map-ZOC3VXO5.js +0 -2
- package/dist/files-WJQJLHMH.js +0 -2
- package/dist/hierarchy-ASNIHAX4.js +0 -2
- package/dist/imports-JICEKDKK.js +0 -2
- package/dist/members-C5H2K3MS.js +0 -2
- package/dist/methods-KZOZHSD4.js +0 -2
- package/dist/output-continuation-command-NX3RH3TP.js +0 -3
- package/dist/project-reindex-A2SXUH2H.js +0 -3
- package/dist/refs-ZOORVRQC.js +0 -2
- package/dist/refs-pagination-SRCUOYRD.js +0 -2
- package/dist/slice-NOTBWA7S.js +0 -2
- package/dist/surface-BTBCLKNA.js +0 -2
- package/dist/symbol-resolution-SVSMX4RN.js +0 -2
- package/dist/system-2EIUFP6B.js +0 -2
- package/dist/trace-BB2GHQPG.js +0 -2
- package/dist/value-flow-OA7AHSUG.js +0 -2
package/dist/chunk-Z67JOKRE.js
DELETED
|
@@ -1,554 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import{$a as ei,$b as ae,$c as Lf,$d as Ws,$e as Jf,Aa as Zr,Ab as Xi,Ac as yf,Ad as vr,Ae as qf,B as dl,Ba as Nt,Bb as af,Bc as bf,Be as Gf,C as ml,Cb as cf,Cc as Zi,Cd as Af,Ce as zf,Da as hl,Db as se,Dc as Bs,Dd as Ff,De as Kf,E as $p,Ea as Jp,Eb as lf,Ec as Sf,Ed as Cr,Ee as Wf,Fb as Sl,Fc as Ne,Fd as Nf,G as jp,Ga as yr,Gb as vl,Gc as $s,Gd as gn,Hb as br,Hc as xe,Ic as q,Id as Gs,Jc as fn,Kb as J,Kc as ai,Kd as Hn,La as Xp,Lb as Nn,Lc as vf,Ld as xr,M as Hp,Ma as Vi,Mb as K,Mc as ne,Md as zs,Na as An,Nb as uf,Nc as Qe,Oa as ge,Ob as Ns,Oc as Sr,Pa as Qp,Pb as Et,Pc as js,Qb as Gt,Qc as Cf,R as Up,Ra as qt,Rb as df,Rc as xf,Re as wl,Sa as Rt,Sc as Rf,Ta as mn,Tc as Hs,Td as _f,Te as Ll,Ub as ti,Uc as _t,Vb as _s,Vc as $n,Ve as Vf,W as qp,Wa as Zp,Wb as It,Wc as zt,Wd as Of,Xa as ef,Xb as ni,Xc as Ef,Xd as xl,Y as hr,Ya as yl,Yb as mf,Yc as If,Za as tf,Zc as wf,Zd as Ks,_a as Z,_b as Qi,_c as Cl,_d as Un,_e as Yf,ab as nf,ac as ri,ae as Bf,ba as Gp,bb as rf,bc as Os,be as Vs,c as Wi,cc as _n,cd as Pf,ce as $f,db as bl,dc as Me,dd as eo,de as to,e as Np,eb as of,ed as Df,ef as Xf,fb as Yi,fd as jn,fe as Rl,ff as Qf,ga as pl,gb as be,gd as Mf,ge as El,gf as Zf,h as _p,he as Il,i as ws,ia as Ps,ic as On,ie as qn,j as it,ja as fl,jc as Bn,je as jf,k as Fe,ka as zp,kc as pf,ke as Hf,la as Kp,lb as sf,lc as T,ld as Tf,le as Uf,m as un,ma as Ye,mb as N,mc as z,n as Ls,na as Je,nc as wt,o as dn,oa as Ct,ob as Ts,oc as Xe,p as Xr,pa as Ds,pb as dt,pc as Se,pe as no,qa as Wp,qb as Ji,qc as me,qe as Ys,ra as Vp,rb as $e,rc as je,s as Qr,sb as W,sc as ii,t as vt,tb as Fn,tc as ff,td as kf,u as Ve,ua as Yp,ub as V,uc as gf,ud as ci,ue as ui,va as Q,vb as ks,vc as oi,vd as Us,w as Op,wb as As,wc as si,wd as qs,x as ul,xa as gl,xb as Fs,xc as hf,xd as li,y as Bp,ya as xt,yb as Ce,yc as U,yd as Lt,za as Ms,zb as pn,zc as Le}from"./chunk-VRJG7N3I.js";import{existsSync as tw}from"fs";import{isAbsolute as eg,join as nw}from"path";function mt(e,t){let n=Pl(e,t,{allowMultiple:!1})[0]?.relativePath;return n||rg(e,t)}function Rr(e,t){return Pl(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function tg(e,t){let n=Pl(e,t,{allowMultiple:!0});return n.length===1?n[0].relativePath:null}function ng(e,t){let n=ei(e,t,{allowMultiple:!0,requirePathMatch:!0});return n.length===1?n[0].relativePath:null}function rg(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=eg(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=nw(e.config.projectRoot,r);return tw(i)?r:null}function Pl(e,t,n){let r=rg(e,t);if(r)return ei(e,r,n).filter(a=>a.relativePath===r);let i=t.replace(/\\/g,"/").replace(/^\.\//,""),o=eg(i)||i.includes("/"),s=ei(e,t,{...n,requirePathMatch:o});if(s.length===0){if(o)return[];let a=ne(e,t);return!a||e.isIgnored(a.relativePath)?[]:[{relativePath:a.relativePath,score:700}]}return s}function ig(e,t){let n=tg(e,t);if(!n)return[];let r=Bs(e,[n],{sort:!0});if(r.length===0)return[];let i=Math.max(0,Fn(W(e,n)).length-1),o=r.map(c=>({symbol:c.symbol,shortName:c.shortName,startLine:c.startLine,endLine:Math.min(c.endLine,i),signature:c.signature,children:[]})),s=new Map;for(let c of o)s.set(c.symbol,c);let a=[];for(let c=0;c<r.length;c++){let l=r[c],u=o[c];if(l.enclosingSymbol&&s.has(l.enclosingSymbol)){s.get(l.enclosingSymbol).children.push(u);continue}let d=null,m=1/0;for(let p of o)if(p!==u&&p.startLine<=u.startLine&&p.endLine>=u.endLine){if(p.startLine===u.startLine&&p.endLine===u.endLine&&!gf(p.symbol,u.symbol))continue;let g=p.endLine-p.startLine;g<m&&(m=g,d=p)}d?d.children.push(u):a.push(u)}return a}import{basename as dL,extname as $g}from"path";function pt(e,t){let n=V(e,t.relativePath);if(n.length===0)return!1;let r=z(t.symbol);if(!r)return!1;let i=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
|
|
3
|
-
`),o=Ce(r);return new RegExp(`^\\s*export\\s+(?:default\\s+)?(?:(?:async\\s+)?function\\s+${o}\\b|(?:abstract\\s+)?class\\s+${o}\\b|(?:interface|type|enum|namespace|module)\\s+${o}\\b|(?:const|let|var)\\s+${o}\\b)`,"m").test(i)?!0:rw(n,r)}function rw(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${Ce(t)}\\b`);return e.some(r=>n.test(r))}import{createHash as iw}from"crypto";import{isUtf8 as ow}from"buffer";import{TextDecoder as sw}from"util";var sg=new sw("utf-8",{fatal:!0});function Ml(e){return Ds(e.config.projectRoot)}function Js(e,t){let n=un(t),r;try{r=fl(e.config.projectRoot,n,{inputKind:"repository text file"})}catch(o){if(Je(o)||o instanceof pl)return null;throw o}let i=aw(r);return i===null?null:cg(n,r,i,ug(e),lg(e))}function ag(e,t={}){let n=[],r=Xs(e,t,i=>n.push(i));return{files:n,candidateFiles:r.candidateFiles,scannedBytes:r.scannedBytes,skippedBinaryPaths:r.skippedBinaryPaths,skippedUnreadablePaths:r.skippedUnreadablePaths,skippedOversizedPaths:r.skippedOversizedPaths}}function Xs(e,t,n){let r=Ml(e).filter(f=>!t.scope||f.includes(t.scope)),i=ug(e),o=lg(e),s=[],a=[],c=[],l=0,u=0,d={aligned:0,stale:0,unavailable:0},m=t.literalBytes?Buffer.isBuffer(t.literalBytes)?[t.literalBytes]:[...t.literalBytes]:[],p=m.length>0?Buffer.allocUnsafe(1024*1024):void 0;for(let f of r){let g,h,b=[],S=o.has(f);try{if(m.length>0){let x=m.length===1?zp(e.config.projectRoot,f,m[0],{inputKind:"repository text file",computeSha256:S,scratchBuffer:p}):Kp(e.config.projectRoot,f,m,{inputKind:"repository text file",computeSha256:S,scratchBuffer:p});if(!x.isUtf8Text){s.push(f);continue}l+=x.byteLength,u+=1,h=x.sha256;let v=Dl(f,h,i,o);if(d[v.state]+=1,b="matchedLiteralIndexes"in x?x.matchedLiteralIndexes:x.includesLiteral?[0]:[],b.length===0||!x.bytes)continue;g=x.bytes}else g=fl(e.config.projectRoot,f,{inputKind:"repository text file"})}catch(x){if(x instanceof pl){c.push(f);continue}if(Je(x))continue;a.push(f);continue}if(m.length===0&&!dg(g)){s.push(f);continue}if(m.length===0){l+=g.byteLength,u+=1,h=S?mg(g):void 0;let x=Dl(f,h,i,o);d[x.state]+=1}if(t.includeBytes&&!t.includeBytes(f,g))continue;let y=sg.decode(g);n(cg(f,g,y,i,o,h),b)}return{candidateFiles:r.length,scannedTextFiles:u,semanticFiles:d,scannedBytes:l,skippedBinaryPaths:s,skippedUnreadablePaths:a,skippedOversizedPaths:c}}function cg(e,t,n,r,i,o){let s=o??mg(t);return{relativePath:e,text:n,bytes:t.byteLength,freshness:{exactText:{state:"current",basis:"working-tree-read",sha256:s},semantic:Dl(e,s,r,i)}}}function Dl(e,t,n,r){if(!r.has(e))return{state:"unavailable",basis:"no-compiler-document"};let i=n.get(e);return!i||!t?{state:"unavailable",basis:"fingerprint-unavailable"}:{state:i===t?"aligned":"stale",basis:"indexed-input-fingerprint"}}function lg(e){return new Set(e.all(`SELECT documents.relative_path FROM documents WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`).map(t=>t.relative_path))}function ug(e){let t=new Map;if(!e.generation.metadataRaw)return t;let n=yr(e.generation.metadataRaw);if(n.kind!=="legacy"&&n.kind!=="supported")return t;let r=n.metadata.fingerprint;if(!og(r)||!Array.isArray(r.files))return t;for(let i of r.files)!og(i)||typeof i.path!="string"||typeof i.hash!="string"||t.set(i.path,i.hash);return t}function aw(e){return dg(e)?sg.decode(e):null}function dg(e){return!e.includes(0)&&ow(e)}function mg(e){return iw("sha256").update(e).digest("hex")}function og(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{SymbolInformation_Kind as ue}from"@c4312/scip";var Qs=new Map(Object.entries(ue).filter(([e,t])=>Number.isInteger(Number(e))&&typeof t=="string").map(([e,t])=>[Number(e),t])),pg=new Map([...Qs.entries()].map(([e,t])=>[t.toLowerCase(),e]));function ro(e){return Qs.get(e)??"Unknown"}function Kt(){return[ue.Function,ue.Method,ue.Macro,ue.Constructor,ue.Getter,ue.Setter,ue.StaticMethod,ue.SingletonMethod,ue.AbstractMethod,ue.ProtocolMethod,ue.TraitMethod]}function fg(){return[ue.Class,ue.Interface,ue.Struct,ue.Trait,ue.Type,ue.TypeAlias,ue.Enum,ue.Union,ue.Protocol]}function e4(){return[ue.Constant,ue.Variable,ue.Value,ue.Field,ue.Property,ue.StaticDataMember,ue.StaticField,ue.StaticProperty,ue.StaticVariable,ue.EnumMember]}function Pt(e,t,n={}){let r=Er(e,[t],{additive:n.additive,semantic:n.semantic,semanticEvidence:n.semanticEvidence}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(o=>Xe(o.symbol)||o.source==="ast-callsite"):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function Gn(e,t,n){return hn(e,[t],n).get(t.symbolId)??[]}function hn(e,t,n){let r=dw(e)?pw(e,t,{semantic:n.semantic!==!1,semanticEvidence:n.semanticEvidence}):mw(e,n.semanticEvidence);return typeof n.limit!="number"?new Map(t.map(i=>[i.symbolId,r.get(i.symbolId)??[]])):new Map(t.map(i=>[i.symbolId,(r.get(i.symbolId)??[]).slice(0,n.limit)]))}var cw=ge("caller-rows",{clearGroups:["whole-project"]}),lw=ge("targeted-caller-strategy",{clearGroups:["whole-project"]}),uw=2e4;function dw(e){return lw.get(e,()=>(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>uw)}function mw(e,t){return cw.get(e,()=>{let n=Le(e),r=Er(e,n,{semanticEvidence:t}),i=new Map;for(let a of n)i.set(a.symbol,a.symbolId);let o=new Map,s=new Map;for(let a of n){let c=r.get(a.symbolId);if(!(!c||c.length===0))for(let l of c){let u=i.get(l.symbol);if(u===void 0||u===a.symbolId)continue;let d=o.get(u);d||(d=[],o.set(u,d),s.set(u,new Set));let m=`${a.symbol}|${a.relativePath}`;s.get(u).has(m)||(s.get(u).add(m),d.push({symbol:a.symbol,file:a.relativePath,source:"caller-map-inversion",callEvidence:l.source}))}}return o})}function pw(e,t,n){let r=n.semantic&&n.semanticEvidence?t.flatMap(p=>{let f=fw(e,p);return f?[f]:[]}):[],i=new Map(r.map(p=>[p.symbolId,p])),o=n.semanticEvidence?.referenceMap(e,r)??new Map,s=Df(e,t),a=new Set(t.map(p=>p.symbol)),l=[...new Set(t.flatMap(p=>_n(e,"reverse",[p.relativePath])))].flatMap(p=>U(e,p)),u=new Map,d=hg(e,l);for(let p of l)for(let f of d.get(p.symbolId)??[]){if(!a.has(f.symbol))continue;let g=u.get(f.symbol)??[];g.push({symbol:p.symbol,file:p.relativePath,source:"caller-map-inversion",callEvidence:f.source}),u.set(f.symbol,g)}let m=new Map;for(let p of t){let f=[],g=new Set,h=S=>{if(S.symbol===p.symbol)return;let y=`${S.symbol}|${S.file}`;g.has(y)||(g.add(y),f.push(S))};for(let S of u.get(p.symbol)??[])h(S);for(let S of s.get(p.symbolId)??[])S.file!==p.relativePath&&h({symbol:S.enclosingSymbol??S.file,file:S.file,source:"resolved-reference"});let b=i.get(p.symbolId);if(b)for(let S of o.get(b.symbolId)??[]){if(S.file===p.relativePath||e.isIgnored(S.file))continue;let y=Ne(U(e,S.file),S.line);h({symbol:y?.symbol??S.file,file:S.file,source:"semantic-reference"})}m.set(p.symbolId,f)}return m}function fw(e,t){let n=Kt().join(", "),r=fg().join(", ");return e.get(`SELECT
|
|
4
|
-
d.id AS documentId,
|
|
5
|
-
gs.id AS symbolId,
|
|
6
|
-
gs.symbol,
|
|
7
|
-
d.relative_path AS relativePath,
|
|
8
|
-
COALESCE(der.start_line, c.start_line) AS startLine,
|
|
9
|
-
COALESCE(der.end_line, c.end_line) AS endLine,
|
|
10
|
-
COALESCE(gs.display_name, '') AS leaf,
|
|
11
|
-
NULL AS parentTypeName,
|
|
12
|
-
CASE WHEN gs.kind IN (${n}) OR gs.symbol LIKE '%().' THEN 1 ELSE 0 END AS isFunctionLike,
|
|
13
|
-
CASE WHEN gs.kind IN (${r}) THEN 1 ELSE 0 END AS isTypeLike,
|
|
14
|
-
gs.kind AS kind,
|
|
15
|
-
gs.documentation AS documentation,
|
|
16
|
-
gs.enclosing_symbol AS enclosingSymbol
|
|
17
|
-
FROM global_symbols gs
|
|
18
|
-
LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
19
|
-
LEFT JOIN chunks c ON c.document_id = der.document_id
|
|
20
|
-
JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
|
|
21
|
-
WHERE gs.id = ?
|
|
22
|
-
LIMIT 1`,t.symbolId)??null}function Er(e,t,n={}){if(t.length===0)return new Map;let r=n.additive??!1,i=[],o=[];for(let u of t)se(u.relativePath)&&Gt(e,u.relativePath)!==null?i.push(u):o.push(u);let s=new Map,a=new Map,c=u=>{for(let[d,m]of u){let p=s.get(d);p||(p=[],s.set(d,p));let f=a.get(d);f||(f=new Set,a.set(d,f));for(let g of m){let h=`${g.symbol}|${g.chunkId}`;f.has(h)||(f.add(h),p.push(g))}}};i.length>0&&c(hg(e,i)),n.semantic!==!1&&n.semanticEvidence&&c(vw(n.semanticEvidence.calleeMap(e,t)));let l=r?t:o;return l.length>0&&c(bw(e,l)),s}function hg(e,t){let n=new Map,r=gw(t,n),i=zt(e);for(let[o,s]of r){let a=Gt(e,o);if(!a)continue;let c=Sf(s);for(let l of a){let u=c.get(l.line);if(!u)continue;let d=hw(e,o,i,l);d&&d.symbol!==u.symbol&&n.get(u.symbolId).push({symbol:d.symbol,file:d.file,chunkId:l.line,source:"ast-callsite",callsiteLine:l.line})}}return n}function gw(e,t){let n=new Map;for(let r of e){let i=n.get(r.relativePath);i?i.push(r):n.set(r.relativePath,[r]),t.set(r.symbolId,[])}for(let r of n.values())r.sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine));return n}function hw(e,t,n,r){let i=ri(e,t,r.calleeLeaf);if(i){let a=_t(t,n.get(i.importedName)??[]).filter(c=>Fe(i.sourcePath,c.file));return a.length===1?a[0]:null}let o=_t(t,n.get(r.calleeLeaf)??[]);if(o.length===0)return null;let s=yw(e,t,o,r.calleeQualifier);return s||$n(e,t,o,r.memberAccess,r.calleeQualifier)}function yw(e,t,n,r){if(!r||se(t)!=="clojure")return null;let o=ae(e,t).filter(s=>s.kind==="namespace"&&s.localName===r&&s.sourcePath).map(s=>s.sourcePath);for(let s of o){let a=n.find(c=>Fe(s,c.file));if(a)return a}return n.find(s=>/`([^`]+)`\//.exec(s.symbol)?.[1]===r)??null}function bw(e,t){if(t.length===0)return new Map;let r=Tl(t.map(p=>p.documentId)).flatMap(p=>e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
|
|
23
|
-
FROM mentions m
|
|
24
|
-
JOIN chunks c ON m.chunk_id = c.id
|
|
25
|
-
WHERE m.role != 1
|
|
26
|
-
AND c.document_id IN (${p.map(()=>"?").join(",")})`,...p)),i=new Map;for(let p of r)i.has(p.document_id)||i.set(p.document_id,[]),i.get(p.document_id).push(p);let s=Tl(r.map(p=>p.symbol_id)).flatMap(p=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
|
|
27
|
-
COALESCE(der.document_id, def_chunk.document_id) AS document_id
|
|
28
|
-
FROM global_symbols gs
|
|
29
|
-
LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
30
|
-
LEFT JOIN (
|
|
31
|
-
SELECT m.symbol_id, MIN(c.document_id) AS document_id
|
|
32
|
-
FROM mentions m
|
|
33
|
-
JOIN chunks c ON m.chunk_id = c.id
|
|
34
|
-
WHERE m.role = 1
|
|
35
|
-
AND m.symbol_id IN (${p.map(()=>"?").join(",")})
|
|
36
|
-
GROUP BY m.symbol_id
|
|
37
|
-
) def_chunk ON def_chunk.symbol_id = gs.id
|
|
38
|
-
WHERE gs.id IN (${p.map(()=>"?").join(",")})`,...p,...p)),a=Tl([...t.map(p=>p.documentId),...s.flatMap(p=>p.document_id===null?[]:[p.document_id])]),c=new Map(a.flatMap(p=>e.all(`SELECT id, relative_path FROM documents
|
|
39
|
-
WHERE id IN (${p.map(()=>"?").join(",")})`,...p).map(f=>[f.id,f.relative_path]))),l=new Map;for(let p of s)l.has(p.symbol_id)||l.set(p.symbol_id,{symbol:p.symbol,file:p.document_id!==null?c.get(p.document_id)??"":""});let u=new Map,d=c,m=Sw(t);for(let[p,f]of m){let h=[...i.get(p)??[]].sort((x,v)=>x.start_line-v.start_line||x.end_line-v.end_line),b=[...f].sort((x,v)=>x.startLine-v.startLine||x.endLine-v.endLine),S=new Set,y=0;for(let x of b){for(;y<h.length&&h[y].start_line<=x.endLine;)S.add(h[y]),y+=1;for(let w of S)w.end_line<x.startLine&&S.delete(w);let v=new Set,C=[],R=null,E=()=>{if(R)return R;let w=d.get(x.documentId)??"",I=new Set;if(w){let k=vf(e,w),D=Math.max(0,x.startLine),F=Math.min(k.length-1,x.endLine);for(let L=D;L<=F;L+=1)for(let A of k[L])I.add(A)}return R=I,I};for(let w of S){if(w.symbol_id===x.symbolId)continue;let I=l.get(w.symbol_id);if(!I)continue;if(!(w.start_line>=x.startLine&&w.end_line<=x.endLine)){if(!(w.start_line<=x.endLine&&w.end_line>=x.startLine))continue;let L=z(I.symbol);if(!L||!E().has(L))continue}let D=`${I.symbol}|${w.chunk_id}`;v.has(D)||(v.add(D),C.push({...I,chunkId:w.chunk_id,source:"scip-chunk"}))}u.set(x.symbolId,C)}}return u}var gg=500;function Tl(e){let t=[...new Set(e)],n=[];for(let r=0;r<t.length;r+=gg)n.push(t.slice(r,r+gg));return n}function Sw(e){let t=new Map;for(let n of e){let r=t.get(n.documentId);r?r.push(n):t.set(n.documentId,[n])}return t}function vw(e){let t=new Map;for(let[n,r]of e){let i=[];for(let o of r)i.push({symbol:o.symbol,file:o.file,chunkId:-1,source:"semantic-callee",...o.callsiteLine===void 0?{}:{callsiteLine:o.callsiteLine}});t.set(n,i)}return t}var Cw=12,xw=280;function di(e,t,n,r){let i=Rw(e,t,n,r);if(i.size===0)return Lw();let o=[],s=new Set,a=(l,u,d,m)=>{if(u===t&&d<=r&&m>=n)return;let p=`${u}:${d}:${m}:${l}`;s.has(p)||(s.add(p),o.push({name:l,relativePath:u,startLine:d,endLine:m}))};for(let l of U(e,t))i.has(l.leaf)&&a(l.leaf,l.relativePath,l.startLine,l.endLine);for(let l of ae(e,t)){let u=l.localName;if(!u||!i.has(u)||!l.sourcePath||l.kind==="namespace")continue;let d=l.importedName==="default"?u:l.importedName;for(let m of qn(e,l.sourcePath,d,{maxReexportDepth:3}))a(u,m.relativePath,m.startLine,m.endLine)}o.sort(bg);let c=o.map(l=>{let u=Ew(e,l);return u?{...l,source:u}:null}).filter(l=>l!==null).slice(0,Cw);return kl(c)}function Zs(e,t=[]){return kl(Iw(e.flatMap(n=>n?.inline??[]),t))}function yg(e){return e?e.inline.reduce((t,n)=>t+n.name.length+n.source.length+32,0):0}function Rw(e,t,n,r){let i=K(e,t),o=new Set;if(!i)return o;for(let s=n;s<=r;s+=1)for(let a of i.identifiersByLine[s]??[])o.add(a);return o}function Ew(e,t){if(t.startLine!==t.endLine)return null;let n=(V(e,t.relativePath)[t.startLine]??"").trim();if(!n||n.length>xw)return null;let r=n.indexOf("=");if(r<0||n[r+1]===">")return null;let i=n.slice(r+1).replace(/(?:\/\/|#).*$/u,"").trim();if(!i||i.includes("${")||/\b(?:function|class|struct|interface|trait|enum|lambda)\b/u.test(i))return null;let s=i.replace(/(['"`])(?:\\.|(?!\1).)*\1/gu,"").replace(/\b(?:0[xX][\dA-Fa-f_]+|0[bB][01_]+|0[oO][0-7_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:[eE][+-]?\d+)?)n?\b/gu,""),a=new Set(["true","false","null","undefined","None","True","False"]);return(s.match(/[A-Za-z_][A-Za-z0-9_]*/gu)??[]).some(l=>!a.has(l))?null:n}function Iw(e,t){let n=new Map;for(let r of e){if(ww(r,t))continue;let i=`${r.relativePath}:${r.startLine}:${r.endLine}:${r.name}`;n.has(i)||n.set(i,{...r})}return[...n.values()].sort(bg)}function ww(e,t){return t.some(n=>n.relativePath===e.relativePath&&n.startLine<=e.startLine&&n.endLine>=e.endLine)}function bg(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||e.name.localeCompare(t.name)}function kl(e){return{coverage:"indexed-project-literal-values",inline:e}}function Lw(){return kl([])}var Pw=12,Dw=20,Fl=200,Nl=800,Mw=.9,Tw=64,kw=Qp("behavior-construct-ranges"),vg={if_statement:"branch",conditional_expression:"branch",ternary_expression:"branch",switch_statement:"branch",switch_expression:"branch",switch_case:"branch",case_statement:"branch",match_statement:"branch",match_expression:"branch",match_arm:"branch",for_statement:"loop",for_in_statement:"loop",for_of_statement:"loop",while_statement:"loop",do_statement:"loop",await_expression:"await",return_statement:"return",throw_statement:"throw",raise_statement:"throw",assignment_expression:"mutation",augmented_assignment_expression:"mutation",assignment:"mutation",pair:"shape",field_initializer:"shape",spread_element:"spread",dictionary_splat:"spread",catch_clause:"catch",except_clause:"catch",finally_clause:"finally"},oa=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],Cg=[...oa,"lifecycle"],xg=["loop","await","throw","mutation","spread","catch","finally","lifecycle"],Aw=new Set(["onBeforeMount","onBeforeUnmount","onMounted","onUnmounted","useEffect","useInsertionEffect","useLayoutEffect"]);var Rg=new Set(["object","object_pattern","dictionary","field_declaration_list","struct_expression","struct_pattern"]);function mi(e,t,n,r,i=[],o={}){let s=J(e,t);if(!s)return null;let a=V(e,t),c=ot(e,t,n,r,i),l=ca(e,t,c.startLine,c.endLine),u=l?.startLine??n,d=l?.endLine??r,m=(l?pi(s.rootNode,c.startLine,c.endLine):null)??br(s.rootNode,u,d);if(!m)return null;let p=Pg(m,a,u,d,i);if(!p||p.lines.length===0||p.lines.some(b=>b.text.length>Nl))return null;let f=Qw(a,u,d),g=Zw(p);if((o.requireSavings??!0)&&g>=f*Mw)return null;let h=oa.filter(b=>p.lines.some(S=>S.signals.includes(b)));return{...l?{callable:{name:l.name,startLine:l.startLine,endLine:l.endLine}}:{},representation:"outline",constructKind:p.constructKind,signature:p.signature,lines:p.lines,signals:h,testCases:q(t)==="test"?iL(a,u,d):[],coverage:{sourceStatements:p.sourceStatements,representedStatements:p.sourceStatements,copiedStatements:p.copiedStatements,omittedStatements:0},rawCharacters:f,outlineCharacters:g,candidateLines:p.sourceStatements,omittedLines:0}}function sa(e,t,n,r,i){if(i.length===0)return[];let o=J(e,t);if(!o)return[];let s=V(e,t),a=ot(e,t,n,r,i),c=ca(e,t,a.startLine,a.endLine),l=c?.startLine??n,u=c?.endLine??r,d=(c?pi(o.rootNode,a.startLine,a.endLine):null)??br(o.rootNode,l,u);if(!d)return[];let m=Pg(d,s,l,u,i);return m?m.lines.filter(p=>p.text.length<=Nl&&p.signals.some(f=>["branch","loop","catch","finally"].includes(f))&&i.some(f=>f>=p.line&&f<=p.endLine)):[]}function Eg(e,t,n,r){let i=J(e,t);if(!i)return null;let o=pi(i.rootNode,n,r)??br(i.rootNode,n,r);if(!o)return null;let s=[],a=Bl(o),c=[];return $l(o,o,l=>{if(oo.has(l.type)||Nw.has(l.type)){Ow(s,c,l);return}if(aa.has(l.type)){Bw(s,c,l);return}if(lo.has(l.type)){$w(s,c,l);return}uo.has(l.type)&&jw(s,l)}),{facts:zw(s),terminals:Lg(a),unsupported:c}}function ot(e,t,n,r,i=[]){let o=i.filter(u=>u>=n&&u<=r),s=kw.get(e,t,W(e,t)??"",()=>new Map),a=`${n}:${r}:${o.join(",")}`,c=s.get(a);if(c)return s.delete(a),s.set(a,c),{startLine:c[0],endLine:c[1]};let l=Fw(e,t,n,r,o);if(s.set(a,[l.startLine,l.endLine]),s.size>Tw){let u=s.keys().next().value;u!==void 0&&s.delete(u)}return l}function Fw(e,t,n,r,i){let o=J(e,t),s=[];if(i.length>0&&o){let u=[],d=i[0],m=d;for(let f of i)d=Math.min(d,f),m=Math.max(m,f);Tg(o.rootNode,d,m,f=>{Kw(f)&&f.startPosition.row>=n&&f.endPosition.row<=r&&i.every(g=>f.startPosition.row<=g&&f.endPosition.row>=g)&&u.push(f),zn.has(f.type)&&f.startPosition.row>=n&&f.endPosition.row<=r&&i.every(g=>f.startPosition.row<=g&&f.endPosition.row>=g)&&s.push(f)});let p=u.sort((f,g)=>f.endPosition.row-f.startPosition.row-(g.endPosition.row-g.startPosition.row)||f.startPosition.row-g.startPosition.row)[0];if(p)return{startLine:p.startPosition.row,endLine:p.endPosition.row}}let a=ca(e,t,n,r);if(a)return{startLine:a.startLine,endLine:a.endLine};if(i.length===0)return{startLine:n,endLine:r};let c=(K(e,t)?.callables??[]).filter(u=>u.startLine>=n&&u.endLine<=r&&i.every(d=>u.startLine<=d&&u.endLine>=d)).sort((u,d)=>u.endLine-u.startLine-(d.endLine-d.startLine)||u.startLine-d.startLine)[0];if(!o)return c?{startLine:c.startLine,endLine:c.endLine}:{startLine:n,endLine:r};let l=s.sort((u,d)=>u.endPosition.row-u.startPosition.row-(d.endPosition.row-d.startPosition.row)||u.startPosition.row-d.startPosition.row)[0];return l?{startLine:l.startPosition.row,endLine:l.endPosition.row}:c?{startLine:c.startLine,endLine:c.endLine}:{startLine:n,endLine:r}}function _l(e,t,n,r,i={}){if(r-n+1<(i.minimumBodyLines??Dw))return null;let s=Mg(e,t,n,r,[],!1);if(!s)return null;let a=s.candidates.map(b=>({...b,signals:b.signals.filter(S=>S!=="anchor"&&S!=="signature")})).filter(b=>b.signals.length>0);if(a.length===0)return null;let c=nL(a),l=a.filter(b=>b.text.length<=Fl);if(l.length===0)return null;let u=xg.filter(b=>(c[b]??0)>0),d=u.filter(b=>b!=="await"),m=s.shapes.reduce((b,S)=>b+S.fields.length,0);if(d.length===0&&!((c.await??0)>0&&m>0)&&m<3)return null;let p=rL(l,c),f=new Map;for(let b of u){let S=p.find(y=>y.signals.includes(b));S&&f.set(S.line,S)}if(f.size===0){let b=p.find(S=>S.signals.includes("branch"));b&&f.set(b.line,b)}let g=Math.min(10,Math.max(1,i.maxLines??f.size)),h=new Map;for(let b of f.values()){if(h.size>=g)break;h.set(b.line,b)}return h.size>=a.length&&s.shapes.length===0?null:{owner:s.callable?.name??null,startLine:n,endLine:r,lines:[...h.values()].sort((b,S)=>b.line-S.line),shapes:s.shapes,signalCounts:c,candidateLines:a.length,omittedLines:a.length-h.size}}function yn(e,t,n,r){let i=Mg(e,t,n,r,[],!1);return i?new Map(i.candidates.map(o=>[o.line,o.signals.filter(s=>s!=="lifecycle")])):new Map}var zn=new Set(["arrow_function","constructor_declaration","function_declaration","function_definition","function_expression","generator_function","generator_function_declaration","function_item","lambda","lambda_expression","method","method_declaration","method_definition"]),ft=new Set(["block","body","compound_statement","declaration_list","statement_block"]),oo=new Set(["if_expression","if_statement","unless","unless_statement"]),Nw=new Set(["conditional_expression","ternary_expression"]),aa=new Set(["do_statement","enhanced_for_statement","for_expression","for_in_statement","for_of_statement","for_statement","loop_expression","while_statement"]),lo=new Set(["match_expression","match_statement","switch_expression","switch_statement"]),Ig=new Set(["case_statement","match_arm","switch_case","switch_default"]),uo=new Set(["try_expression","try_statement"]),na=new Set(["catch_clause","except_clause","rescue"]),ao=new Set(["ensure","finally_clause"]),so=new Set(["else","else_clause"]),wg=new Set(["raise_statement","return_statement","throw_statement"]),_w=new Set(["block_comment","comment","line_comment"]);function Ow(e,t,n){let r=n.childForFieldName("condition")??Hl(n),i=n.childForFieldName("consequence")??n.childForFieldName("body")??n.namedChildren.find(c=>ft.has(c.type)),o=n.childForFieldName("alternative")??n.namedChildren.find(c=>so.has(c.type));if(!r||!i){t.push(jl(n,"conditional-fields-unresolved"));return}let s=Vt(r,"predicate",r.text),a=Vt(i,Sg(i),"consequence");if(Wt(e,s,a,"predicate-consequence",{branchRole:"consequence"}),ra(e,s,i,"consequence"),o){let c=Vt(o,Sg(o),"alternative");Wt(e,s,c,"predicate-alternative",{branchRole:"alternative"}),ra(e,s,o,"alternative");return}Wt(e,s,Ol(s,"otherwise continue"),"predicate-fallthrough",{branchRole:"fallthrough"})}function Bw(e,t,n){let r=n.childForFieldName("body")??n.namedChildren.find(s=>ft.has(s.type));if(!r){t.push(jl(n,"loop-body-unresolved"));return}let i=n.childForFieldName("condition"),o=Vt(i??n,"predicate",i?.text??Ot(n,r));Wt(e,o,Vt(r,"outcome","iteration"),"loop-iteration",{branchRole:"iteration"}),ra(e,o,r,"iteration"),Wt(e,o,Ol(o,"loop exits"),"loop-exit",{branchRole:"exit"})}function $w(e,t,n){let r=n.childForFieldName("body")??n.namedChildren.find(c=>ft.has(c.type)),i=n.childForFieldName("value")??n.childForFieldName("condition")??n.childForFieldName("subject")??Hl(n),o=Uw(r??n);if(!i||o.length===0){t.push(jl(n,"switch-cases-unresolved"));return}let s=Vt(i,"predicate",i.text),a=!1;for(let c of o){let l=Gw(c);a||=l;let u=Ot(c,c.namedChildren.find(d=>ia(d)));Wt(e,s,Vt(c,"outcome",u||(l?"default":"case")),l?"predicate-default":"predicate-case",{branchRole:l?"default":"case"}),ra(e,s,c,l?"default":"case")}a||Wt(e,s,Ol(s,"no case matched"),"predicate-fallthrough",{branchRole:"fallthrough"})}function jw(e,t){let n=Vt(t,"scope","try");for(let r of qw(t)){let i=ao.has(r.type),o=Vt(r,"handler",i?"finally":Ot(r,ea(r)));Wt(e,n,o,i?"finally-cleanup":"exception-handler",{branchRole:i?"finally":"catch"}),Hw(e,o,r,i?"finally":"catch")}}function Hw(e,t,n,r){for(let i of Bl(n)){let o=i.label.startsWith("throw")||i.label.startsWith("raise")?"throw":"return";Wt(e,t,i,o==="throw"?"handler-throw":"handler-return",{branchRole:r,terminalKind:o})}}function ra(e,t,n,r){for(let i of Bl(n)){let o=i.label.startsWith("throw")||i.label.startsWith("raise")?"throw":"return";Wt(e,t,i,o==="throw"?"predicate-throw":"predicate-return",{branchRole:r,terminalKind:o})}}function Wt(e,t,n,r,i){e.push({controller:t,outcome:n,subtype:r,attributes:i})}function Vt(e,t,n){return{kind:t,label:co(n).slice(0,Nl),startLine:e.startPosition.row,endLine:e.endPosition.row,implicit:!1}}function Ol(e,t){return{...e,kind:"outcome",label:t,implicit:!0}}function Sg(e){return wg.has(e.type)?"terminal":"outcome"}function Bl(e){let t=[];return $l(e,e,n=>{wg.has(n.type)&&t.push(Vt(n,"terminal",n.text))}),Lg(t)}function $l(e,t,n){n(t);for(let r of t.namedChildren)r!==e&&zn.has(r.type)||$l(e,r,n)}function Uw(e){let t=[],n=r=>{for(let i of r.namedChildren)lo.has(i.type)||(Ig.has(i.type)?t.push(i):n(i))};return n(e),t}function qw(e){let t=[],n=r=>{for(let i of r.namedChildren)uo.has(i.type)||(na.has(i.type)||ao.has(i.type)?t.push(i):zn.has(i.type)||n(i))};return n(e),t}function Gw(e){let t=Ot(e,e.namedChildren.find(n=>ia(n))).trim();return e.type==="switch_default"||/^(?:default\b|_\s*=>)/u.test(t)}function jl(e,t){return{startLine:e.startPosition.row,endLine:e.endPosition.row,reason:t}}function zw(e){let t=new Map;for(let n of e)t.set(`${n.controller.startLine}\0${n.controller.endLine}\0${n.outcome.startLine}\0${n.outcome.endLine}\0${n.subtype}\0${n.outcome.label}`,n);return[...t.values()]}function Lg(e){let t=new Map;for(let n of e)t.set(`${n.startLine}\0${n.endLine}\0${n.kind}\0${n.label}`,n);return[...t.values()]}function Kw(e){return zn.has(e.type)||aa.has(e.type)||lo.has(e.type)||uo.has(e.type)||na.has(e.type)||ao.has(e.type)}function Pg(e,t,n,r,i){let s=pi(e,n,r)??e,a=ea(s),c=[],l=0,u=0,d=(C,R,E,w,I=!1,k=!0)=>{let D=I?E.trim():co(E);if(!D)return;let F=Math.max(n,C.startPosition.row),L=Math.min(r,C.endPosition.row);c.push({line:F,endLine:Math.max(F,L),depth:R,signals:oa.filter(A=>w.includes(A)||A==="anchor"&&i.some(P=>P>=F&&P<=L)),text:D,copied:I}),k&&(l+=1,I&&(u+=1))},m=(C,R)=>{for(let E of C.namedChildren)v(E,R)},p=(C,R)=>{if(oo.has(C.type)){f(C,R,"else if");return}if(so.has(C.type)){let E=C.namedChildren.find(I=>oo.has(I.type));if(E){f(E,R,"else if");return}d(C,R,"else",["branch"],!1,!1);let w=ea(C)??C.namedChildren.find(I=>ft.has(I.type));if(w)v(w,R+1);else for(let I of C.namedChildren)v(I,R+1);return}d(C,R,"else",["branch"],!1,!1),v(C,R+1)},f=(C,R,E=C.type.startsWith("unless")?"unless":"if")=>{let w=C.childForFieldName("condition")??Hl(C),I=C.childForFieldName("consequence")??C.childForFieldName("body")??C.namedChildren.find(F=>ft.has(F.type)),k=C.childForFieldName("alternative")??C.namedChildren.find(F=>so.has(F.type)),D=w?w.text:Ot(C,I);d(C,R,`${E} ${Jw(D)}`,io(w,["branch"])),I&&v(I,R+1),k&&p(k,R)},g=(C,R)=>{let E=C.childForFieldName("body")??C.namedChildren.find(w=>ft.has(w.type));d(C,R,Ot(C,E),io(C,["loop"])),E&&v(E,R+1)},h=(C,R)=>{let E=C.childForFieldName("body")??C.namedChildren.find(w=>ft.has(w.type));d(C,R,Ot(C,E),io(C,["branch"])),E&&v(E,R+1)},b=(C,R)=>{let E=C.namedChildren.find(w=>ia(w));d(C,R,Ot(C,E),["branch"],!1,!1);for(let w of C.namedChildren)(w===E||ia(w))&&v(w,R+1)},S=(C,R)=>{d(C,R,"try",[],!1);for(let E of C.namedChildren)ft.has(E.type)?v(E,R+1):(na.has(E.type)||ao.has(E.type))&&v(E,R)},y=(C,R,E)=>{let w=C.childForFieldName("body")??C.namedChildren.find(k=>ft.has(k.type)),I=E==="finally"?"finally":Ot(C,w);d(C,R,I,[E],!1,!1),w&&v(w,R+1)},x=(C,R)=>{let E=ea(C);d(C,R,Ot(C,E),io(C,["binding"])),E&&v(E,R+1)},v=(C,R)=>{if(C.startPosition.row>r||C.endPosition.row<n||_w.has(C.type)||C.type==="empty_statement")return;if(ft.has(C.type)){m(C,R);return}if(oo.has(C.type)){f(C,R);return}if(aa.has(C.type)){g(C,R);return}if(lo.has(C.type)){h(C,R);return}if(Ig.has(C.type)){b(C,R);return}if(uo.has(C.type)){S(C,R);return}if(na.has(C.type)){y(C,R,"catch");return}if(ao.has(C.type)){y(C,R,"finally");return}if(so.has(C.type)){p(C,R);return}if(zn.has(C.type)){x(C,R);return}let w=!Dg(C)||Xw(C);d(C,R,C.text,io(C),w)};return v(a&&a!==s?a:s,0),l===0?null:{constructKind:Yw(s),signature:Vw(s,a,t,n),lines:c,sourceStatements:l,copiedStatements:u}}function pi(e,t,n){let r=e.namedChildren.filter(i=>i.startPosition.row<=t&&i.endPosition.row>=n);for(let i of r.sort(Ww)){let o=pi(i,t,n);if(o)return o}return zn.has(e.type)&&e.startPosition.row<=t&&e.endPosition.row>=n?e:null}function Ww(e,t){return e.endPosition.row-e.startPosition.row-(t.endPosition.row-t.startPosition.row)||e.startPosition.row-t.startPosition.row}function ea(e){return e.childForFieldName("body")??e.childForFieldName("consequence")??e.namedChildren.find(t=>ft.has(t.type))??null}function Vw(e,t,n,r){let i=Ot(e,t);return i||(n[r]??e.text).trim()}function Yw(e){return e.type.includes("constructor")?"constructor":e.type.includes("method")||e.type==="method"?Al(e,new Set(["class_body","class_declaration","class_definition"]))?"class method":"object method":e.type==="arrow_function"||e.type==="function_expression"||e.type==="lambda"?Al(e,new Set(["object","pair"]))?"object member":"function value":e.type.includes("function")?Al(e,zn)?"nested function":"module function":"source construct"}function Al(e,t){let n=e.parent;for(;n;){if(t.has(n.type))return!0;n=n.parent}return!1}function Hl(e){return e.namedChildren.find(t=>!ft.has(t.type)&&!so.has(t.type))??null}function Ot(e,t){if(!t)return co(e.text);let n=Math.max(0,t.startIndex-e.startIndex);return co(e.text.slice(0,n)).replace(/[:{]\s*$/u,"").trim()}function Jw(e){let t=co(e);return t.startsWith("(")&&t.endsWith(")")?t.slice(1,-1).trim():t}function co(e){return e.trim().replace(/\r?\n[\t ]*/gu," ")}function io(e,t=[]){let n=new Set(t);return e&&mo(e,r=>{let i=vg[r.type];i&&n.add(i),r.type==="call_expression"&&(n.add("call"),kg(r)&&n.add("shape")),Ul.has(r.type)&&n.add("binding")}),oa.filter(r=>n.has(r))}function Xw(e){let t=!1;return mo(e,n=>{t||!n.text.includes(`
|
|
40
|
-
`)||/(?:string|template|heredoc|raw_string)/u.test(n.type)&&(t=!0)}),t}function ia(e){return ft.has(e.type)||oo.has(e.type)||aa.has(e.type)||lo.has(e.type)||uo.has(e.type)||zn.has(e.type)||Dg(e)}function Dg(e){return/(?:statement|declaration|expression|assignment|return|throw|raise|break|continue|yield|with_item)$/u.test(e.type)||Ul.has(e.type)}function Qw(e,t,n){let r=0;for(let i=t;i<=n;i+=1)r+=(e[i]?.length??0)+10;return r}function Zw(e){return e.constructKind.length+e.signature.length+80+e.lines.reduce((t,n)=>t+n.text.length+n.depth*2+10,0)}function Mg(e,t,n,r,i,o){let s=J(e,t);if(!s)return null;let a=V(e,t),c=ca(e,t,n,r),l=o?c?.startLine??n:n,u=o?c?.endLine??r:r,m=(c?.startLine===l&&c.endLine===u?pi(s.rootNode,l,u):null)??br(s.rootNode,l,u);if(!m)return null;let p=new Map,f=new Map,g=new Map,h=(y,x)=>{if(y<l||y>u)return;let v=p.get(y)??new Set;v.add(x),p.set(y,v)};c&&h(c.startLine,"signature");for(let y of i)h(y,"anchor");mo(m,y=>{let x=vg[y.type];if(x&&h(y.startPosition.row,x),x==="shape"&&eL(f,y,m,l,u),y.type==="call_expression"){let C=(y.childForFieldName("function")??y.namedChild(0))?.text.split(".").at(-1);if(kg(y)){h(y.startPosition.row,"shape");let R=ta(y.text);R.length<=Fl&&g.set(y.startPosition.row,R)}if(C&&Aw.has(C)){h(y.startPosition.row,"lifecycle");let R=ta(y.text);R.length<=Fl&&g.set(y.startPosition.row,R)}}Ul.has(y.type)&&h(y.startPosition.row,"binding")});let b=K(e,t);for(let y of b?.callSites??[])y.line<l||y.line>u||(h(y.line,"call"),y.calleeLeaf==="catch"&&h(y.line,"catch"));let S=[...p.entries()].sort(([y],[x])=>y-x).map(([y,x])=>({line:y,signals:Cg.filter(v=>x.has(v)),text:g.get(y)??ta(a[y]??"")})).filter(y=>y.text.length>0||y.signals.includes("anchor"));return{...c?{callable:c}:{},rangeStart:l,rangeEnd:u,sourceLines:a,candidates:S,shapes:[...f.values()].sort((y,x)=>y.startLine-x.startLine)}}function eL(e,t,n,r,i){if(t.startPosition.row<r||t.endPosition.row>i)return;let o=t.childForFieldName("key")??t.childForFieldName("name")??t.namedChild(0),s=ta(o?.text??"");if(!s||s.includes(`
|
|
41
|
-
`)||s.length>60)return;let a=tL(t,n);if(a.startPosition.row<r||a.endPosition.row>i)return;let c=`${a.startPosition.row}:${a.endPosition.row}`,l=e.get(c)??{startLine:a.startPosition.row,endLine:a.endPosition.row,fields:[]};l.fields.some(u=>u.name===s&&u.line===t.startPosition.row)||l.fields.push({name:s,line:t.startPosition.row}),e.set(c,l)}function tL(e,t){let n=e.parent;for(;n&&n!==t.parent;){if(Rg.has(n.type))return n;if(n===t)break;n=n.parent}return e.parent??e}function ca(e,t,n,r){return K(e,t)?.callables.filter(i=>i.startLine<=n&&i.endLine>=r).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine)||i.startLine-o.startLine)[0]}function mo(e,t){t(e);for(let n of e.namedChildren)mo(n,t)}function Tg(e,t,n,r){r(e);for(let i of e.namedChildren)i.startPosition.row>t||i.endPosition.row<n||Tg(i,t,n,r)}function ta(e){return e.trim().replace(/\s+/gu," ")}function kg(e){if(e.type!=="call_expression")return!1;let t=e.childForFieldName("arguments")??e.namedChildren.find(r=>r.type==="arguments"||r.type==="argument_list");if(!t)return!1;let n=!1;return mo(t,r=>{Rg.has(r.type)&&(n=!0)}),n}function nL(e){let t={};for(let n of Cg){let r=e.filter(i=>i.signals.includes(n)).length;r>0&&(t[n]=r)}return t}function rL(e,t){let n=new Map;for(let o of e){let s=o.signals.join(",");n.set(s,(n.get(s)??0)+1)}let r=new Set(xg),i=o=>{let s=n.get(o.signals.join(","))??1,a=Math.min(...o.signals.map(u=>t[u]??1)),c=o.signals.some(u=>r.has(u))?3:1,l=Math.max(0,o.signals.length-1)*1e3;return c*(1e3/s+1e3/a)+l};return[...e].sort((o,s)=>i(s)-i(o)||s.line-o.line)}var Ul=new Set(["lexical_declaration","variable_declarator","const_item","static_item","let_declaration","assignment"]);function iL(e,t,n){let r=[],i=/\b(?:describe|it|test)(?:\.(?:only|skip|todo))?\s*\(\s*(['"`])([^'"`]+)\1/u;for(let o=t;o<=n;o+=1){let s=i.exec(e[o]??"")?.[2];if(!(!s||r.includes(s))&&(r.push(s),r.length>=Pw))break}return r}var oL=new Set(["arrow_function","class_declaration","constructor_declaration","field_definition","function_declaration","function_definition","function_expression","function_item","generator_function_declaration","generator_function","lexical_declaration","method","method_declaration","method_definition","object_method","variable_declaration"]);function fi(e,t,n){let r=J(e,t)?.rootNode??null,i=sL(r,n);if(!i)return null;let o=V(e,t);if(o.length===0)return null;let s=Math.max(0,i.startPosition.row),a=i.endPosition.column===0?i.endPosition.row-1:i.endPosition.row;return{type:i.type,startLine:s,endLine:Math.min(o.length-1,Math.max(s,a))}}function po(e,t,n,r,i){let o=ot(e,t,r,i,[n]),s=o.startLine===o.endLine&&/(?:=>|\(|\{|\[|,)\s*$/u.test(V(e,t)[o.startLine]??"");if(!s&&(o.startLine>r||o.endLine<i))return o;let a=fi(e,t,n);return s&&a?{startLine:a.startLine,endLine:a.endLine}:a&&a.startLine>=r&&a.endLine<=i?{startLine:a.startLine,endLine:a.endLine}:{startLine:r,endLine:i}}function sL(e,t){if(!e||!Ng(e,t))return null;let n=Fg(e,t);for(;n;){if(oL.has(n.type))return n;n=n.parent}return null}function Fg(e,t){let n=e.namedChildren.filter(r=>Ng(r,t)).sort((r,i)=>Ag(r)-Ag(i));return n.length>0?Fg(n[0],t):e}function Ng(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function Ag(e){return e.endIndex-e.startIndex}var aL=new Set(["call","call_expression","command","command_call","function_call_expression","invocation_expression","macro_invocation","method_call","method_invocation","new_expression","object_creation_expression"]);function la(e,t,n,r){if(!Number.isSafeInteger(n)||n<0)return null;if(!Number.isSafeInteger(r)||r<0)throw new RangeError(`contextLines must be a non-negative safe integer; received ${r}`);let i=V(e,t);if(i.length===0||n>=i.length)return null;let o=Math.max(0,n-r),s=Math.min(i.length-1,n+r);return{relativePath:t,startLine:o,endLine:s,focusLine:n,source:i.slice(o,s+1).join(`
|
|
42
|
-
`)}}function _g(e,t,n,r,i){let o=la(e,t,n,r);if(!o)return null;let s=J(e,t)?.rootNode??null;if(!s)return{...o,kind:"bounded-context"};let a=cL(s,n,i);if(a.length!==1)return{...o,kind:a.length===0?"non-call-reference":"bounded-context"};let c=a[0],l=V(e,t),u=Math.max(0,c.startPosition.row),d=c.endPosition.column===0?c.endPosition.row-1:c.endPosition.row,m=Math.min(l.length-1,Math.max(u,d));return{relativePath:t,startLine:u,endLine:m,focusLine:n,source:l.slice(u,m+1).join(`
|
|
43
|
-
`),kind:"complete-call-expression"}}function Og(e,t,n,r,i){if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`maxLines must be a positive safe integer; received ${i}`);let o=V(e,t);if(o.length===0||n<0||n>=o.length)return null;let s=Math.min(o.length-1,r,n+i-1);return{relativePath:t,startLine:n,endLine:s,focusLine:n,source:o.slice(n,s+1).join(`
|
|
44
|
-
`)}}function Kn(e,t,n,r,i=6){if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`maxLines must be a positive safe integer; received ${r}`);let o=V(e,t);if(o.length===0||n<0||n>=o.length)return null;let s=fi(e,t,n);if(!s){let g=la(e,t,n,i);return g?{...g,unitType:null,unitStartLine:g.startLine,unitEndLine:g.endLine,omittedLines:0}:null}let a=s.startLine,c=s.endLine,l=c-a+1,u=Math.min(l,r),d=n-a-Math.floor(u/2),m=Math.max(0,Math.min(l-u,d)),p=a+m,f=p+u-1;return{relativePath:t,startLine:p,endLine:f,focusLine:n,source:o.slice(p,f+1).join(`
|
|
45
|
-
`),unitType:s.type,unitStartLine:a,unitEndLine:c,omittedLines:l-u}}function cL(e,t,n){let r=[];return Bg(e,t,n,r),r.filter(i=>!r.some(o=>o!==i&&o.startIndex>=i.startIndex&&o.endIndex<=i.endIndex))}function Bg(e,t,n,r){if(uL(e,t)){aL.has(e.type)&&lL(e)===n&&r.push(e);for(let i of e.namedChildren)Bg(i,t,n,r)}}function lL(e){let t=e.childForFieldName("function")??e.childForFieldName("constructor")??e.childForFieldName("method")??e.childForFieldName("name")??e.namedChild(0);return t?t.text.match(/[\p{L}_$][\p{L}\p{N}_$!?-]*/gu)?.at(-1)??null:null}function uL(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function jg(e,t,n={}){let{context:r=0}=n,i=Jg(t);if(i)return Xg(e,i.filePath,i.startLine,i.endLine,r);let o=Vg(e,t);if(o)return zg(e,o);let s=ne(e,t);return s?fo(e,s,r):null}function K4(e,t,n={}){if(t.length===0)throw new RangeError("code requires at least one selector.");if(t.length>24)throw new RangeError(`code accepts at most ${24} selectors per complete packet; received ${t.length}.`);let r=n.context??0,i=n.members??"exported",o=t.map(c=>mL(e,c,r,i)),s=o.flatMap(c=>c.results),a=s.map(c=>({relativePath:c.relativePath,startLine:c.startLine,endLine:c.endLine}));return{requested:t.length,matched:o.filter(c=>c.status==="matched").length,ambiguous:o.filter(c=>c.status==="ambiguous").length,missing:o.filter(c=>c.status==="missing").length,entries:o,bindingClosure:Zs(s.map(c=>c.bindingClosure),a)}}function mL(e,t,n,r){let i=Jg(t);if(i){let u=Xg(e,i.filePath,i.startLine,i.endLine,n);return u?pL(e,t,u,n):ql(e,t,"definition-source-unreadable")}let o=Vg(e,t);if(o)return gL(e,t,o,n,r);let s=Qe(e,t);if(!s.match)return ql(e,t,"definition-not-found");let a=EL(e,s),c=a.map(Yg);if(s.total>1){let u=s.total<=4&&a.length===s.total;return{selector:t,status:"ambiguous",kind:"source",totalCandidates:s.total,results:u?a.flatMap(d=>{let m=fo(e,d,n);return m?[m]:[]}):[],definitions:[],candidates:c,omittedCandidates:Math.max(0,s.total-c.length),suggestions:[]}}let l=fo(e,s.match,n);return l?RL(t,l):ql(e,t,"definition-source-unreadable")}function pL(e,t,n,r){let i=U(e,n.relativePath).filter(l=>!Hg(l,n.relativePath)),o=fL(e,n,i),s=Gg(o.map(l=>fo(e,l,r)).filter(l=>l!==null)).filter(l=>!Wg(n,l)),a=new Set(s.map(l=>l.symbol)),c=o.filter(l=>!a.has(l.symbol)&&!(n.startLine<=l.startLine&&n.endLine>=l.endLine)).map(Yg);return{selector:t,status:"matched",kind:"source",totalCandidates:1,results:[n,...s],definitions:[],candidates:[],omittedCandidates:0,suggestions:[],rangeCoverage:{basis:"requested-range-and-same-file-call-closure",referencedDefinitions:o.length,returnedDefinitions:o.length-c.length,returnedBodies:s.length,omittedDefinitions:c.length,omittedLedger:c}}}function fL(e,t,n){if(!go(t.freshness))return[];if(n.length===0)return[];let r=Er(e,n,{additive:!1,semantic:!1}),i=new Map;for(let s of n){let a=i.get(s.symbol)??[];a.push(s),i.set(s.symbol,a)}let o=new Map;for(let s of n)if(!(s.endLine<t.startLine||s.startLine>t.endLine)){for(let a of r.get(s.symbolId)??[])if(a.file===t.relativePath&&!(a.source==="ast-callsite"&&(a.chunkId<t.startLine||a.chunkId>t.endLine)))for(let c of i.get(a.symbol)??[])o.set(c.symbolId,c)}return qg(e,[...o.values()],n)}function gL(e,t,n,r,i){let o=n.relativePath,s=yL(e,o),a=go(n.freshness)?U(e,o).filter(g=>!Hg(g,o)):[],c=a.filter(g=>pt(e,g)),l=c.length>0?c:hL(s,a),u=i==="all"?[]:qg(e,l,a),d=i==="all"||a.length===0?[zg(e,n)]:Gg(u.map(g=>fo(e,g,r)).filter(g=>g!==null)),m=SL(s,d),p=vL(o,s,d),f=CL(s);return{selector:t,status:"matched",kind:"file-source",totalCandidates:1,results:d,definitions:[],candidates:[],omittedCandidates:0,suggestions:[],fileCoverage:{members:i,basis:i==="all"||a.length===0?"complete-file-source":c.length>0?"explicit-exports-and-same-file-reference-closure":"top-level-and-same-file-reference-closure",totalDefinitions:f,returnedDefinitions:m,returnedBodies:d.length,omittedDefinitions:Math.max(0,f-m),omittedLedger:p}}}function hL(e,t){let n=new Set(e.map(r=>r.symbol));return t.filter(r=>n.has(r.symbol))}function yL(e,t){return ig(e,t).flatMap(n=>bL(n,t)?n.children:[n])}function Hg(e,t){return Ug(t).has(e.leaf)}function bL(e,t){return Ug(t).has(z(e.symbol))}function Ug(e){let t=dL(e);return new Set([t,t.slice(0,Math.max(0,t.length-$g(t).length))])}function qg(e,t,n){if(t.length===0)return[];let r=Er(e,n,{additive:!0,semantic:!1}),i=new Map;for(let a of n){let c=i.get(a.symbol)??[];c.push(a),i.set(a.symbol,c)}let o=new Map,s=[...t];for(;s.length>0;){let a=s.shift();if(!o.has(a.symbolId)){o.set(a.symbolId,a);for(let c of r.get(a.symbolId)??[])for(let l of i.get(c.symbol)??[])o.has(l.symbolId)||s.push(l)}}return[...o.values()].sort(xL)}function Gg(e){let t=[...e].sort((r,i)=>r.relativePath.localeCompare(i.relativePath)||r.startLine-i.startLine||i.endLine-r.endLine),n=[];for(let r of t)n.some(i=>Wg(i,r))||n.push(r);return n}function zg(e,t){let n=t.text.split(`
|
|
46
|
-
`);return{symbol:t.relativePath,shortName:t.relativePath,relativePath:t.relativePath,startLine:0,endLine:Math.max(0,n.length-1),language:e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath)?.language??zl(t.relativePath),source:t.text,freshness:t.freshness,...go(t.freshness)?{bindingClosure:di(e,t.relativePath,0,Math.max(0,n.length-1))}:{}}}function SL(e,t){return ua(e).filter(n=>t.some(r=>Gl(n,r))).length}function vL(e,t,n){let r=[];return Kg(r,e,t,n,0),r}function Kg(e,t,n,r,i){for(let o of n){if(r.some(a=>Gl(o,a)))continue;let s=ua(o.children).filter(a=>!r.some(c=>Gl(a,c))).length;e.push({symbol:o.symbol,shortName:o.shortName,relativePath:t,startLine:o.startLine,endLine:o.endLine,signature:o.signature,depth:i,nestedDefinitions:s}),Kg(e,t,o.children,r,i+1)}}function ua(e){return e.flatMap(t=>[t,...ua(t.children)])}function CL(e){return ua(e).length}function Gl(e,t){return t.startLine<=e.startLine&&t.endLine>=e.endLine}function Wg(e,t){return e.relativePath===t.relativePath&&e.startLine<=t.startLine&&e.endLine>=t.endLine}function xL(e,t){return e.startLine-t.startLine||t.endLine-e.endLine||e.symbol.localeCompare(t.symbol)}function RL(e,t){return{selector:e,status:"matched",kind:"source",totalCandidates:1,results:[t],definitions:[],candidates:[],omittedCandidates:0,suggestions:[]}}function ql(e,t,n){return{selector:t,status:"missing",kind:"source",totalCandidates:0,results:[],definitions:[],candidates:[],omittedCandidates:0,suggestions:js(e,t,5),reason:n}}function Vg(e,t){try{return Js(e,t)}catch(n){if(n instanceof _p)return null;throw n}}function EL(e,t){if(!t.match)return[];let n=[t.match];for(let i of t.candidates){let o=U(e,i.relativePath).find(s=>s.symbol===i.symbol&&s.startLine===i.startLine);o&&n.push(o)}let r=new Set;return n.filter(i=>{let o=`${i.relativePath}:${i.startLine}:${i.endLine}:${i.symbol}`;return r.has(o)?!1:(r.add(o),!0)})}function Yg(e){return{symbol:e.symbol,shortName:T(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function Jg(e){let t=e.match(/^(.+):(\d+)-(\d+)$/);if(!t)return null;let n=Number(t[2]),r=Number(t[3]);if(!Number.isSafeInteger(n)||n<1)throw new RangeError(`Source range start line must be a positive integer, got "${t[2]}".`);if(!Number.isSafeInteger(r)||r<n)throw new RangeError(`Source range end line must be an integer at or after ${n}, got "${t[3]}".`);return{filePath:t[1],startLine:n,endLine:r}}function fo(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=Js(e,t.relativePath);if(!i)return null;let s=i.text.split(`
|
|
47
|
-
`),a=t.endLine<=t.startLine?Kn(e,t.relativePath,t.startLine,Number.MAX_SAFE_INTEGER):null,c=a?.unitType?a.unitStartLine:t.startLine,l=a?.unitType?a.unitEndLine:t.endLine,u=Math.max(0,c-n),d=Math.min(s.length-1,l+n),m=s.slice(u,d+1).join(`
|
|
48
|
-
`);return{symbol:t.symbol,shortName:T(t.symbol),relativePath:t.relativePath,startLine:u,endLine:d,language:r?.language??zl(t.relativePath),source:m,freshness:i.freshness,...go(i.freshness)?{bindingClosure:di(e,t.relativePath,u,d)}:{}}}function Xg(e,t,n,r,i){let o=Js(e,t);if(!o)return null;let s=e.get("SELECT language FROM documents WHERE relative_path = ?",o.relativePath),c=o.text.split(`
|
|
49
|
-
`);if(n>c.length)return null;let l=Math.max(0,n-1-i),u=Math.min(c.length-1,r-1+i),d=c.slice(l,u+1).join(`
|
|
50
|
-
`);return{symbol:`${o.relativePath}:${n}-${r}`,shortName:`${o.relativePath}:${n}-${r}`,relativePath:o.relativePath,startLine:l,endLine:u,language:s?.language??zl(o.relativePath),source:d,freshness:o.freshness,...go(o.freshness)?{bindingClosure:di(e,o.relativePath,l,u)}:{}}}function go(e){return!!(e&&e.semantic.state!=="stale"&&e.semantic.basis!=="no-compiler-document")}function zl(e){switch($g(e).toLowerCase()){case".ts":case".tsx":case".mts":case".cts":return"typescript";case".js":case".jsx":case".mjs":case".cjs":return"javascript";case".py":case".pyi":return"python";case".rs":return"rust";case".go":return"go";case".java":return"java";case".kt":case".kts":return"kotlin";case".scala":return"scala";case".rb":return"ruby";case".php":return"php";case".cs":return"csharp";case".vb":return"vb";case".dart":return"dart";case".c":case".h":return"c";case".cc":case".cpp":case".cxx":case".hpp":case".hh":case".hxx":return"cpp";case".vue":return"vue";default:return null}}function da(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath)??[];r.push(n),t.set(n.relativePath,r)}return t}function Qg(e){let t=new Map,n=wL(e),r=new Map;return i=>{let o=IL(i),s=r.get(o);if(s!==void 0)return s;if(!n.has(i.file))return r.set(o,i.symbol),i.symbol;let a=t.get(i.file);a||(a=LL(U(e,i.file)),t.set(i.file,a));let c=PL(a,i);return r.set(o,c),c}}function IL(e){return`${e.file}\0${e.symbol}\0${e.line}`}function wL(e){return new Set(e.all("SELECT relative_path FROM documents").map(t=>t.relative_path))}function LL(e){let t=new Map,n=new Map;for(let r of e){let i=t.get(r.leaf);i?i.push(r):t.set(r.leaf,[r]);let o=n.get(r.startLine);o?o.push(r):n.set(r.startLine,[r])}return{definitions:e,byLeaf:t,byStartLine:n}}function PL(e,t){if(e.definitions.length===0)return t.symbol;let n=TL(t.symbol),r=DL(e.byLeaf,n),i=ML(r,t.line);if(i)return i.symbol;let o=e.byStartLine.get(t.line)??[];return o.length===1?o[0].symbol:t.symbol}function DL(e,t){let n=[],r=new Set;for(let i of t)for(let o of e.get(i)??[])r.has(o.symbolId)||(r.add(o.symbolId),n.push(o));return n}function ML(e,t){let n=null;for(let r of e)if(!(r.startLine>t||r.endLine<t)){if(r.startLine===t)return r;(!n||r.endLine-r.startLine<n.endLine-n.startLine)&&(n=r)}return n}function TL(e){let t=new Set([e]),r=e.split(/::|\.|#/).filter(Boolean).at(-1);return r&&t.add(r),t}function Zg(e,t){let r=ae(e,t).map(i=>AL(t,i));return{usage:r,positions:FL(e,t,r)}}function eh(e,t){return{importUsage(n){let r=e.importUsageFacts(n);if(!t||r.positions.length===0)return r.usage;let i=t.importDefinitionsForFile(n,r.positions);return i.available?kL(r.usage,i.sourcePaths):r.usage}}}function kL(e,t){return e.map((n,r)=>{let i=t.get(String(r));return i?{...n,sourcePath:i}:n})}function AL(e,t){let n=t.isTypeOnly===!0,r=t.kind==="side-effect"||n||t.used;return{importer:e,sourcePath:t.sourcePath,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:n,isUsed:r,isTypeUsed:n,isValueUsed:t.kind==="side-effect"||!n&&t.used,references:[]}}function FL(e,t,n){let r=J(e,t);if(!r)return[];let i=NL(r.rootNode),o=new Map;for(let a of i){let c=o.get(Wl(a.importedName,a.localName));c?c.push(a.position):o.set(Wl(a.importedName,a.localName),[a.position])}let s=[];return n.forEach((a,c)=>{let l=o.get(Wl(a.importedName,a.localName??a.importedName))?.shift();l&&s.push({...l,id:String(c),file:t})}),s}function NL(e){let t=[];for(let n of e.descendantsOfType("use_declaration")){let r=n.namedChildren.find(i=>i.type!=="visibility_modifier");r&&t.push(...ma(r,""))}return t.filter(n=>n.importedName!=="*")}function ma(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":return[{importedName:e.text,localName:e.text,position:Kl(e,e.text)}];case"scoped_identifier":{let n=e.text.split("::").pop()??e.text;return[{importedName:n,localName:n,position:Kl(e,n)}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=mf(t,n.text);return r.namedChildren.flatMap(o=>ma(o,i))}case"use_list":return e.namedChildren.flatMap(n=>ma(n,t));case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);return!n||!r?[]:ma(n,t).map(i=>({...i,localName:r.text}))}case"use_wildcard":{let n=e.namedChild(0),r="*";return[{importedName:r,localName:r,position:Kl(n??e,r)}]}default:return[]}}function Kl(e,t){let n=Math.max(0,e.text.lastIndexOf(t));return{id:"",file:"",line:e.startPosition.row,column:e.startPosition.column+n+_L(t)}}function _L(e){return Math.max(0,Math.min(e.length-1,1))}function Wl(e,t){return`${e}\0${t}`}import{spawnSync as ou}from"child_process";import{existsSync as su}from"fs";import{fileURLToPath as _P}from"url";function Vn(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function pa(e){let t=kf(Tf,e),n=t.runnable;return n?{available:!0,dependencyAvailable:n,resolvedBinary:t.resolvedBinary??void 0,note:"rust-analyzer semantic reference queries are enabled."}:{available:!1,dependencyAvailable:n,resolvedBinary:t.resolvedBinary??void 0,reason:"rust-analyzer is not runnable; Rust semantic checks will use SCIP/source evidence only."}}import{existsSync as CP,mkdtempSync as Rh,rmSync as Zl}from"fs";import{tmpdir as nu}from"os";import{join as eu}from"path";import{fileURLToPath as xo,pathToFileURL as xP}from"url";import{SHARE_ENV as RP,Worker as EP}from"worker_threads";function Yn(e,t,n=new Set){let r=new Map;for(let i of e)n.has(i.symbolId)||r.set(i.symbolId,t.get(i.symbolId)??[]);return r}function Ir(e,t,n){let r=Vn(process.env.SCIP_RUST_SEMANTIC_BATCH_TIMEOUT_MS)??0;if(r>0)return r;let i=Math.max(1,Math.ceil(e/Math.max(1,n)));return Math.max(12e4,3e4+i*t)}import{spawn as tP}from"child_process";import{createHash as nP,randomUUID as rP}from"crypto";import{existsSync as gh,realpathSync as iP,rmSync as oP}from"fs";import{tmpdir as sP}from"os";import{resolve as hi}from"path";import{execFileSync as GL}from"child_process";import{existsSync as OL}from"fs";import{deserializeSCIP as BL,SymbolRole as $L}from"@c4312/scip";import{realpathSync as a3}from"fs";import{basename as l3,dirname as u3,join as d3,relative as m3,sep as p3}from"path";import{fileURLToPath as g3,pathToFileURL as h3}from"url";function fa(e){let t=new Map;for(let n of e)t.set(`${n.file}\0${n.line}\0${n.column}`,n);return[...t.values()].sort((n,r)=>{let i=n.file.localeCompare(r.file);return i!==0?i:n.line!==r.line?n.line-r.line:n.column-r.column})}var Vl=new WeakMap,jL="SCIP_RUST_SCIP_OCCURRENCE_REFERENCE_MODE";function th(e,t){let n=new Map,r=ga(),i=t.filter(s=>ih(s,r));if(i.length===0)return n;let o=oh(e);if(!o)return n;for(let s of i){let a=rh(o,s);a!==null&&n.set(s.symbolId,a)}return n}function nh(e,t){if(!ih(t,ga()))return null;let n=oh(e);return n?rh(n,t):null}function rh(e,t){return e.referencesBySymbol.get(t.symbol)??[]}function ih(e,t="safe"){if(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||je(e.symbol)||/impl#\[[^\]]+\]\[Default\]default\(\)\.$/.test(e.symbol))return!1;if(t==="all")return!0;let n=wt(e.symbol);if(n==="method")return!0;if(n!=="term")return!1;let r=Bn(e.symbol);return"kind"in r?!1:!HL(r)}function HL(e){for(let t=0;t<e.descriptors.length-1;t+=1)if(e.descriptors[t]?.suffix==="type")return!0;return!1}function oh(e){if(Vl.has(e))return Vl.get(e)??null;let t=UL(e);return Vl.set(e,t),t}function UL(e){if(!e.generation.indexPath||!OL(e.generation.indexPath))return null;try{let t=BL(Qr(e.generation.indexPath,{inputKind:"SCIP occurrence-reference index",maxBytes:Xr})),n=new Map;for(let r of t.documents??[]){let i=r.relativePath;if(!(!i||e.isIgnored(i)))for(let o of r.occurrences??[]){if(!o.symbol||(o.symbolRoles&$L.Definition)!==0)continue;let s=qL(i,o.range);if(!s)continue;let a=n.get(o.symbol)??[];a.push(s),n.set(o.symbol,a)}}for(let[r,i]of n)n.set(r,fa(i));return{referencesBySymbol:n}}catch{return null}}function qL(e,t){if(t.length<3)return null;let n=t[0],r=t[1];return!Number.isInteger(n)||!Number.isInteger(r)?null:{file:e,line:n,column:r}}function ga(){return process.env[jL]==="all"?"all":"safe"}var sh=new Map;function Yl(e){let n=pa(e).resolvedBinary??null;return{engine:"rust-analyzer",resolvedBinary:n,version:n?zL(e,n):"unavailable"}}function wr(e){return{...Yl(e),scipOccurrenceReferenceMode:ga()}}function zL(e,t){let n=`${e}\0${t}`,r=sh.get(n);if(r)return r;let i;try{i=GL(t,["--version"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim()}catch{i="unknown"}return sh.set(n,i),i}import{createHash as KL}from"crypto";var WL=new Set(["Cargo.lock","Cargo.toml","rust-project.json","rust-toolchain","rust-toolchain.toml"]);function ah(e){let t=Wp(e,{includePath:VL});return KL("sha256").update(JSON.stringify(t)).digest("hex")}function VL(e){let t=e.replaceAll("\\","/"),n=t.split("/").at(-1)??t;return t.endsWith(".rs")||WL.has(n)?!0:t===".cargo/config"||t===".cargo/config.toml"||t.endsWith("/.cargo/config")||t.endsWith("/.cargo/config.toml")}import{createHash as YL}from"crypto";import{resolve as JL}from"path";var gi=3;function Xl(e){return YL("sha256").update(vr({kind:"scip-query-durable-rust-mailbox",protocolVersion:gi,sessionDir:JL(e)})).digest("hex")}function uh(e,t){return Q(e)?e.protocolVersion!==gi?lh(e.protocolVersion===void 0?"helper wrote a prior uncorrelated response protocol":`helper wrote unsupported response protocol ${String(e.protocolVersion)}`):e.mailboxVersion!==gn||e.id!==t.requestId||e.operationKey!==t.operationKey||e.sessionIdentity!==t.sessionIdentity||e.deadlineAtMs!==t.deadlineAtMs?lh("helper wrote an incompatible response identity"):typeof e.completedAtMs!="number"||!Number.isFinite(e.completedAtMs)||e.completedAtMs>t.deadlineAtMs||t.nowMs>t.deadlineAtMs?{ok:!1,code:"expired-request",error:"helper response arrived after the durable request deadline"}:e.ok===!1?typeof e.error!="string"||!eP(e.errorCode)?Jl("helper wrote an invalid rejection response"):{ok:!1,code:e.errorCode,error:e.error}:e.ok!==!0||e.session!=="created"&&e.session!=="reused"&&e.session!=="invalidated"||!XL(e.response,t.requestKind)?Jl("helper wrote an invalid success response"):{ok:!0,session:e.session,response:e.response}:Jl("helper wrote an invalid response object")}function XL(e,t){return!Q(e)||typeof e.available!="boolean"||e.available===!1&&(typeof e.reason!="string"||e.reason.length===0)||e.available===!0&&e.reason!==void 0?!1:t==="import-definitions"?Array.isArray(e.sourcePaths)&&e.sourcePaths.every(n=>Array.isArray(n)&&n.length===2&&typeof n[0]=="string"&&(n[1]===null||typeof n[1]=="string")):ch(e.references,QL)&&(e.incompleteReferenceSymbolIds===void 0||Array.isArray(e.incompleteReferenceSymbolIds)&&e.incompleteReferenceSymbolIds.every(n=>Number.isSafeInteger(n)))&&(e.callees===void 0||ch(e.callees,ZL))&&(e.signatures===void 0||Array.isArray(e.signatures)&&e.signatures.every(n=>Array.isArray(n)&&n.length===2&&Number.isSafeInteger(n[0])&&(n[1]===null||typeof n[1]=="string")))}function ch(e,t){return Array.isArray(e)&&e.every(n=>Array.isArray(n)&&n.length===2&&Number.isSafeInteger(n[0])&&Array.isArray(n[1])&&n[1].every(t))}function QL(e){return Q(e)&&typeof e.file=="string"&&xt(e.line)&&xt(e.column)}function ZL(e){return Q(e)&&typeof e.symbol=="string"&&typeof e.file=="string"&&xt(e.line)&&(e.callsiteLine===void 0||xt(e.callsiteLine))}function eP(e){return e==="unsupported-protocol"||e==="malformed-request"||e==="expired-request"||e==="handler-error"}function Jl(e){return{ok:!1,code:"malformed-response",error:e}}function lh(e){return{ok:!1,code:"incompatible-response",error:e}}var aP=5e3,hh=10,cP=3e4;function dh(e,t,n,r=vh){let i=r.engineIdentity(e),o={protocolVersion:gi,projectRoot:r.canonicalProjectRoot(e),projectFingerprint:r.projectFingerprint(e),engine:{engine:i.engine,resolvedBinary:i.resolvedBinary,version:i.version},workerFingerprint:r.fileFingerprint(t),environment:yh(r.environment())};return{key:Ch(vr(o)),...o}}function ho(e,t,n,r){if(e.protocolVersion!==gi||!n(e.pid))return!1;if(!e.processIdentity)return!0;let i=r?.(e.pid);return i!=null&&qs(e.processIdentity,i)}function Ql(e,t,n){let r;try{r=ul(t,{maxBytes:dn,inputKind:"Rust semantic engine artifact"})}catch{r="missing"}let i=Ch(vr({projectRoot:hi(e),serverPath:hi(t),serverFingerprint:r})).slice(0,20);return hi(n,`scip-query-rust-session-${i}`)}function mh(e){let t=e===void 0?Number.NaN:Number(e);return Number.isInteger(t)&&t>=0?t:0}function yh(e){return Object.fromEntries(Object.entries(e).filter(([t])=>Sh(t)).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,n??null]))}function bh(e,t){let n=t.runtime??fP,r=t.identityRuntime??vh,i=Ql(e,t.serverPath,t.tempRoot??sP()),o=!1,s=(a,c)=>{if(o)throw new Error("Durable Rust semantic session was already disposed.");return uP(i,t.serverPath,t.semanticWorkerPath,a,c,n,t.mailboxLimits)};return{requestSemantic(a,c){let l=dh(e,t.semanticWorkerPath,a,r),{readinessDeadlineMs:u,...d}=a;return s({kind:"semantic",identityKey:l.key,workerEnvironment:fh(),request:{...d,referenceRetryTimeoutMs:lP(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,a.referenceRetryTimeoutMs),settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:mh(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},requestImportDefinitions(a,c){let l=dh(e,t.semanticWorkerPath,a,r),{readinessDeadlineMs:u,...d}=a;return s({kind:"import-definitions",identityKey:l.key,workerEnvironment:fh(),request:{...d,settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:mh(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},shutdown(){o=!0}}}function lP(e,t){return t!==void 0?t:e===void 0?cP:void 0}function uP(e,t,n,r,i,o,s={}){let a=o.now(),c=a+i,l=(o.monotonicNow??Lt)(),u=l+i,d=Hn("rust-semantic-v3",r),m=xr(d),p=Gs(e),f=Xl(e),g=zs(p,{mailboxVersion:gn,protocolVersion:gi,id:m,operationKey:d,clientId:o.randomId(),enqueuedAtMs:a,deadlineAtMs:c,sessionIdentity:f,request:r},{nowMs:a,limits:s});for(ph(e,t,n,u,o);(o.monotonicNow??Lt)()<=u;){if(gh(g.responsePath)){let b=dP(vt(g.responsePath,{maxBytes:s.maxItemBytes??dn,inputKind:"durable Rust semantic mailbox response"}),{requestId:m,operationKey:d,sessionIdentity:f,deadlineAtMs:g.authoritativeDeadlineAtMs,requestKind:r.kind,nowMs:o.now()});if(!b.ok)throw new Error(b.error);return be()&&Ts({type:"span",name:"rust.semantic.durable-session.request",durationMs:(o.monotonicNow??Lt)()-l,ok:!0,session:b.session,kind:r.kind}),b.response}let h=yo(e);(!h||!ho(h,o.now(),o.isProcessAlive,o.readProcessIdentity))&&ph(e,t,n,u,o),o.sleep(hh)}throw new Error(`Durable Rust semantic session timed out after ${(i/1e3).toFixed(0)}s.`)}function ph(e,t,n,r,i){let o=yo(e);if(o&&ho(o,i.now(),i.isProcessAlive,i.readProcessIdentity))return;oP(hi(e,"server.json"),{force:!0}),i.spawnServer(t,e,n);let s=i.monotonicNow??Lt,a=Math.min(r,s()+aP);for(;s()<=a;){let c=yo(e);if(c&&ho(c,i.now(),i.isProcessAlive,i.readProcessIdentity))return;i.sleep(hh)}throw new Error("Durable Rust semantic session helper did not become ready within 5s.")}function yo(e){try{let t=JSON.parse(vt(hi(e,"server.json"),{maxBytes:Ls,inputKind:"durable Rust session state"}));if(typeof t.protocolVersion!="number"||t.sessionIdentity!==void 0&&(typeof t.sessionIdentity!="string"||t.sessionIdentity!==Xl(e))||typeof t.pid!="number"||typeof t.heartbeatAtMs!="number"||t.busyUntilMs!==void 0&&typeof t.busyUntilMs!="number"||t.mailbox!==void 0&&!mP(t.mailbox))return null;let n=t.processIdentity===void 0?null:Us(t.processIdentity);return t.processIdentity!==void 0&&(!n||n.pid!==t.pid)?null:{protocolVersion:t.protocolVersion,...t.sessionIdentity===void 0?{}:{sessionIdentity:t.sessionIdentity},pid:t.pid,...n?{processIdentity:n}:{},heartbeatAtMs:t.heartbeatAtMs,...t.busyUntilMs===void 0?{}:{busyUntilMs:t.busyUntilMs},...t.mailbox===void 0?{}:{mailbox:t.mailbox}}}catch{return null}}function dP(e,t){try{return uh(JSON.parse(e),t)}catch(n){return{ok:!1,code:"malformed-response",error:`helper wrote malformed JSON: ${n instanceof Error?n.message:String(n)}`}}}function mP(e){if(!e||typeof e!="object")return!1;let t=e;return xt(t.pending)&&xt(t.inflight)&&xt(t.responses)&&xt(t.deadLetters)&&xt(t.invalid)&&xt(t.totalItems)&&typeof t.totalBytes=="number"&&Number.isFinite(t.totalBytes)&&t.totalBytes>=0&&(t.oldestPendingAt===void 0||Number.isFinite(Date.parse(t.oldestPendingAt)))}function fh(){return Object.fromEntries(Object.entries(process.env).filter(([e])=>pP(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t??null]))}function Sh(e){return e==="HOME"||e==="PATH"||e.startsWith("CARGO_")||e.startsWith("RA_")||e.startsWith("RUST")}function pP(e){return Sh(e)||e.startsWith("SCIP_RUST_")||e==="SCIP_QUERY_PROFILE"||e==="SCIP_QUERY_PROFILE_CACHE_STATE"||e==="SCIP_QUERY_PROFILE_COMMAND"||e==="SCIP_QUERY_PROFILE_OUT"||e==="SCIP_QUERY_PROFILE_RUN_ID"||e==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY"||e==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY_KIND"||e==="SCIP_QUERY_PROFILE_MIN_MS"}var vh={canonicalProjectRoot(e){try{return iP(e)}catch{return hi(e)}},projectFingerprint(e){return ah(e)},engineIdentity:Yl,fileFingerprint(e){return ul(e,{maxBytes:dn,inputKind:"Rust semantic engine artifact"})},environment(){return yh(process.env)}},fP={now:Date.now,monotonicNow:Lt,randomId:rP,isProcessAlive:ci,readProcessIdentity:li,spawnServer(e,t,n){if(!gh(e))throw new Error(`Durable Rust semantic session helper was not found at ${e}. Run npm run build first.`);tP(process.execPath,[e,t,n],{detached:!0,stdio:"ignore"}).unref()},sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)}};function Ch(e){return nP("sha256").update(e).digest("hex")}import{randomUUID as rQ}from"crypto";import{readdirSync as gP,rmSync as oQ,writeFileSync as sQ}from"fs";import{join as hP}from"path";var yP="rust-analyzer-owner-",bP=".json",SP=16*1024;async function xh(e,t){if(!e)return[];let n;try{n=gP(e)}catch{return[]}let r=n.filter(s=>s.startsWith(yP)&&s.endsWith(bP)).map(s=>hP(e,s)),i=[],o=[];for(let s of r){let a=vP(s);a?o.push(a):i.push({reaped:!1,reason:"identity-unavailable",detail:`Rust analyzer ownership record ${s} could not be validated.`})}return i.push(...await Promise.all(o.map(s=>_f(s,t)))),i}function vP(e){try{let t=vt(e,{maxBytes:SP,inputKind:"rust-analyzer process ownership record"}),n=JSON.parse(t),r=Us(n.rootIdentity);return n.version!==1||!r||typeof n.ownsProcessGroup!="boolean"?null:{rootPid:r.pid,rootIdentity:r,ownsProcessGroup:n.ownsProcessGroup,knownMembers:new Map([[r.pid,r]])}}catch{return null}}var Eh=15e3,Ih=8,Lh=5e3,IP=64,wP=96,ru=class{constructor(t,n,r={}){this.projectRoot=t;this.status=n;this.opts=r;this.requester=r.requester??DP(t,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION)}projectRoot;status;opts;requester;referencesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:So(n),references:vo(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!0});return{...bo(r),resolvedBinary:n.resolvedBinary,references:Yn(t,new Map(r.references),new Set(r.incompleteReferenceSymbolIds??[]))}}catch(r){return this.opts.fallbackReferenceResolver?.referencesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),references:vo(t)}}}calleesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:So(n),callees:Co(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!0});return{...bo(r),resolvedBinary:n.resolvedBinary,callees:tu(t,new Map(r.callees??[]))}}catch(r){return this.opts.fallbackCalleeResolver?.calleesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),callees:Co(t)}}}referencesAndCalleesForDefinitions(t,n){let r=this.status(this.projectRoot);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:So(r),references:vo(t),callees:Co(n)};let i=[...t,...n];try{let o=this.requestSession(r.resolvedBinary,i,{includeReferences:t.length>0,includeCallees:n.length>0,referenceDefinitions:t,calleeDefinitions:n});return{...bo(o),resolvedBinary:r.resolvedBinary,references:Yn(t,new Map(o.references),new Set(o.incompleteReferenceSymbolIds??[])),callees:tu(n,new Map(o.callees??[]))}}catch(o){return this.fallbackReferencesAndCallees(r,t,n,o)}}signaturesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:So(n),signatures:wh(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!1,includeSignatures:!0});return{...bo(r),resolvedBinary:n.resolvedBinary,signatures:FP(t,new Map(r.signatures??[]))}}catch(r){return this.opts.fallbackSignatureResolver?.signaturesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),signatures:wh(t)}}}importDefinitionsForFile(t,n){let r=this.status(this.projectRoot);if(n.length===0)return r.available?{available:!0,resolvedBinary:r.resolvedBinary,sourcePaths:new Map}:{available:!1,reason:r.reason,resolvedBinary:r.resolvedBinary,sourcePaths:new Map};if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:So(r),sourcePaths:new Map(n.map(i=>[i.id,null]))};try{let i=this.requestImportDefinitions(r.resolvedBinary,t,n);return{...bo(i),resolvedBinary:r.resolvedBinary,sourcePaths:new Map(i.sourcePaths)}}catch(i){return{available:!1,resolvedBinary:r.resolvedBinary,reason:i instanceof Error?i.message:String(i),sourcePaths:new Map(n.map(o=>[o.id,null]))}}}dispose(){this.requester.shutdown()}requestSession(t,n,r){let i=ha(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Eh),o=ya(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),s=ha(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Ih),a=ya(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),c=r.referenceDefinitions?[...r.referenceDefinitions]:void 0,l=r.calleeDefinitions?[...r.calleeDefinitions]:void 0,u=r.signatureDefinitions?[...r.signatureDefinitions]:void 0,d=Ro(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,...r}),m={projectRoot:this.projectRoot,rustAnalyzerBinary:t,definitions:[...n],...c?{referenceDefinitions:c}:{},...l?{calleeDefinitions:l}:{},...u?{signatureDefinitions:u}:{},requestTimeoutMs:i,...r.includeReferences!==!1&&o>0?{referenceRetryTimeoutMs:o}:{},diagnosticsTimeoutMs:a,settleDelayMs:d,concurrency:s,includeReferences:r.includeReferences,includeCallees:r.includeCallees,includeSignatures:r.includeSignatures},p=NP(m);return N("rust.semantic.session.request",()=>this.requester.requestSemantic(m,Ir(p,iu(i,m.referenceRetryTimeoutMs),s)),()=>({definitions:n.length,operationDefinitions:p,referenceDefinitions:m.referenceDefinitions?.length,calleeDefinitions:m.calleeDefinitions?.length,signatureDefinitions:m.signatureDefinitions?.length,references:m.includeReferences!==!1,callees:m.includeCallees===!0,signatures:m.includeSignatures===!0,referenceRetryTimeoutMs:m.referenceRetryTimeoutMs}))}fallbackReferencesAndCallees(t,n,r,i){let o=n.length===0?{available:!0,resolvedBinary:t.resolvedBinary,references:vo(n)}:this.opts.fallbackReferenceResolver?.referencesForDefinitions(n),s=r.length===0?{available:!0,resolvedBinary:t.resolvedBinary,callees:Co(r)}:this.opts.fallbackCalleeResolver?.calleesForDefinitions(r);if(o&&s){let a={resolvedBinary:o.resolvedBinary??s.resolvedBinary??t.resolvedBinary,references:Yn(n,o.references),callees:tu(r,s.callees)};return o.available&&s.available?{available:!0,...a}:{available:!1,reason:(o.available?void 0:o.reason)??(s.available?void 0:s.reason)??"Rust semantic fallback was unavailable.",...a}}return{available:!1,resolvedBinary:t.resolvedBinary,reason:i instanceof Error?i.message:String(i),references:vo(n),callees:Co(r)}}requestImportDefinitions(t,n,r){let i=ha(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Eh),o=ha(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Ih),s=ya(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),a=ya(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,Lh),c={projectRoot:this.projectRoot,rustAnalyzerBinary:t,file:n,positions:[...r],requestTimeoutMs:i,diagnosticsTimeoutMs:s,settleDelayMs:a,concurrency:o};return N("rust.semantic.import-definitions.session.request",()=>this.requester.requestImportDefinitions(c,Ir(r.length,i,o)),()=>({file:n,positions:r.length}))}};function bo(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function So(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function Ph(e,t,n={}){return new ru(e,t,n)}function Ro(e,t){let n=kh(e);if(n!==null)return n;let r=t.includeReferences!==!1;return r&&t.includeCallees!==!0&&t.includeSignatures!==!0&&t.definitionCount<=IP||r&&t.includeCallees===!0&&t.includeSignatures!==!0&&t.definitionCount<=wP?0:Lh}function Dh(e){let t=e?.trim().toLowerCase(),n=t==="0"||t==="false"||t==="off"||t==="worker",r=t==="1"||t==="true"||t==="on"||t==="durable",i=t===void 0||t==="";return{transport:n||!i&&!r?"worker":"durable",source:i?"default":"environment",fallback:"worker",valid:i||n||r,optOut:"SCIP_RUST_SEMANTIC_DURABLE_SESSION=0"}}function LP(e){return Dh(e).transport}function IQ(e,t){let n=Dh(t);if(n.transport==="worker")return{...n,state:"per-command"};let r=xo(Th()),i=Ql(e,r,nu()),o=yo(i);return o?{...n,state:ho(o,Date.now(),ci,li)?"live":"stale",pid:o.pid,heartbeatAtMs:o.heartbeatAtMs,...o.busyUntilMs===void 0?{}:{busyUntilMs:o.busyUntilMs}}:{...n,state:"stopped"}}function PP(e,t){let n=null,r=!1,i=!1,o=!1,s=()=>n??=t(),a=()=>{i||(e.shutdown(),i=!0)},c=(u,d,m)=>{let p=AP(u);r=!0;try{a()}catch{}be()&&Ts({type:"span",name:"rust.semantic.durable-session.request",durationMs:m,ok:!1,kind:d,session:"worker-fallback",reason:p})},l=(u,d,m)=>{if(o)throw new Error("Rust semantic failover session was already disposed.");if(r)return m(s());let p=performance.now();try{return d(e)}catch(f){c(f,u,performance.now()-p)}return m(s())};return{requestSemantic(u,d){return l("semantic",m=>m.requestSemantic(u,d),m=>m.requestSemantic(u,d))},requestImportDefinitions(u,d){return l("import-definitions",m=>m.requestImportDefinitions(u,d),m=>m.requestImportDefinitions(u,d))},shutdown(){if(o)return;o=!0;let u=[];try{a()}catch(d){u.push(d)}try{n?.shutdown()}catch(d){u.push(d)}if(u.length>0)throw u[0]}}}function DP(e,t,n={worker:()=>MP(),durable:()=>bh(e,{serverPath:xo(Th()),semanticWorkerPath:xo(Mh())})}){return LP(t)==="durable"?PP(n.durable(),n.worker):n.worker()}function MP(e={}){let t=null,n=null,r=1,i=!1,o=null,s=null,a=d=>{d&&Zl(d,{recursive:!0,force:!0})},c=()=>{if(o)return;let d=t,m=n;t=null,n=null;let p=d?d.terminate():Promise.resolve(0);o=Promise.allSettled([p,xh(m,{gracefulMs:1e3,forceMs:1e3})]).then(([f,g])=>{let b=(g.status==="fulfilled"?g.value:[{reaped:!1,detail:String(g.reason)}]).filter(S=>!S.reaped);if(f.status==="rejected"||b.length>0){s=new Error(`Rust semantic worker cleanup did not complete; ownership evidence remains at ${m??"unknown"}.`);return}a(m)}).finally(()=>{o=null})},l=()=>{if(t)return t;if(o)throw new Error("The previous Rust semantic session worker is still terminating; retry the request.");if(s)throw s;let d=e.semanticWorkerPath?xP(e.semanticWorkerPath):Mh();if(!CP(xo(d)))throw new Error(`Rust semantic session worker was not found at ${xo(d)}. Run npm run build before using built semantic Rust queries.`);return n=Rh(eu(nu(),"scip-query-rust-session-")),t=new EP(d,e.shareEnvironment?{env:RP}:void 0),t.unref(),t},u=()=>{let d=n??Rh(eu(nu(),"scip-query-rust-session-"));return n=d,eu(d,`${r++}.json`)};return{requestSemantic(d,m){if(i)throw new Error("Rust semantic session was already disposed.");let p=l(),f=u(),g=new SharedArrayBuffer(4),h=new Int32Array(g);if(p.postMessage({kind:"semantic",request:d,responsePath:f,sharedBuffer:g}),Atomics.wait(h,0,0,m)==="timed-out")throw c(),new Error(`Rust semantic session worker timed out after ${(m/1e3).toFixed(0)}s`);try{let S=TP(vt(f,{maxBytes:dn,inputKind:"Rust semantic worker response"}));if(!S.ok)throw new Error(S.error);return S.response}finally{Zl(f,{force:!0})}},requestImportDefinitions(d,m){if(i)throw new Error("Rust semantic session was already disposed.");let p=l(),f=u(),g=new SharedArrayBuffer(4),h=new Int32Array(g);if(p.postMessage({kind:"import-definitions",request:d,responsePath:f,sharedBuffer:g}),Atomics.wait(h,0,0,m)==="timed-out")throw c(),new Error(`Rust semantic import-definition session worker timed out after ${(m/1e3).toFixed(0)}s`);try{let S=kP(vt(f,{maxBytes:dn,inputKind:"Rust import-definition worker response"}));if(!S.ok)throw new Error(S.error);return S.response}finally{Zl(f,{force:!0})}},shutdown(){if(i)return;if(i=!0,!t){a(n),n=null;return}let d=u(),m=new SharedArrayBuffer(4),p=new Int32Array(m);t.postMessage({kind:"shutdown",responsePath:d,sharedBuffer:m}),Atomics.wait(p,0,0,5e3),c()}}}function TP(e){let t=JSON.parse(e);if(!t||typeof t!="object")return{ok:!1,error:"Rust semantic session worker wrote a non-object response."};let n=t;return n.ok===!0&&"response"in n?{ok:!0,response:n.response}:{ok:!1,error:typeof t.error=="string"?t.error:"Rust semantic session worker failed."}}function kP(e){let t=JSON.parse(e);if(!t||typeof t!="object")return{ok:!1,error:"Rust semantic session worker wrote a non-object response."};let n=t;return n.ok===!0&&"response"in n?{ok:!0,response:n.response}:{ok:!1,error:typeof t.error=="string"?t.error:"Rust semantic session worker failed."}}function AP(e){let t=e instanceof Error?`${e.name} ${e.message}`.toLowerCase():String(e).toLowerCase();return t.includes("readiness")?"readiness":t.includes("timeout")||t.includes("timed out")?"timeout":t.includes("helper")?"helper":"request"}function vo(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Co(e){return new Map(e.map(t=>[t.symbolId,[]]))}function wh(e){return new Map(e.map(t=>[t.symbolId,null]))}function tu(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??[]]))}function FP(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function NP(e){let t=0;return e.includeReferences!==!1&&(t+=(e.referenceDefinitions??e.definitions).length),e.includeCallees===!0&&(t+=(e.calleeDefinitions??e.definitions).length),e.includeSignatures===!0&&(t+=(e.signatureDefinitions??e.definitions).length),Math.max(1,t)}function iu(e,t){return t&&t>0?Math.max(e,t):e}function Mh(){return new URL("./rust-semantic-session-worker.js",import.meta.url)}function Th(){return new URL("./rust-semantic-session-server.js",import.meta.url)}function ha(e,t){return Vn(e)??t}function ya(e,t){return kh(e)??t}function kh(e){if(!e)return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var au=15e3,cu=8;function _h(e,t={}){let n=t.status??pa,r=$P(e,n),i=jP(e,n),o=HP(e,n),s=t.referenceResolver||t.calleeResolver||t.signatureResolver||!OP(t)?null:Ph(e,n,{fallbackReferenceResolver:r,fallbackCalleeResolver:i,fallbackSignatureResolver:o}),a=t.referenceResolver??s??r,c=t.calleeResolver??s??i,l=t.signatureResolver??s??o,u=t.importUsageResolver??eh(t.sourceImportUsageResolver??BP(),t.importDefinitionResolver??s),d=t.calleeSymbolResolver,m=t.sourceZeroCalleeOracle,p=t.scipOccurrenceCalleeOracle,f=new Map,g=new Map,h=null,b=null,S=()=>(h??=n(e),h),y=()=>{let E=S();return E.dependencyAvailable?b??E:E},x=E=>{if(E.length===0)return new Map;let w=Io(E);try{let I=a.referencesForDefinitions(w),k=S();return b=ba(k,I),I.available?new Map(I.references):Yn(w,I.references)}catch(I){let k=S();return b=Eo(k,I),Lr(w)}},v=E=>{if(E.length===0)return new Map;let w=Io(E),I=w.filter(Ah);if(I.length===0)return Pr(w);let k=new Map,D=Nh(I,p),F=[];for(let L of I)g.has(L.symbolId)?k.set(L.symbolId,g.get(L.symbolId)??[]):D.has(L.symbolId)?k.set(L.symbolId,D.get(L.symbolId)??[]):Fh(L,m)?k.set(L.symbolId,[]):F.push(L);if(F.length===0)return yi(w,k,void 0);try{let L=c.calleesForDefinitions(F),A=S();b=ba(A,L);let P=yi(F,L.callees,d);for(let[j,B]of P)k.set(j,B);return yi(w,k,void 0)}catch(L){let A=S();return b=Eo(A,L),Pr(w)}},C=(E,w)=>{let I=Io(E),k=Io(w),D=k.filter(Ah),F=new Map,L=Nh(D,p),A=[];for(let P of D)L.has(P.symbolId)?F.set(P.symbolId,L.get(P.symbolId)??[]):Fh(P,m)?F.set(P.symbolId,[]):A.push(P);if(I.length===0&&A.length===0)return{references:Lr(I),callees:yi(k,F,void 0)};try{let P=s?s.referencesAndCalleesForDefinitions(I,A):zP(a,c,{referenceDefinitions:I,calleeDefinitions:A}),j=S();b=ba(j,P);let B=P.available?new Map(P.references):Yn(I,P.references);for(let[G,O]of P.callees)F.set(G,O);let X=yi(k,F,d);for(let[G,O]of X)g.set(G,O);return{references:B,callees:X}}catch(P){let j=S();return b=Eo(j,P),{references:Lr(I),callees:Pr(k)}}},R=E=>{if(E.length===0)return new Map;let w=Io(E);try{let I=l.signaturesForDefinitions(w),k=S();return b=ba(k,I),Oh(w,I.signatures)}catch(I){let k=S();return b=Eo(k,I),Sa(w)}};return{language:"rust",availability:y,dispose:()=>{s?.dispose()},importUsage:E=>{let w=f.get(E);if(w)return w;try{let I=u.importUsage(E);return f.set(E,I),I}catch(I){let k=S();return b=Eo(k,I),[]}},referencesFor:E=>x([E]).get(E.symbolId)??[],referencesForDefinitions:x,referencesAndCalleesForDefinitions:C,calleesFor:E=>v([E]).get(E.symbolId)??[],calleesForDefinitions:v,signatureFor:E=>R([E]).get(E.symbolId)??null}}function ba(e,t){let n={dependencyAvailable:e.dependencyAvailable,resolvedBinary:t.resolvedBinary??e.resolvedBinary,...e.note?{note:e.note}:{}};return t.available?{available:!0,...n}:{available:!1,reason:t.reason,...n}}function Eo(e,t){return{available:!1,dependencyAvailable:e.dependencyAvailable,resolvedBinary:e.resolvedBinary,...e.note?{note:e.note}:{},reason:t instanceof Error?t.message:String(t)}}function OP(e){if(e.usePersistentSession!==void 0)return e.usePersistentSession;let t=process.env.SCIP_RUST_SEMANTIC_SESSION;return t!=="0"&&t!=="false"}function BP(){return{importUsageFacts:()=>({usage:[],positions:[]})}}function Io(e){return e.map(t=>{let n=t;return{...t,leaf:typeof n.leaf=="string"?n.leaf:z(t.symbol),parentTypeName:n.parentTypeName??null,isFunctionLike:typeof n.isFunctionLike=="boolean"?n.isFunctionLike:Se(t.symbol),isTypeLike:n.isTypeLike??!1,kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosingSymbol??null}})}function Ah(e){return e.isFunctionLike}function Fh(e,t){if(!t)return!1;try{return t(e)}catch{return!1}}function Nh(e,t){if(!t||e.length===0)return new Map;try{return t(e)}catch{return new Map}}function $P(e,t){return{referencesForDefinitions:n=>UP(e,t,n)}}function jP(e,t){return{calleesForDefinitions:n=>qP(e,t,n)}}function HP(e,t){return{signaturesForDefinitions:n=>GP(e,t,n)}}function UP(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:du(r),references:Lr(n)};let i=lu();if(!su(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,references:Lr(n)};let o=bi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,au),s=va(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),a=bi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,cu),c=va(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),l=Ro(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!0}),u={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,...s>0?{referenceRetryTimeoutMs:s}:{},diagnosticsTimeoutMs:c,settleDelayMs:l,concurrency:a},d=ou(process.execPath,[i],{cwd:e,input:JSON.stringify(u),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Ir(n.length,iu(o,u.referenceRetryTimeoutMs),a)}),m=mu(d.stdout);if(m)return{...uu(m),resolvedBinary:r.resolvedBinary,references:Yn(n,new Map(m.references),new Set(m.incompleteReferenceSymbolIds??[]))};let p=d.error instanceof Error?d.error.message:d.stderr.trim()||`Rust semantic worker exited with status ${d.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:p,references:Lr(n)}}function qP(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:du(r),callees:Pr(n)};let i=lu();if(!su(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,callees:Pr(n)};let o=bi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,au),s=bi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,cu),a=va(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=Ro(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!0}),l={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:s,includeReferences:!1,includeCallees:!0},u=ou(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Ir(n.length,o,s)}),d=mu(u.stdout);if(d)return{...uu(d),resolvedBinary:r.resolvedBinary,callees:yi(n,new Map(d.callees??[]),void 0)};let m=u.error instanceof Error?u.error.message:u.stderr.trim()||`Rust semantic worker exited with status ${u.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:m,callees:Pr(n)}}function GP(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:du(r),signatures:Sa(n)};let i=lu();if(!su(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,signatures:Sa(n)};let o=bi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,au),s=bi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,cu),a=va(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=Ro(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!1,includeSignatures:!0}),l={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:s,includeReferences:!1,includeCallees:!1,includeSignatures:!0},u=ou(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Ir(n.length,o,s)}),d=mu(u.stdout);if(d)return{...uu(d),resolvedBinary:r.resolvedBinary,signatures:Oh(n,new Map(d.signatures??[]))};let m=u.error instanceof Error?u.error.message:u.stderr.trim()||`Rust semantic worker exited with status ${u.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:m,signatures:Sa(n)}}function zP(e,t,n){let r=n.referenceDefinitions.length>0?e.referencesForDefinitions(n.referenceDefinitions):{available:!0,references:Lr(n.referenceDefinitions)},i=n.calleeDefinitions.length>0?t.calleesForDefinitions(n.calleeDefinitions):{available:!0,callees:Pr(n.calleeDefinitions)},o={resolvedBinary:r.resolvedBinary??i.resolvedBinary,references:r.references,callees:i.callees};return r.available&&i.available?{available:!0,...o}:{available:!1,reason:(r.available?void 0:r.reason)??(i.available?void 0:i.reason)??"Rust semantic resolution was unavailable.",...o}}function Lr(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Pr(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Sa(e){return new Map(e.map(t=>[t.symbolId,null]))}function yi(e,t,n){let r=0,i=0;return N("rust.semantic.callees.complete-map",()=>{let o=new Map;for(let s of e){let a=t.get(s.symbolId)??[];a.length>0&&(r+=1),i+=a.length,o.set(s.symbolId,a.map(c=>({...c,symbol:n?n(c):c.symbol})))}return o},()=>({definitions:e.length,rows:r,callees:i,resolveSymbols:!!n}))}function Oh(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function lu(){return _P(new URL("./rust-semantic-worker.js",import.meta.url))}function uu(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function du(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function mu(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;if(typeof n.available!="boolean"||!Array.isArray(n.references)||n.available===!1&&typeof n.reason!="string"||n.available===!0&&n.reason!==void 0)return null;let r={references:n.references,incompleteReferenceSymbolIds:Array.isArray(n.incompleteReferenceSymbolIds)?n.incompleteReferenceSymbolIds.filter(i=>typeof i=="number"):void 0,callees:Array.isArray(n.callees)?n.callees:void 0,signatures:Array.isArray(n.signatures)?n.signatures:void 0};return n.available===!0?{available:!0,...r}:{available:!1,reason:String(n.reason),...r}}catch{return null}}function bi(e,t){return Vn(e)??t}function va(e,t){if(!e)return t;let n=Number(e);return Number.isInteger(n)&&n>=0?n:t}import{existsSync as KP}from"fs";import{deserializeSCIP as WP,SymbolRole as VP}from"@c4312/scip";var pu=new WeakMap;function $h(e,t){let n=t.filter(YP);if(n.length===0)return new Map;let r=!1,i=0,o=0;return N("rust.scip-occurrence.callees",()=>{let s=QP(e);if(r=!!s,!s)return new Map;let a=new Map;for(let c of n){let l=JP(e,s,c);l!==null&&(a.set(c.symbolId,l),i+=1,o+=l.length)}return a},()=>({definitions:t.length,candidates:n.length,indexAvailable:r,resolvedDefinitions:i,resolvedCallees:o}))}function YP(e){return!(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||!e.isFunctionLike||e.leaf==="main"||je(e.symbol))}function JP(e,t,n){let r=K(e,n.relativePath);if(!r||r.language!=="rust")return null;let i=r.callables.find(l=>l.startLine!==n.startLine||l.endLine!==n.endLine?!1:l.name===n.leaf||n.leaf.endsWith(l.name)||l.name.endsWith(n.leaf));if(!i)return null;let o=r.callSites.filter(l=>l.line>=i.startLine&&l.line<=i.endLine);if(o.length===0)return null;let s=(t.occurrencesByFile.get(n.relativePath)??[]).filter(l=>l.line>=i.startLine&&l.line<=i.endLine&&l.callee.symbol!==n.symbol);if(s.some(l=>l.traitImplMember)||!XP(o,s))return null;let a=[],c=new Set;for(let l of s){let u=`${l.callee.symbol}\0${l.callee.file}\0${l.callee.line}`;c.has(u)||(c.add(u),a.push(l.callee))}return a}function XP(e,t){let n=Bh(e),r=Bh(t);if(n.size!==r.size)return!1;for(let[i,o]of n)if(r.get(i)!==o)return!1;return!0}function Bh(e){let t=new Map;for(let n of e){let r=n.calleeLeaf??n.leaf;if(!r)continue;let i=`${n.line}\0${r}`;t.set(i,(t.get(i)??0)+1)}return t}function QP(e){if(pu.has(e))return pu.get(e)??null;let t=ZP(e);return pu.set(e,t),t}function ZP(e){if(!e.generation.indexPath||!KP(e.generation.indexPath))return null;try{let t=Le(e).filter(o=>o.symbol.startsWith("rust-analyzer ")&&o.relativePath.endsWith(".rs")&&o.isFunctionLike),n=new Map(t.map(o=>[o.symbol,o])),r=WP(Qr(e.generation.indexPath,{inputKind:"SCIP occurrence-callee index",maxBytes:Xr})),i=new Map;for(let o of r.documents??[]){let s=o.relativePath;if(!s||!s.endsWith(".rs")||e.isIgnored(s))continue;let a=[];for(let c of o.occurrences??[]){if(!c.symbol||(c.symbolRoles&VP.Definition)!==0)continue;let l=n.get(c.symbol);if(!l)continue;let u=c.range?.[0];Number.isInteger(u)&&a.push({line:u,leaf:l.leaf,traitImplMember:je(l.symbol),callee:{symbol:l.symbol,file:l.relativePath,line:l.startLine,callsiteLine:u}})}i.set(s,a)}return{occurrencesByFile:i}}catch{return null}}var Ca=class{sessions=new WeakMap;getOrCreate(t,n,r){let i=eD(t,n),o=this.sessions.get(t);o||(o=new Map,this.sessions.set(t,o));let s=o.get(i);if(s)return s.hits+=1,s.lastUsedAtMs=Date.now(),s.provider;let a=Date.now(),c=r();return o.set(i,{key:i,language:n,projectRoot:t.config.projectRoot,provider:c,createdAtMs:a,lastUsedAtMs:a,hits:1}),c}sessionsFor(t){return[...this.sessions.get(t)?.values()??[]]}clear(t){let n=this.sessions.get(t);if(n)for(let r of n.values())r.provider.dispose?.();this.sessions.delete(t)}};function eD(e,t){return`${e.config.projectRoot}:${t}-workspace`}import{randomUUID as PD}from"crypto";import{existsSync as DD}from"fs";import{dirname as MD}from"path";function jh(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.available!="boolean"||t.dependencyAvailable!==void 0&&typeof t.dependencyAvailable!="boolean"||t.tsconfigPath!==void 0&&typeof t.tsconfigPath!="string"||t.tsconfigPaths!==void 0&&(!Array.isArray(t.tsconfigPaths)||!t.tsconfigPaths.every(n=>typeof n=="string"))||t.resolvedBinary!==void 0&&typeof t.resolvedBinary!="string"||t.note!==void 0&&typeof t.note!="string")return null;if(t.available===!0){if(t.reason!==void 0)return null}else if(typeof t.reason!="string"||t.reason.length===0)return null;return t}import{performance as le}from"perf_hooks";function Dt(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}import qh from"path";import{realpathSync as Hh}from"fs";function tD(e,t){return e.getReferences().map(n=>{let r=n.getNode();return xa(r,t)})}function nD(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function Gh(e,t,n,r){let i=[];for(let o of nD(e))for(let s of tD(o,r))s.file===t.relativePath&&s.line>=t.startLine&&s.line<=t.endLine||i.push(s);for(let o of n)i.push(o);return Si(i)}function zh(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();vi(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:xa(a,r),node:a}))}return i}function xa(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:vi(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function Kh(e,t,n){let r=e.getSourceFile(),i=gu(r,e),o=e.getText(),s=new RegExp(`\\b${Ce(o)}\\b`,"g"),a=r.getFullText().split(`
|
|
51
|
-
`),c=[];for(let l=0;l<a.length;l++){if(l===i)continue;let u=a[l]??"";s.lastIndex=0;let d;for(;(d=s.exec(u))!==null;)c.push({file:t,line:l,column:d.index})}return Si(c.filter(l=>vi(n,qh.join(n,l.file))===t))}function fu(e){for(let t=e;t;t=t.getParent()){let n=t.getKindName();if(n.includes("Type")||n==="InterfaceDeclaration"||n==="TypeAliasDeclaration")return!0;if(n==="CallExpression"||n==="NewExpression"||n==="ExpressionStatement")return!1}return!1}function gu(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function Si(e){let t=new Set,n=[];for(let r of e){let i=`${r.file}:${r.line}:${r.column}`;t.has(i)||(t.add(i),n.push(r))}return n}function vi(e,t){let n=e||process.cwd(),r=Uh(n,t);if(r)return r;try{return Uh(Hh(n),Hh(t))}catch{return null}}function Uh(e,t){let n=qh.relative(e,t).replace(/\\/g,"/");return!n||n===".."||n.startsWith("../")?null:n}function Wh(e,t,n,r){let i=rD(t,r);return i.size===0?new Map:iD(e,n,i)}function rD(e,t){let n=new Map;for(let r of U(e,t)){let i=z(r.symbol)??r.leaf;if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return n}function iD(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of oD(e,o)){let a=n.get(s);if(!a)continue;let c=gu(t,o);for(let l of a){if(c<l.startLine-1||c>l.endLine+1)continue;let u=Math.abs(c-l.startLine),d=i.get(l.symbolId);d!==void 0&&d<=u||(i.set(l.symbolId,u),r.set(l.symbolId,o))}}}),r}function oD(e,t){let n=[],r=i=>{i&&!n.includes(i)&&n.push(i)};if("getNameNode"in t&&typeof t.getNameNode=="function"){let i=t.getNameNode();r(i?.getText())}if("getName"in t&&typeof t.getName=="function"){let i=t.getName();r(i)}return e.Node.isIdentifier(t)&&r(t.getText()),n}var sD=An("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function Vh(e,t,n,r){let i=bu(e,t),o=hu(i.get(r)??[],n);if(o)return o;let s=[];for(let a of i.values())for(let c of a)((c.leaf||z(c.symbol)||"").includes(r)||c.symbol.includes(r))&&s.push(c);return hu(s,n)}function yu(e,t,n,r){return hu(bu(e,t).get(r)??[],n)}function Yh(e,t){let n=new Map;for(let[r,i]of bu(e,t)){let o=i[0];o&&n.set(r,o)}return n}function bu(e,t){return sD.get(e,t,()=>{let n=new Map;for(let r of U(e,t)){let i=r.leaf||z(r.symbol);if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push({...r,leaf:i})}for(let r of n.values())r.sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine||i.symbolId-o.symbolId);return n})}function hu(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let i of e){let o=Math.abs(i.startLine-t);(o<r||o===r&&n&&i.startLine<n.startLine)&&(n=i,r=o)}return n}import aD from"path";import{realpathSync as cD}from"fs";function Jh(e,t){let n=new Map,r=null,i=null,o=()=>(i??=Z(e,{extensions:Ks}),i),s=()=>(r??=N("typescript.source-file-index",()=>lD(e.config.projectRoot,t,o()),()=>({projects:t.length,indexedDocuments:o().length})),r),a=c=>Un(c)?Dt(n,c,()=>{let l=Xh(e.config.projectRoot,c);if(!l)return null;for(let{project:u,sourceFiles:d}of s()){let m=d.get(l)??null;if(m||(m=u.addSourceFileAtPathIfExists(l)??null,m&&Su(d,m)),m)return{project:u,sourceFile:m}}return null}):null;return{sourceFile:c=>a(c)?.sourceFile??null,sourceFileMatch:a,indexedTypeScriptLikeDocuments:o}}function lD(e,t,n){let r=t.map(({project:i})=>{let o=new Map;for(let s of i.getSourceFiles())Su(o,s);return{project:i,sourceFiles:o}});for(let i of n){let o=Xh(e,i);if(o)for(let s of r){if(s.sourceFiles.has(o))break;let a=s.project.addSourceFileAtPathIfExists(o)??null;if(a){Su(s.sourceFiles,a);break}}}return r}function Su(e,t){let n=vu(t.getFilePath());e.set(n,t);try{e.set(vu(cD(n)),t)}catch(r){if(!Je(r))throw r}}function Xh(e,t){try{return vu(Ps(e,t,{inputKind:"indexed TypeScript source file"}).absolutePath)}catch(n){if(!Je(n))throw n;return null}}function vu(e){return aD.resolve(e)}function Cu(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Qh(e){let t=`${e.relativeDir}/src`;return[`${t}/index.ts`,`${t}/index.tsx`,`${t}/index.mts`,`${t}/index.cts`]}import{existsSync as wo}from"fs";import Ze from"path";var xu=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Ru(e,t){let r=t?Ze.dirname(Ze.join(e,t)):e,i=Ze.resolve(e);for(;r.startsWith(i);){for(let s of xu){let a=Ze.join(r,s);if(wo(a))return a}let o=Ze.dirname(r);if(o===r)break;r=o}for(let o of xu){let s=Ze.join(e,o);if(wo(s))return s}return null}function Zh(e){let t=e.config.projectRoot,n=new Set(uD(t,e.config.semantic?.typescript?.tsconfigs)),r=Z(e,{includeIgnored:!1,extensions:Ks});for(let i of r){let o=Ru(t,i);o&&n.add(Ze.resolve(o))}if(n.size===0){let i=Ru(t);i&&n.add(Ze.resolve(i))}return[...n].filter(i=>!ey(t,i)).sort((i,o)=>i.localeCompare(o))}function uD(e,t=[]){let n=new Set;for(let r of t){let i=Ze.isAbsolute(r)?r:Ze.join(e,r);wo(i)&&n.add(Ze.resolve(i))}for(let r of dD(e))for(let i of xu){let o=Ze.join(r,i);wo(o)&&n.add(Ze.resolve(o))}if(n.size===0){let r=Ru(e);r&&n.add(Ze.resolve(r))}return[...n].filter(r=>!ey(e,r)).sort((r,i)=>r.localeCompare(i))}function dD(e){let t=Ze.join(e,"package.json");if(!wo(t))return[];let n;try{n=JSON.parse(Ve(t,"project package manifest"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>rf(e,i))}function ey(e,t){let n=Ze.relative(e,t).replace(/\\/g,"/");return n.startsWith("..")||n.includes("/node_modules/")||n.startsWith("node_modules/")||n.includes("/dist/")||n.startsWith("dist/")}var mD=32;function sy(e,t){let n=N("typescript.provider.load",()=>Ws());if(!n)return Vs("ts-morph is not installed");let r=N("typescript.provider.tsconfig-discovery",()=>Zh(e));if(r.length===0)return Vs("no tsconfig found");try{let i=N("typescript.provider.project-bundles",()=>Bf(n,r),()=>({tsconfigs:r.length}));return pD(e,n,i)}catch(i){return Vs(i instanceof Error?i.message:String(i),r[0],r)}}function pD(e,t,n,r={}){return N("typescript.provider.construct",()=>new Eu(e,t,n),()=>({tsconfigs:n.length,reusedProjects:r.reusedProjects===!0}))}var Eu=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=nf(t.config.projectRoot),this.sourceFiles=Jh(t,r)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(t=>t.tsconfigPath)}}importUsage(t){return Dt(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let r=gD();return N("typescript.import-usage.file",()=>this.importUsageForSourceFile(t,n,r),()=>({file:t,...r}))})}referencesFor(t){return Dt(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);return this.referencesForDefinitionNode(t,n)})}referencesForDefinitions(t,n={}){let r=new Map,i=be(),o=[];for(let u of t){let d=this.referencesCache.get(u.symbolId);d?r.set(u.symbolId,d):o.push(u)}if(o.length===0)return r;let s=o,a=n.exact?[]:o.filter(u=>!ny(u));if(a.length>=mD){let u=this.referencesForDefinitionsBySymbolScan(a);for(let d of a){let m=u.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),r.set(d.symbolId,m)}if(s=o.filter(d=>ny(d)),s.length===0)return r}let c=new Map;for(let u of s){let d=c.get(u.relativePath);d?d.push(u):c.set(u.relativePath,[u])}let l=[];for(let[u,d]of c){let m=ry();N("typescript.references-map.file",()=>{let p=this.definitionNodesForFile(u);for(let f of d){i&&(m.cacheMisses+=1);let g=p.get(f.symbolId)??null;i&&(g?m.nodeHits+=1:m.nodeMisses+=1);try{let h=this.referencesForDefinitionNode(f,g,i?m:void 0);this.referencesCache.set(f.symbolId,h),r.set(f.symbolId,h)}catch{m.preciseSearchFailures+=1,l.push(f)}}},()=>({relativePath:u,definitions:d.length,...iy(m)}))}if(l.length>0){let u=this.referencesForDefinitionsBySymbolScan(l);for(let d of l){let m=u.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),r.set(d.symbolId,m)}}return r}referenceFragmentsForFiles(t){let n=Le(this.db).filter(o=>Un(o.relativePath)),r=t.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(n,r);return $f(n,i,r)}referencesForDefinitionsBySymbolScan(t,n){let r=be(),i=ry(),o=new Map,s=new Set(t.map(c=>c.symbolId)),a=new Map(t.map(c=>[c.symbolId,c]));for(let c of t)o.set(c.symbolId,[]);return N("typescript.references-map.inverted-scan",()=>{let c=r?le.now():0,l=n?this.packageImportReferencesForFiles(n):this.packageImportReferences();for(let h of t){let b=l.get(h.symbolId)??[];if(b.length>0){let S=o.get(h.symbolId)??[];S.push(...b),o.set(h.symbolId,S)}r&&(i.packageReferenceCount+=b.length)}r&&(i.packageRefsMs+=le.now()-c);let u=new Map,d=new Map,m=this.hierarchyTargetsForDefinitions(t),p=new Set(t.map(h=>h.leaf).filter(Boolean)),f=r?le.now():0;for(let h of n??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(h))continue;let b=this.sourceFiles.sourceFile(h);b&&(r&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(b,h,s,a,m,p,u,d,o,r?i:void 0))}r&&(i.scanMs+=le.now()-f);let g=r?le.now():0;this.addHierarchyMemberReferences(t,o,r?i:void 0),r&&(i.hierarchyMs+=le.now()-g);for(let[h,b]of o){let S=Si(b);o.set(h,S),r&&(i.referenceCount+=S.length)}},()=>({definitions:t.length,...iy(i)})),o}addReferencesFromSourceFileScan(t,n,r,i,o,s,a,c,l,u){let d=this.compilerCheckerForSourceFile(t),m=t.compilerNode,p=bD(t),f=g=>{if(this.tsMorph.ts.isIdentifier(g)){if(u&&(u.identifiers+=1),!s.has(g.text)&&!p.has(g.text)){this.tsMorph.ts.forEachChild(g,f);return}let h=this.compilerReferenceSymbol(d,g,u);if(h){let b;a.has(h)?b=a.get(h)??null:(b=this.referenceDefinitionFromCompilerSymbol(h),a.set(h,b)),u&&(b?u.targetHits+=1:u.targetMisses+=1);let S=Dt(c,h,()=>this.compilerSymbolKeys(h)),y=null,x=null,v=b&&r.has(b.symbolId)?i.get(b.symbolId):void 0;if(v&&(y=Ra(m,g),!ty(v,n,y))){let C=m.getLineAndCharacterOfPosition(g.getStart(m));x={file:n,line:C.line,column:C.character};let R=l.get(v.symbolId)??[];R.push(x),l.set(v.symbolId,R),u&&(u.requestedHits+=1)}for(let C of S)for(let R of o.get(C)?.values()??[]){if(y??=Ra(m,g),ty(R,n,y))continue;if(!x){let w=m.getLineAndCharacterOfPosition(g.getStart(m));x={file:n,line:w.line,column:w.character}}let E=l.get(R.symbolId)??[];E.push(x),l.set(R.symbolId,E),u&&(u.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(g,f)};f(m)}hierarchyTargetsForDefinitions(t){let n=new Map;for(let r of t){let i=this.nodeForDefinition(r),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let s=o.parent;if(!this.isHierarchyContainer(s))continue;let a=this.compilerCheckerForSourceFile(i.getSourceFile()),c=a.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(a,s,c))for(let u of this.compilerSymbolKeys(l)){let d=n.get(u)??new Map;d.set(r.symbolId,r),n.set(u,d)}}return n}hierarchyMemberSymbols(t,n,r){let i=new Set,o=new Set,s=(a,c,l)=>{if(!o.has(a)){o.add(a),i.add(c);for(let u of l){let d=u.getProperty(r.name);d&&s(u,d,this.hierarchyAncestorTypesForType(t,u))}}};return s(t.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(t,n)),i}addHierarchyMemberReferences(t,n,r){let i=new Map;for(let o of t){let s=this.nodeForDefinition(o),a=s?.compilerNode;if(!a||!this.isHierarchyMethod(a))continue;let c=a.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(s.getSourceFile()),u=l.getSymbolAtLocation(a.name);if(!u)continue;let d=a.getSourceFile(),m=d.getLineAndCharacterOfPosition(a.name.getStart(d)),p={definition:o,location:{file:o.relativePath,line:m.line,column:m.character}},f=n.get(o.symbolId)??[];for(let h of this.hierarchyMemberSymbols(l,c,u))if(h!==u)for(let b of this.compilerSymbolLocations(h))f.push(b),r&&(r.hierarchyReferences+=1);n.set(o.symbolId,f);let g=this.hierarchyRootMemberSymbols(l,c,u);for(let h of g){let b=i.get(h)??new Map;b.set(o.symbolId,p),i.set(h,b)}r&&(r.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){r&&(r.hierarchyFamilies+=1);for(let{definition:s}of o.values()){let a=n.get(s.symbolId)??[];for(let c of o.values())c.definition.symbolId!==s.symbolId&&(a.push(c.location),r&&(r.hierarchyReferences+=1));n.set(s.symbolId,a)}}}hierarchyRootMemberSymbols(t,n,r){let i=new Set,o=new Set,s=(a,c,l)=>{if(o.has(a))return;o.add(a);let u=!1;for(let d of l){let m=d.getProperty(r.name);m&&(u=!0,s(d,m,this.hierarchyAncestorTypesForType(t,d)))}if(!u)for(let d of this.compilerSymbolKeys(c))i.add(d)};return s(t.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(t,n)),i}compilerSymbolKeys(t){return(t.declarations??[]).map(n=>{let r=n.getSourceFile();return`${r.fileName}\0${n.getStart(r)}\0${t.name}`})}compilerSymbolLocations(t){let n=[];for(let r of t.declarations??[]){let i=r.getSourceFile(),o=vi(this.db.config.projectRoot,i.fileName);if(!o)continue;let s=r.name,a=i.getLineAndCharacterOfPosition((s??r).getStart(i));n.push({file:o,line:a.line,column:a.character})}return n}baseTypes(t,n){try{return t.getBaseTypes(n)??[]}catch{return[]}}hierarchyAncestorTypes(t,n){let r=new Set(this.hierarchyAncestorTypesForType(t,t.getTypeAtLocation(n)));for(let i of n.heritageClauses??[])for(let o of i.types)r.add(t.getTypeAtLocation(o));return[...r]}hierarchyAncestorTypesForType(t,n){let r=new Set(this.baseTypes(t,n));for(let i of n.getSymbol()?.declarations??[])if(this.isHierarchyContainer(i))for(let o of i.heritageClauses??[])for(let s of o.types)r.add(t.getTypeAtLocation(s));return[...r]}isHierarchyMethod(t){return this.tsMorph.ts.isMethodDeclaration(t)||this.tsMorph.ts.isMethodSignature(t)}isHierarchyContainer(t){return this.tsMorph.ts.isClassDeclaration(t)||this.tsMorph.ts.isClassExpression(t)||this.tsMorph.ts.isInterfaceDeclaration(t)}compilerReferenceSymbol(t,n,r){r&&(r.symbolLookups+=1);let i=t.getSymbolAtLocation(n);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return r&&(r.aliasResolutions+=1),t.getAliasedSymbol(i)}catch{return i}}}calleesFor(t){return Dt(this.calleesCache,t.symbolId,()=>Dt(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}calleesForDefinitions(t){let n=new Map,r=new Map;for(let i of t){let o=r.get(i.relativePath);o?o.push(i):r.set(i.relativePath,[i])}for(let[i,o]of r){let s=this.fileCalleesCache.get(i),a=new Set(o.map(l=>l.symbolId)),c=s??this.calleeMapForFile(i,a);for(let l of o){let u=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,u),n.set(l.symbolId,u)}}return n}referencesForDefinitionNode(t,n,r){let i=r?le.now():0,o=this.packageImportReferencesForDefinition(t);if(r&&(r.packageRefsMs+=le.now()-i,r.packageReferenceCount+=o.length),!n)return o;let s=r?le.now():0,a=Gh(n,t,o,this.db.config.projectRoot);return r&&(r.semanticRefsMs+=le.now()-s,r.referenceCount+=a.length),a}signatureFor(t){return Dt(this.signatureCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);if(!n||!this.tsMorph.Node.isFunctionDeclaration(n)&&!this.tsMorph.Node.isMethodDeclaration(n)&&!this.tsMorph.Node.isArrowFunction(n)&&!this.tsMorph.Node.isFunctionExpression(n)&&!this.tsMorph.Node.isConstructorDeclaration(n))return null;let r=n.getType().getCallSignatures()[0];if(!r)return null;let i=r.getParameters().map(s=>{let a=s.getDeclarations()[0],c=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return oy(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${oy(o)}`})}importUsageForSourceFile(t,n,r){let i=[],o=new Map;for(let s of n.getImportDeclarations()){r.declarations+=1;let a=bl(this.db,t,s.getModuleSpecifierValue()),c=s.getImportClause()?.isTypeOnly()??!1;for(let l of Iu(s)){r.entries+=1;let u=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(u?r.bindingSymbols+=1:r.missingBindingSymbols+=1);let d={sourcePath:a,entry:l,typeOnlyDeclaration:c,bindingSymbol:u,references:[]};if(i.push(d),c||!l.localName||!u)continue;let m=o.get(l.localName);m?m.push(d):o.set(l.localName,[d])}}return o.size>0&&n.forEachDescendant(s=>{if(s.getKindName()!=="Identifier")return;let a=o.get(s.getText());if(!a||hD(s))return;r.scannedIdentifiers+=1;let c=s.getSymbol()?.compilerSymbol;if(r.symbolLookups+=1,!!c){for(let l of a)if(l.bindingSymbol===c){l.references.push({location:xa(s,this.db.config.projectRoot),node:s}),r.matchedReferences+=1;break}}}),i.map(s=>s.typeOnlyDeclaration?fD(t,s.sourcePath,s.entry):s.entry.identifier&&!s.bindingSymbol?(r.fallbackEntries+=1,this.valueImportUsageForEntry(t,s.sourcePath,s.entry)):this.valueImportUsageFromLocations(t,s.sourcePath,s.entry,s.references))}valueImportUsageForEntry(t,n,r){let i=r.identifier?r.identifier.findReferences():[],o=[];for(let s of i)for(let a of zh(s,t,r.identifier,this.db.config.projectRoot))o.push(a);return this.valueImportUsageFromLocations(t,n,r,o)}valueImportUsageFromLocations(t,n,r,i){let o=i.some(c=>!fu(c.node)),s=i.some(c=>fu(c.node)),a=r.isTypeOnly;return{importer:t,sourcePath:n,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:a,isUsed:a||i.length>0,isTypeUsed:a||s,isValueUsed:o,references:i.map(c=>c.location)}}packageImportReferencesForDefinition(t){return this.packageImportReferences().get(t.symbolId)??[]}packageImportReferencesForFiles(t){let n=new Map,r=new Set;for(let o of t){let s=this.sourceFiles.sourceFile(o);if(s)for(let a of s.getImportDeclarations()){let c=Cu(this.workspacePackages,a.getModuleSpecifierValue());c&&r.add(c)}}if(r.size===0)return n;let i=this.packageExportsForNames(r);for(let o of t)this.addPackageImportReferencesForDocument(n,i,o);for(let[o,s]of n)n.set(o,Si(s));return n}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let t=new Map,n=this.packageExports();for(let r of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(t,n,r);for(let[r,i]of t)t.set(r,Si(i));return this.packageImportReferenceIndex=t,t}addPackageImportReferencesForDocument(t,n,r){if(this.db.isIgnored(r))return;let i=this.sourceFiles.sourceFileMatch(r);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(t,n,r,o)}addPackageImportReferencesForDeclaration(t,n,r,i){let o=Cu(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of Iu(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=Kh(a.identifier,r,this.db.config.projectRoot);l.length>0&&xD(t,c,l)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(t=>t.name))),this.packageExportIndex)}packageExportsForNames(t){let n=new Map;for(let r of this.workspacePackages){if(!t.has(r.name))continue;let i=new Map;for(let o of Qh(r))this.collectPackageExports(r,o,i,new Set);i.size>0&&n.set(r.name,i)}return n}collectPackageExports(t,n,r,i){if(i.has(n))return;i.add(n);let o=this.sourceFiles.sourceFile(n);if(o)for(let s of o.getExportDeclarations()){let a=s.getModuleSpecifierValue(),c=a?bl(this.db,n,a):n;if(!c||!c.startsWith(`${t.relativeDir}/src/`))continue;let l=s.getNamedExports();if(l.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(t,c,r,i);continue}for(let u of l){let d=u.getNameNode().getText(),m=u.getAliasNode()?.getText()??d,p=this.indexedDefinitionByLeaf(c,d);if(!p)continue;let f=r.get(m);f||(f=new Set,r.set(m,f)),f.add(p.symbolId)}}}indexedDefinitionByLeaf(t,n){return Dt(this.indexedDefinitionLeafCache,t,()=>Yh(this.db,t)).get(n)??null}nodeForDefinition(t){return Dt(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return Dt(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?Wh(this.tsMorph,this.db,n,t):new Map})}referenceDefinitionFromCompilerSymbol(t){return this.definitionFromCompilerSymbol(t,void 0,!0)}definitionFromCompilerSymbol(t,n,r=!1){let i=t.name,o=n?le.now():0,s=t.declarations??[];n&&(n.declarationsMs+=le.now()-o,n.declarationChecks+=s.length);for(let a of s){let c=n?le.now():0,l=a.getSourceFile(),u=vi(this.db.config.projectRoot,l.fileName),d=l.getLineAndCharacterOfPosition(a.getStart(l)).line;if(n&&(n.declarationLocationMs+=le.now()-c),!u||this.db.isIgnored(u))continue;let m=n?le.now():0,p=this.compilerDeclarationName(a),f=r?yu(this.db,u,d,i)??(p&&p!==i?yu(this.db,u,d,p):null):Vh(this.db,u,d,i);if(n&&(n.indexedLookupMs+=le.now()-m),f)return{symbolId:f.symbolId,symbol:f.symbol,file:f.relativePath,line:f.startLine}}return null}compilerDeclarationName(t){let n=t.name;return n&&this.tsMorph.ts.isIdentifier(n)?n.text:null}calleeMapForFile(t,n){let r=be(),i=0,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=r?vD():void 0;return N("typescript.callee-map.file",()=>{let p=r?le.now():0,f=this.sourceFiles.sourceFile(t);if(r&&(c=Math.round(le.now()-p)),!f)return new Map;let g=r?le.now():0,h=U(this.db,t).sort((E,w)=>E.startLine-w.startLine||w.endLine-E.endLine);if(r&&(l=Math.round(le.now()-g)),i=h.length,h.length===0)return new Map;let b=new Map,S=r?le.now():0,y=this.compilerCheckerForSourceFile(f),x=f.compilerNode;r&&(u=Math.round(le.now()-S));let v=new Map,C=E=>{if(this.tsMorph.ts.isCallExpression(E)||this.tsMorph.ts.isNewExpression(E)){r&&(o+=1);let w=this.semanticCalleeForCallNode(y,x,h,E,v,n,m);w&&(r&&(s+=1),yD(b,w.callerId,w.target))}this.tsMorph.ts.forEachChild(E,C)},R=r?le.now():0;C(x),r&&(d=Math.round(le.now()-R));for(let[E,w]of b)b.set(E,RD(w));return a=b.size,b},()=>({relativePath:t,definitions:i,callNodes:o,resolvedCallees:s,outputRows:a,requestedDefinitions:n?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:u,traversalMs:d,...m?CD(m):{}}))}semanticCalleeForCallNode(t,n,r,i,o,s,a){let c=a?le.now():0,l=SD(r,Ra(n,i));if(a&&(a.callerLookupMs+=le.now()-c),!l)return null;if(s&&!s.has(l.symbolId))return a&&(a.skippedUnrequestedCallers+=1),null;let u=i.expression,d=this.compilerSymbolForExpression(t,u,a),m=null;if(d)if(a&&(a.targetSymbolHits+=1),o.has(d))a&&(a.compilerSymbolCacheHits+=1),m=o.get(d)??null;else{a&&(a.compilerSymbolCacheMisses+=1);let p=a?le.now():0;m=this.definitionFromCompilerSymbol(d,a),a&&(a.targetLookupMs+=le.now()-p),o.set(d,m)}else a&&(a.targetMisses+=1);return m?{callerId:l.symbolId,target:{symbol:m.symbol,file:m.file,line:m.line,callsiteLine:Ra(n,i)}}:null}compilerSymbolForExpression(t,n,r){let i=r?le.now():0,o=t.getSymbolAtLocation(n);if(r&&(r.expressionSymbolMs+=le.now()-i),o)return o;r&&(r.typeFallbacks+=1);let s=r?le.now():0,a=t.getTypeAtLocation(n).getSymbol();return r&&(r.typeSymbolMs+=le.now()-s),a}compilerCheckerForSourceFile(t){let n=t.getProject(),r=this.compilerCheckerCache.get(n);return r||(r=n.getTypeChecker().compilerObject,this.compilerCheckerCache.set(n,r)),r}};function Iu(e){let t=[],n=e.getDefaultImport();n&&t.push({identifier:n,importedName:"default",localName:n.getText(),kind:"default",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});let r=e.getNamespaceImport();r&&t.push({identifier:r,importedName:"*",localName:r.getText(),kind:"namespace",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});for(let i of e.getNamedImports()){let o=i.getNameNode(),a=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);t.push({identifier:a,importedName:o.getText(),localName:a?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(e.getImportClause()?.isTypeOnly()??!1)})}return t.length===0&&t.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),t}function fD(e,t,n){return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function gD(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function hD(e){for(let t=e;t;t=t.getParent())if(t.getKindName()==="ImportDeclaration")return!0;return!1}function yD(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function bD(e){let t=new Set;for(let n of e.getImportDeclarations())for(let r of Iu(n))r.localName&&t.add(r.localName);return t}function SD(e,t){let n=null;for(let r of e)t<r.startLine||t>r.endLine||(!n||r.startLine>=n.startLine)&&(n=r);return n}function Ra(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line}function ty(e,t,n){return t===e.relativePath&&n>=e.startLine&&n<=e.endLine}function ny(e){return e.symbol.includes("#")?wt(e.symbol)==="type"&&e.relativePath.endsWith(".d.ts"):!1}function vD(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function CD(e){return{...e,callerLookupMs:Math.round(e.callerLookupMs),expressionSymbolMs:Math.round(e.expressionSymbolMs),typeSymbolMs:Math.round(e.typeSymbolMs),targetLookupMs:Math.round(e.targetLookupMs),declarationsMs:Math.round(e.declarationsMs),declarationLocationMs:Math.round(e.declarationLocationMs),indexedLookupMs:Math.round(e.indexedLookupMs)}}function ry(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}function iy(e){return{...e,scanMs:Math.round(e.scanMs),packageRefsMs:Math.round(e.packageRefsMs),semanticRefsMs:Math.round(e.semanticRefsMs),hierarchyMs:Math.round(e.hierarchyMs)}}function xD(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function RD(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}|${r.line}|${r.callsiteLine??""}`;t.has(i)||(t.add(i),n.push(r))}return n}function oy(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}import{join as ED}from"path";var Ci=3,ID=2,wD="typescript-semantic";function cy(e){let t=ED(e,wD),n=Gs(t);return{...n,requestDir:n.legacyRequestDir}}function G6(e){let t=JSON.parse(e),n=t.protocolVersion,r=n===ID;if(!r&&n!==Ci||typeof t.id!="string"||typeof t.generation!="string"||typeof t.deadlineAtMs!="number"||!Number.isFinite(t.deadlineAtMs)||t.profileEnvironment!==void 0&&!gl(t.profileEnvironment)||!t.request||!LD(t.request)||!r&&(t.mailboxVersion!==gn||typeof t.operationKey!="string"||!/^[a-f0-9]{64}$/.test(t.operationKey)||t.id!==xr(t.operationKey)||typeof t.clientId!="string"||!t.clientId||typeof t.enqueuedAtMs!="number"||!Number.isFinite(t.enqueuedAtMs)||t.deadlineAtMs<t.enqueuedAtMs))throw new Error("TypeScript semantic service received an invalid mailbox request.");if(!r){let o=t,s=Hn("typescript-semantic-v3",{generation:o.generation,profileEnvironment:o.profileEnvironment,request:o.request});if(o.operationKey!==s)throw new Error("TypeScript semantic service received a mismatched mailbox operation identity.");return o}let i=Hn("typescript-semantic-v2",{id:t.id,generation:t.generation,request:t.request});return{protocolVersion:Ci,mailboxVersion:gn,id:t.id,operationKey:i,clientId:"legacy-v2",enqueuedAtMs:t.deadlineAtMs,deadlineAtMs:t.deadlineAtMs,generation:t.generation,...t.profileEnvironment?{profileEnvironment:t.profileEnvironment}:{},request:t.request}}function LD(e){if(!e||typeof e!="object"||!("kind"in e))return!1;let t=e;switch(t.kind){case"availability":return!0;case"import-usage":return typeof t.file=="string";case"reference-fragments":return Yi(t.files)!==null;case"references":return ay(t.definitions)&&(t.exact===void 0||typeof t.exact=="boolean");case"callees":return ay(t.definitions);case"signature":return ly(t.definition);default:return!1}}function ay(e){return Array.isArray(e)&&e.every(ly)}function ly(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.symbolId=="number"&&typeof t.documentId=="number"&&typeof t.symbol=="string"&&typeof t.relativePath=="string"&&typeof t.leaf=="string"&&typeof t.startLine=="number"&&typeof t.endLine=="number"}var TD=12e4,kD=5;function my(e,t,n={}){let r=new wu(e,n),i=null,o=null,s=process.env.SCIP_QUERY_SKIP_WATCH_SERVICE==="1",a=()=>(i??=sy(e,t),i),c=(d,m,p)=>{if(s)return p();try{return m(r.request(d))}catch{return s=!0,p()}},l=(d,m)=>c({kind:"references",definitions:[...d],...m?.exact?{exact:!0}:{}},p=>dy(p),()=>a().referencesForDefinitions?.(d,m)??new Map(d.map(p=>[p.symbolId,a().referencesFor(p)]))),u=d=>c({kind:"callees",definitions:[...d]},m=>dy(m),()=>a().calleesForDefinitions?.(d)??new Map(d.map(m=>[m.symbolId,a().calleesFor(m)])));return{language:"typescript",availability:()=>(o??=c({kind:"availability"},ND,()=>a().availability()),o),importUsage:d=>c({kind:"import-usage",file:d},m=>m,()=>a().importUsage(d)),referencesFor:d=>l([d]).get(d.symbolId)??[],referencesForDefinitions:l,referenceFragmentsForFiles:d=>c({kind:"reference-fragments",files:[...d]},m=>FD(m),()=>a().referenceFragmentsForFiles?.(d)??new Map),calleesFor:d=>u([d]).get(d.symbolId)??[],calleesForDefinitions:u,signatureFor:d=>c({kind:"signature",definition:d},_D,()=>a().signatureFor(d)),dispose:()=>i?.dispose?.()}}var wu=class{constructor(t,n={}){this.db=t;this.runtime=n.runtime??BD,this.timeoutMs=n.timeoutMs??OD(),this.mailboxLimits=n.mailboxLimits??{},this.cacheDir=MD(t.config.dbPath),this.projectRoot=Hp(t.config.projectRoot)}db;runtime;timeoutMs;cacheDir;projectRoot;mailboxLimits;request(t){let n=Of(this.cacheDir),r=cy(this.cacheDir),i=xl(n.statePath);if(!uy(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript semantic service is not running.");let o=this.db.generation.identity;if(!o)throw new Error("Published TypeScript generation identity is unavailable.");let s=this.runtime.now(),a=s+this.timeoutMs,c=(this.runtime.monotonicNow??Lt)()+this.timeoutMs,l=sf(),u=Hn("typescript-semantic-v3",{generation:o,profileEnvironment:l,request:t}),d=xr(u),m=zs(r,{mailboxVersion:gn,operationKey:u,clientId:this.runtime.randomId(),enqueuedAtMs:s,deadlineAtMs:a,protocolVersion:Ci,id:d,generation:o,profileEnvironment:l,request:t},{nowMs:s,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??Lt)()<=c;){if(DD(m.responsePath))return AD(vt(m.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript semantic mailbox response"}),d,o,u);let p=xl(n.statePath);if(!uy(p,this.projectRoot,this.runtime))throw new Error("TypeScript semantic service stopped while processing a request.");this.runtime.sleep(kD)}throw new Error(`TypeScript semantic service timed out after ${this.timeoutMs}ms.`)}};function uy(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptSemantic?.protocolVersion===Ci&&n.isProcessAlive(e.pid)&&(!e.processIdentity||r!=null&&qs(e.processIdentity,r))}function AD(e,t,n,r){let i=JSON.parse(e);if(i.protocolVersion!==Ci||i.id!==t||i.operationKey!==r||i.ok===!0&&i.generation!==n)throw new Error("TypeScript semantic service wrote an incompatible response.");if(i.ok===!0)return i.response;throw new Error(typeof i.error=="string"?i.error:"TypeScript semantic service request failed.")}function dy(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid numeric map.");return new Map(e)}function FD(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid string map.");return new Map(e)}function ND(e){let t=jh(e);if(!t)throw new Error("TypeScript semantic service wrote invalid availability.");return t}function _D(e){if(e!==null&&typeof e!="string")throw new Error("TypeScript semantic service wrote an invalid signature.");return e}function OD(){let e=Number(process.env.SCIP_TYPESCRIPT_SEMANTIC_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:TD}var BD={now:Date.now,monotonicNow:Lt,randomId:PD,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:ci,readProcessIdentity:li};var py=new Ca;Xp({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>py.clear(e)});function Dr(e,t){let n=He(t)??"typescript";return py.getOrCreate(e,n,()=>n==="rust"?_h(e.config.projectRoot,{sourceImportUsageResolver:{importUsageFacts:r=>Zg(e,r)},calleeSymbolResolver:Qg(e),sourceZeroCalleeOracle:r=>$D(e,r),scipOccurrenceCalleeOracle:r=>$h(e,r)}):my(e,t))}function He(e){return e?se(e)==="rust"?"rust":Un(e)?"typescript":null:"typescript"}function $D(e,t){let n=K(e,t.relativePath);if(!n||n.language!=="rust")return!1;let r=n.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine&&i.name===t.leaf)??n.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine);return r?!n.callSites.some(i=>i.line>=r.startLine&&i.line<=r.endLine):!1}var jD=/^[A-Za-z_][A-Za-z0-9_]*$/,fy=/\bDefault::default\b/g,HD=/^\.\.\s*Default::default\b/;function gy(e,t){let n=new Map,r=new Map;for(let i of t){let o=Lu(e,i,r);o!==null&&n.set(i.symbolId,o)}return n}function Lu(e,t,n=new Map){let r=qD(t.symbol);if(!r)return null;let i=Hs(e,[t.symbolId]);if(i.length===0)return null;let o=new RegExp(`(^|[^A-Za-z0-9_])${Ce(r)}::default\\b`,"g"),s=new RegExp(`(^|[^A-Za-z0-9_])${Ce(r)}\\s*$`),a=UD(e,t.symbolId),c=[];for(let l of i){let u=GD(e,l.relative_path,n);if(u===null)return null;let d=u.split(/\r?\n/),m=0,p=[],f=0;for(let g=l.chunk_start;g<=l.chunk_end&&g<d.length;g+=1){let b=d[g]??"",S=new Set;o.lastIndex=0;let y;for(;y=o.exec(b);)c.push({file:l.relative_path,line:g,column:y.index+y[1].length+r.length+2}),f+=1;for(let x=0;x<b.length;x+=1){let v=HD.exec(b.slice(x));if(v){if(a&&p.includes(m)){let R=x+v[0].lastIndexOf("default");c.push({file:l.relative_path,line:g,column:R}),S.add(R),f+=1}x+=v[0].length-1;continue}let C=b[x];if(C==="{"){let R=s.test(b.slice(0,x));m+=1,R&&p.push(m);continue}if(C==="}")for(m=Math.max(0,m-1);p.length>0&&p[p.length-1]>m;)p.pop()}for(fy.lastIndex=0;y=fy.exec(b);){let x=y.index+9;if(!S.has(x))return null}}if(f===0)return null}return fa(c)}function UD(e,t){return e.get("SELECT 1 AS present FROM mentions WHERE symbol_id = ? AND role = 1 LIMIT 1",t)?.present===1}function qD(e){let t=/impl#\[([^\]]+)\]\[Default\]default\(\)\./.exec(e)?.[1]??null;return!t||!jD.test(t)?null:t}function GD(e,t,n){if(n.has(t))return n.get(t)??null;let r=e.get("SELECT text FROM documents WHERE relative_path = ?",t),i=typeof r?.text=="string"?r.text:zD(e,t);return n.set(t,i),i}function zD(e,t){try{return Ye(e.config.projectRoot,t,{inputKind:"indexed Rust source file"})}catch(n){if(!Je(n))throw n;return null}}var KD="typescript-import-usage-v1",WD="typescript-signatures-v1",Pu=ge("semantic-prefetched-callees",{clearGroups:["whole-project","source-file","semantic-provider"]}),hy=Ji({kind:"semantic-import-usage",invalidation:$e("semantic-import-usage"),serialize:e=>JSON.stringify(e),deserialize:Ly}),yy=Ji({kind:"semantic-signatures",invalidation:$e("semantic-signatures"),serialize:e=>JSON.stringify(e),deserialize:nM}),by=dt({kind:"typescript-import-usage",invalidation:$e("typescript-import-usage"),serialize:e=>JSON.stringify(e),deserialize:Ly}),Sy=dt({kind:"typescript-signatures",invalidation:$e("typescript-signatures"),serialize:e=>JSON.stringify(e),deserialize:rM});function st(e){let t=new Map,n=new Set;return{capability:(r,i)=>Py(e,r,i),importUsage:r=>YD(e,r),references:r=>xy(e,r),materializeReferences:(r,i)=>Ey(e,r,t,n,i),callerMap:r=>JD(e,r,t,n),calleeMap:r=>ZD(e,r),signature:r=>eM(e,r)}}function VD(e,t){if(t.size===0)return;let n=Pu.get(e,()=>new Map);for(let[r,i]of t)n.set(r,[...i])}function Cy(e,t){if(!Pu.has(e))return{hits:[],misses:[...t]};let n=Pu.get(e,()=>new Map),r=[],i=[];for(let o of t)n.has(o.symbolId)?r.push({definition:o,callees:n.get(o.symbolId)??[]}):i.push(o);return{hits:r,misses:i}}function Po(e,t){return st(e).importUsage(t)}function YD(e,t){if(He(t)==="typescript"){let o="fallback",s=0,a=0,c=0,l=0;return N("typescript.import-usage.materialize",()=>{let u=to(e,t,KD);if(u?.key){s=1;let m=by.read(e,t,u.key);if(m)return o="hit",a=1,m;c=1;let p=Yt(e,t);if(!p)return o="unavailable",[];let f=p.importUsage(t);return by.write(e,t,u.key,f),o="computed",f}l=1;let d=Yt(e,t);return d?(o="direct-fallback",d.importUsage(t)):(o="unavailable",[])},()=>({state:o,eligible:s,cacheHits:a,cacheMisses:c,fallbacks:l}))}let n=wy(e,"semantic-import-usage",t);if(n){let o=hy.read(e,t,n);if(o)return o}let r=Yt(e,t);if(!r)return[];let i=r.importUsage(t);return n&&hy.write(e,t,n,i),i}function Ea(e,t){return st(e).references(t)}function xy(e,t){let n=Lu(e,t);if(n)return n;let r=nh(e,t);if(r)return r;let i=Yt(e,t.relativePath);return i?i.referencesFor(t):[]}function Jn(e,t){return st(e).callerMap(t)}function Ry(e,t){let n=new Map,r=[];for(let i of t){if(He(i.relativePath)==="typescript"){r.push(i);continue}Du(e,n,i,xy(e,i))}if(r.length>0){let o=El(e,r,s=>Dr(e,s))?.references;if(!o){let s=Yt(e,r[0].relativePath);o=s?s.referencesForDefinitions?s.referencesForDefinitions(r,{exact:!0}):new Map(r.map(a=>[a.symbolId,s.referencesFor(a)])):new Map,s&&be()&&Rl(e,r,o,a=>Dr(e,a))}for(let s of r)Du(e,n,s,o.get(s.symbolId)??[])}return n}function JD(e,t,n=new Map,r=new Set){let i=new Map,o=Ey(e,t,n,r),s=0;return N("semantic.callers.from-references",()=>{for(let a of t)s+=Du(e,i,a,n.get(a.symbolId)??[])},()=>({definitions:t.length,materialized:o.definitions,inMemoryHits:o.inMemoryHits,incompleteInMemoryHits:o.incompleteInMemoryHits,resultRows:i.size,callerFiles:s})),i}function Ey(e,t,n,r,i={}){let o=mn(e),s=[],a=[],c=[],l=0,u=0,d=0,m=0,p=0,f=0,g=0,h=0,b=0,S=0,y=0,x=0,v=[],C=new Map,R=t.filter(w=>He(w.relativePath)==="typescript"&&!n.has(w.symbolId)&&!r.has(w.symbolId)),E=El(e,R,w=>Dr(e,w));if(E){b=R.length,S=E.cacheHits,y=E.cacheMisses,x=E.computedFiles;for(let w of R)n.set(w.symbolId,E.references.get(w.symbolId)??[])}if(N("semantic.references.cache-scan",()=>{for(let[w,I]of da(t)){let k=[];for(let L of I)n.has(L.symbolId)?u+=1:r.has(L.symbolId)?h+=1:k.push(L);if(k.length===0){g+=1;continue}let D=XD(e,o,w);if(!D){for(let L of k)He(L.relativePath)||(l+=1),c.push(L);continue}f+=1;let F=ef(e,w,D);for(let L of k){let A=F.get(L.symbol)??null;if(A!==null){let P=QD(A);if(P){d+=1,n.set(L.symbolId,P);continue}m+=1}a.push({definition:L,cacheFingerprint:D})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:l,cacheHits:d,parseFailures:m,misses:a.length,unkeyed:c.length,inMemoryHits:u,incompleteInMemoryHits:h,fullyInMemoryFiles:g,cacheReadFiles:f})),a.length>0||c.length>0){v=[...c,...a.map(w=>w.definition)],C=N("semantic.references.compute-misses",()=>{let w=Mu(e,v,i);return p=w.size,w},()=>({definitions:v.length,misses:a.length,unkeyed:c.length,rows:p}));for(let w of v)C.has(w.symbolId)?(n.set(w.symbolId,C.get(w.symbolId)??[]),r.delete(w.symbolId)):r.add(w.symbolId);for(let{definition:w,cacheFingerprint:I}of a)C.has(w.symbolId)&&Py(e,"semantic-references",w.relativePath).available&&s.push({relativePath:w.relativePath,symbol:w.symbol,projectFingerprint:I,payload:JSON.stringify(C.get(w.symbolId)??[])})}return s.length>0&&N("semantic.references.cache-write",()=>tf(e,s),()=>({entries:s.length})),C.size>0&&Rl(e,v,C,w=>Dr(e,w)),{definitions:t.length,inMemoryHits:u,incompleteInMemoryHits:h,cacheHits:d,misses:a.length,unkeyed:c.length,skippedUnsupportedLanguage:l,parseFailures:m,computed:p,incomplete:r.size,cacheWrites:s.length,fragmentDefinitions:b,fragmentCacheHits:S,fragmentCacheMisses:y,fragmentComputedFiles:x}}function XD(e,t,n){if(!t)return null;let r=He(n);return r==="typescript"?t:r==="rust"?qt(JSON.stringify({kind:"semantic-references",language:r,engine:wr(e.config.projectRoot),projectFingerprint:t})):null}function Mu(e,t,n={}){let r=be(),i=new Map,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=0,p=0;return N("semantic.references.provider-loop",()=>{let f=gy(e,t),g=th(e,t),h=new Map,b=n.prefetchCallees?new Map:null,S=[];for(let x of t){let v,C=()=>(v??=Yt(e,x.relativePath),v);if(b){let I=C();if(I?.referencesAndCalleesForDefinitions){let k=b.get(I);k?k.push(x):b.set(I,[x]),p+=1}}let R=f.get(x.symbolId);if(R){a+=1,c+=R.length,Lo(i,x.symbolId,R,r,I=>{d+=1,m+=I});continue}let E=g.get(x.symbolId);if(E){l+=1,u+=E.length,Lo(i,x.symbolId,E,r,I=>{d+=1,m+=I});continue}let w=C();if(!w){r&&(s+=1);continue}if(r&&(o+=1),w.referencesForDefinitions){let I=h.get(w);I?I.push(x):h.set(w,[x])}else S.push({provider:w,definition:x})}let y=new Set;if(b)for(let[x,v]of b){if(!x.referencesAndCalleesForDefinitions)continue;let C=h.get(x)??[],R=x.referencesAndCalleesForDefinitions(C,v);y.add(x),VD(e,R.callees);for(let E of C){if(!R.references.has(E.symbolId))continue;let w=R.references.get(E.symbolId)??[];Lo(i,E.symbolId,w,r,I=>{d+=1,m+=I})}}for(let[x,v]of h){if(y.has(x))continue;let C=x.referencesForDefinitions(v);for(let R of v){if(!C.has(R.symbolId))continue;let E=C.get(R.symbolId)??[];Lo(i,R.symbolId,E,r,w=>{d+=1,m+=w})}}for(let{provider:x,definition:v}of S){let C=x.referencesFor(v);Lo(i,v.symbolId,C,r,R=>{d+=1,m+=R})}return i},()=>({definitions:t.length,providerHits:o,providerMisses:s,rustDefaultFastPathRows:a,rustDefaultFastPathReferences:c,rustScipOccurrenceFastPathRows:l,rustScipOccurrenceFastPathReferences:u,prefetchCalleeDefinitions:p,definitionsWithReferences:d,referenceCount:m,rows:i.size}))}function Lo(e,t,n,r,i){e.set(t,n),r&&n.length>0&&i(n.length)}function Du(e,t,n,r){let i=0;for(let o of r){if(o.file===n.relativePath||e.isIgnored(o.file))continue;let s=t.get(n.symbolId);s||(s=new Set,t.set(n.symbolId,s));let a=s.size;s.add(o.file),s.size!==a&&(i+=1)}return i}function QD(e){try{return JSON.parse(e)}catch{return null}}function Ia(e,t){return st(e).calleeMap(t)}function ZD(e,t){let n=be(),r=new Map,i=0,o=0,s=0,a=0;return N("semantic.callees.provider-loop",()=>{let c=new Map,l=[];for(let u of t){let d=Yt(e,u.relativePath);if(!d){n&&(o+=1);continue}n&&(i+=1);let m=u;if(d.calleesForDefinitions){let p=c.get(d);p?p.push(m):c.set(d,[m])}else l.push({provider:d,definition:m})}for(let[u,d]of c){let m=u.calleesForDefinitions(d);for(let p of d){let f=m.get(p.symbolId)??[];vy(r,p.symbolId,f,n,g=>{s+=1,a+=g})}}for(let{provider:u,definition:d}of l){let m=u.calleesFor(d);vy(r,d.symbolId,m,n,p=>{s+=1,a+=p})}return r},()=>({definitions:t.length,providerHits:i,providerMisses:o,definitionsWithCallees:s,calleeCount:a,rows:r.size}))}function vy(e,t,n,r,i){n.length>0&&(e.set(t,n),r&&i(n.length))}function Iy(e,t){return st(e).signature(t)}function eM(e,t){if(He(t.relativePath)==="typescript"){let s="fallback",a=0,c=0,l=0,u=0;return N("typescript.signature.materialize",()=>{let d=to(e,t.relativePath,WD);if(d?.key){a=1;let p=Sy.read(e,t.relativePath,d.key)??{};if(Object.prototype.hasOwnProperty.call(p,t.symbol))return s="hit",c=1,p[t.symbol]??null;l=1;let f=Yt(e,t.relativePath);if(!f)return s="unavailable",null;let g=f.signatureFor(t);return Sy.write(e,t.relativePath,d.key,{...p,[t.symbol]:g}),s="computed",g}u=1;let m=Yt(e,t.relativePath);return m?(s="direct-fallback",m.signatureFor(t)):(s="unavailable",null)},()=>({state:s,eligible:a,cacheHits:c,cacheMisses:l,fallbacks:u}))}let n=wy(e,"semantic-signatures",t.relativePath),r=tM(t);if(n){let s=yy.read(e,r,n);if(s)return s.signature}let i=Yt(e,t.relativePath);if(!i)return null;let o=i.signatureFor(t);return n&&yy.write(e,r,n,{signature:o}),o}function wy(e,t,n){let r=mn(e);if(!r)return null;let i=He(n);return i!=="rust"?null:qt(JSON.stringify({kind:t,language:i,engine:wr(e.config.projectRoot),projectFingerprint:r}))}function tM(e){return`${e.relativePath}\0${e.symbol}`}function Ly(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:null}catch{return null}}function nM(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t.signature;return n!==null&&typeof n!="string"?null:{signature:n}}catch{return null}}function rM(e){try{let t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return null;for(let n of Object.values(t))if(n!==null&&typeof n!="string")return null;return t}catch{return null}}function Py(e,t,n){let r=He(n);if(!r)return{slot:t,language:"typescript",available:!1,reason:"semantic evidence is only available for TypeScript or Rust files"};try{return{slot:t,language:r,...Dr(e,n).availability()}}catch(i){return{slot:t,language:r,available:!1,reason:i instanceof Error?i.message:String(i)}}}function Yt(e,t){if(!He(t))return null;let n=Dr(e,t);return n.availability().available?n:null}var re={references:Ea,referenceMap:Mu,callerMap:(e,t)=>st(e).callerMap(t),calleeMap:Tu};function Tu(e,t){let n=be(),r=new Map,i=Cy(e,t),o=[],s=[],a=0,c=0,l=0,u=0,d=0,m=0,p=0;for(let{definition:y,callees:x}of i.hits)d+=1,x.length>0&&(m+=1,p+=x.length,r.set(y.symbolId,x));let f=iM(e,i.hits);if(f.entries.length>0&&N("semantic.callees.prefetch-cache-write",()=>yl(e,f.entries),()=>({entries:f.entries.length,sourceMissing:f.sourceMissing,skippedUnsupportedLanguage:f.skippedUnsupportedLanguage})),N("semantic.callees.cache-scan",()=>{for(let[y,x]of da(i.misses)){if(!He(y)){n&&(a+=x.length);continue}let v=W(e,y);if(!v){n&&(c+=x.length),s.push(...x);continue}let C=Rt(e,y,v),R=Dy(e,y);if(!R){s.push(...x);continue}let E=Zp(e,y,C,R);for(let w of x){let I=E.get(w.symbol)??null;if(I!==null){let k=sM(I);if(k){n&&(l+=1),k.length>0&&r.set(w.symbolId,k);continue}n&&(u+=1)}o.push({def:w,contentHash:C,depsDigest:R})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:a,sourceMissing:c,cacheHits:l,parseFailures:u,misses:o.length,unkeyed:s.length,inMemoryHits:d,inMemoryRows:m,inMemoryCalleeCount:p,resultRows:r.size})),o.length===0&&s.length===0)return r;let g=[...s,...o.map(y=>y.def)],h=0,b=N("semantic.callees.compute-misses",()=>{let y=Ia(e,g);return h=y.size,y},()=>({definitions:g.length,misses:o.length,unkeyed:s.length,rows:h}));for(let[y,x]of b)r.set(y,x);let S=o.filter(y=>st(e).capability("semantic-callees",y.def.relativePath).available).map(y=>({relativePath:y.def.relativePath,symbol:y.def.symbol,contentHash:y.contentHash,depsDigest:y.depsDigest,payload:JSON.stringify(b.get(y.def.symbolId)??[])}));return S.length>0?N("semantic.callees.cache-write",()=>yl(e,S),()=>({entries:S.length})):N("semantic.callees.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",misses:o.length})),r}function iM(e,t){let n=[],r=new Map,i=0,o=0;for(let{definition:s,callees:a}of t){if(!He(s.relativePath)){o+=1;continue}if(!r.has(s.relativePath)){let l=W(e,s.relativePath),u=l?Dy(e,s.relativePath):null;r.set(s.relativePath,l&&u?{contentHash:Rt(e,s.relativePath,l),depsDigest:u}:null)}let c=r.get(s.relativePath);if(!c){i+=1;continue}n.push({relativePath:s.relativePath,symbol:s.symbol,contentHash:c.contentHash,depsDigest:c.depsDigest,payload:JSON.stringify(a)})}return{entries:n,sourceMissing:i,skippedUnsupportedLanguage:o}}var oM="typescript-callees-v2-callsite-line";function Dy(e,t){let n=He(t);if(n==="typescript")return to(e,t,oM)?.key??null;let r=cM(e,t);return n==="rust"?qt(JSON.stringify({kind:"semantic-callees",language:n,engine:wr(e.config.projectRoot),positionMapping:"nearby-leaf-v2-callsite-line",depsDigest:r})):r}function sM(e){try{return JSON.parse(e)}catch{return null}}var aM=An("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function cM(e,t){return aM.get(e,t,()=>{let r=[...Me(e).get(t)??[]].sort().map(i=>`${i}:${Rt(e,i,W(e,i))}`);return qt(r.join("|"))})}function QZ(e,t,n={}){let r=ne(e,t);if(!r)return[];let o=!Se(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine}]:[],s=jn(e,r,{semantic:n.semantic,semanticEvidence:re}).map(u=>({relativePath:u.file,line:u.line})),a=lM(e,r),c=new Set,l=[];for(let u of[...o,...s,...a]){let d=`${u.relativePath}:${u.line}`;c.has(d)||(c.add(d),l.push(u))}return l}function lM(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=uM(t.symbol);if(n.length===0)return[];let r=[];for(let i of Z(e,{extensions:[".rb"],includeIgnored:!1})){let o=W(e,i);if(!o)continue;let s=o.split(`
|
|
52
|
-
`);for(let a=0;a<s.length;a++){let c=s[a]??"";n.some(l=>new RegExp(`@${l}\\b|\\b${l}:`).test(c))&&r.push({relativePath:i,line:a})}}return r}function uM(e){let n=(e.split(":").pop()??e).replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),r=n.split("_").filter(Boolean),i=new Set;return n&&i.add(n),r.length>=1&&i.add(r[r.length-1]),r.length>=2&&i.add(r.slice(-2).join("_")),[...i]}import{existsSync as Gu,statSync as $T}from"fs";import{join as jT}from"path";import{existsSync as Ri}from"fs";import{randomUUID as Ky}from"crypto";import{isAbsolute as UM,join as Sn,relative as qM,resolve as GM}from"path";var Xn=1,Qn=2,dM="./node_modules/scip-query/docs/schemas/project-config.schema.json";function ku(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(a){return{kind:"malformed",reason:`invalid JSON: ${a instanceof Error?a.message:String(a)}`}}if(!Q(t))return{kind:"malformed",reason:"project config must be a JSON object"};let n=t.schemaVersion;if(n!==void 0&&!Number.isInteger(n))return{kind:"malformed",reason:"schemaVersion must be an integer"};let r=n===void 0?Xn:n;if(r!==Xn&&r!==Qn)return{kind:"unsupported",schemaVersion:r,direction:r<Xn?"older":"future"};let i=t.$schema;if(i!==void 0&&(typeof i!="string"||i.trim()===""))return{kind:"malformed",reason:"$schema must be a non-empty string when present"};let o=wa(t),s=r!==Qn||typeof t.$schema!="string";return r===Xn?{kind:"legacy",sourceVersion:Xn,config:o,needsMigration:s}:{kind:"supported",sourceVersion:Qn,config:o,needsMigration:s}}function wa(e){let t=e,{$schema:n,schemaVersion:r,...i}=t;return{$schema:typeof n=="string"&&n.trim()!==""?n:dM,schemaVersion:Qn,...i}}function xi(e){return`${JSON.stringify(wa(e),null,2)}
|
|
53
|
-
`}import{createHash as mM}from"crypto";var Xt=1,er=2,Fy=1,_u=1,Nu="sha256",pM=1;function Tr(e,t,n){if(!Nt(e)||!Ms(t))throw new Error("Observation identity requires a bounded projection name and positive projection version.");return{schemaVersion:Fy,canonicalizationVersion:_u,hashAlgorithm:Nu,projection:{name:e,version:t},digest:mM(Nu).update(fM(e,t,n)).digest("hex")}}function fM(e,t,n){return`{"canonicalizationVersion":${_u},"projection":${JSON.stringify(e)},"projectionVersion":${t},"value":${JSON.stringify(n)}}`}function gM(e){if(!Q(e))return{kind:"malformed",reason:"observation receipt must be an object"};let t=e.schemaVersion;if(!Number.isInteger(t))return{kind:"malformed",reason:"observation receipt schemaVersion must be an integer"};if(t===Xt)return xM(e)?{kind:"legacy",schemaVersion:Xt,receipt:e}:{kind:"malformed",reason:"observation receipt v1 fields are malformed or contradictory"};if(t===er)return RM(e)?{kind:"supported",schemaVersion:er,receipt:e}:{kind:"malformed",reason:"observation receipt v2 facts are malformed or contradictory"};let n=t;return{kind:"unsupported",schemaVersion:n,direction:n<Xt?"older":"future"}}function La(e){let t=gM(e);return t.kind==="legacy"||t.kind==="supported"}function hM(e,t){return{collaborationDomain:Mr(Jt(e,n=>n.facts.collaborationDomain),Jt(t,n=>n.facts.collaborationDomain)),repositoryLineage:Mr(Jt(e,n=>n.facts.repositoryLineage),Jt(t,n=>n.facts.repositoryLineage)),workspaceInstance:Mr(Jt(e,n=>n.facts.workspaceInstance),Jt(t,n=>n.facts.workspaceInstance)),wholeContent:Mr(Jt(e,n=>n.facts.wholeContent),Jt(t,n=>n.facts.wholeContent)),relevantInputs:yM(e,t),indexInput:Mr(Jt(e,n=>n.facts.index?.inputs),Jt(t,n=>n.facts.index?.inputs)),indexGeneration:bM(e,t),observationStability:vM(e,t)}}function i8(e,t,n=hM(e,t)){let r=[["collaborationDomain",n.collaborationDomain],["wholeContent",n.wholeContent],["observationStability",n.observationStability]],i=[];for(let[s,a]of r)a.state!=="established"&&i.push(`${s}:${a.state}`);for(let[s,a]of[["left",e],["right",t]]){let c=CM(a);c!=="not-applicable"&&c!=="established"&&i.push(`${s}IndexAlignment:${c}`)}let o=r.some(([,s])=>s.state==="disproven")||i.some(s=>s.endsWith(":disproven"));return{policyVersion:pM,authority:i.length===0?"completion":o?"none":"advisory",requiredRelationships:["collaborationDomain","wholeContent","observationStability"],reasons:i}}function yM(e,t){let n=My(e),r=My(t);return[...new Set([...n.keys(),...r.keys()])].sort().map(o=>{let s=n.get(o),a=r.get(o),c=s?.subject??a?.subject??o,l=s?.identity.projection.name??a?.identity.projection.name??o;return{subject:c,projection:l,judgment:Mr(s?.identity,a?.identity)}})}function My(e){return e.schemaVersion!==er?new Map:new Map((e.facts.relevantInputs??[]).map(t=>[`${t.subject}\0${t.identity.projection.name}`,t]))}function bM(e,t){return e.schemaVersion===Xt&&t.schemaVersion===Xt?SM(e.index?.generationIdentity,t.index?.generationIdentity):e.schemaVersion===Xt||t.schemaVersion===Xt?bn("unknown",["legacy-fact-not-comparable"],ky(e),ky(t)):Mr(e.facts.index?.generation,t.facts.index?.generation)}function SM(e,t){let n=e?[{kind:"legacy-index-generation",value:e}]:[],r=t?[{kind:"legacy-index-generation",value:t}]:[];return e===void 0||t===void 0?Ny(n,r):bn(e===t?"established":"disproven",[e===t?"identities-equal":"identities-different"],n,r)}function Mr(e,t){let n=e?[{kind:"identity",identity:e}]:[],r=t?[{kind:"identity",identity:t}]:[];return!e||!t?Ny(n,r):Ou(e,t)?bn(e.digest===t.digest?"established":"disproven",[e.digest===t.digest?"identities-equal":"identities-different"],n,r):bn("unknown",["identity-projections-not-comparable"],n,r)}function vM(e,t){if(e.schemaVersion===Xt||t.schemaVersion===Xt)return bn("unknown",["legacy-fact-not-comparable"],[],[]);let n=Ay(e),r=Ay(t),i=Ty(e),o=Ty(t);return i==="invalidated"||o==="invalidated"?bn("disproven",[...i==="invalidated"?["left-observation-invalidated"]:[],...o==="invalidated"?["right-observation-invalidated"]:[]],n,r):i!=="fixed"||o!=="fixed"?bn("unknown",[...i==="no-repository-source"?["left-observation-has-no-repository-source"]:i!=="fixed"?["left-observation-not-fixed"]:[],...o==="no-repository-source"?["right-observation-has-no-repository-source"]:o!=="fixed"?["right-observation-not-fixed"]:[]],n,r):bn("established",["all-observed-sources-fixed"],n,r)}function Ty(e){let t=e.observedSources.filter(r=>r.kind!=="process");if(t.length===0)return"no-repository-source";let n=new Map(e.stabilityProofs.map(r=>[r.source,r.kind]));return t.some(r=>n.get(r.kind)==="invalidated")?"invalidated":t.every(r=>{let i=n.get(r.kind);return i==="immutable"||i==="fixed-snapshot"})?"fixed":"unknown"}function CM(e){if(e.schemaVersion!==er)return e.index?"unknown":"not-applicable";if(!e.observedSources.some(r=>r.kind==="index-generation"))return"not-applicable";let t=e.facts.index?.inputs;if(!t)return"unknown";let n=(e.facts.relevantInputs??[]).find(r=>Ou(r.identity,t))?.identity;return n?n.digest===t.digest?"established":"disproven":"unknown"}function Jt(e,t){return e.schemaVersion===er?t(e):void 0}function ky(e){return e.schemaVersion===Xt&&e.index?[{kind:"legacy-index-generation",value:e.index.generationIdentity}]:e.schemaVersion===er&&e.facts.index?[{kind:"identity",identity:e.facts.index.generation}]:[]}function Ay(e){return e.stabilityProofs.map(t=>({kind:"stability",proof:t}))}function Ny(e,t){let n=e.length===0&&t.length===0?"both-facts-missing":e.length===0?"left-fact-missing":"right-fact-missing";return bn("unknown",[n],e,t)}function bn(e,t,n,r){return{state:e,reasons:t,facts:{left:n,right:r}}}function Ou(e,t){return e.schemaVersion===t.schemaVersion&&e.canonicalizationVersion===t.canonicalizationVersion&&e.hashAlgorithm===t.hashAlgorithm&&e.projection.name===t.projection.name&&e.projection.version===t.projection.version}function xM(e){if(!Q(e))return!1;let t=e.index,n=e.worktree;return Oy(e.observedAt)&&Nt(e.projectIdentity)&&MM(e.authorityKind)&&(t===void 0||Q(t)&&Nt(t.generationIdentity)&&(t.source==="immutable"||t.source==="legacy")&&(t.alignment==="not-certified"||t.alignment==="leased"))&&(n===void 0||Q(n)&&Nt(n.identity)&&typeof n.clean=="boolean"&&(n.headCommit===void 0||Nt(n.headCommit))&&(n.treeOid===void 0||Nt(n.treeOid)))&&DM(e.authorityKind,t,n)}function RM(e){if(!Q(e))return!1;let t=e.facts,n=e.observedSources,r=e.stabilityProofs;if(!Oy(e.observedAt)||!Q(t)||!Array.isArray(n)||n.length===0||!n.every(IM)||!Fu(n,c=>c.kind)||!Array.isArray(r)||!r.every(wM)||!Fu(r,c=>c.source)||r.some(c=>!n.some(l=>l.kind===c.source))||!r.every(c=>PM(c,t))||["collaborationDomain","repositoryLineage","workspaceInstance","wholeContent"].some(c=>t[c]!==void 0&&!Zn(t[c])))return!1;let o=t.relevantInputs;if(o!==void 0&&(!Array.isArray(o)||!o.every(EM)||!Fu(o,c=>`${c.subject}\0${c.identity.projection.name}`)))return!1;let s=t.index;if(s!==void 0&&(!Q(s)||!Zn(s.generation)||s.inputs!==void 0&&!Zn(s.inputs)||s.source!=="immutable"&&s.source!=="legacy"))return!1;let a=e.diagnostics;return(a===void 0||Q(a)&&(a.clean===void 0||typeof a.clean=="boolean")&&(a.headCommit===void 0||Nt(a.headCommit))&&(a.treeOid===void 0||Nt(a.treeOid)))&&LM(t,n)}function Zn(e){return!Q(e)||!Q(e.projection)?!1:e.schemaVersion===Fy&&e.canonicalizationVersion===_u&&e.hashAlgorithm===Nu&&Nt(e.projection.name)&&Ms(e.projection.version)&&Zr(e.digest)}function EM(e){return Q(e)&&Nt(e.subject)&&Zn(e.identity)}function IM(e){return Q(e)&&_y(e.kind)&&(e.identity===void 0||Zn(e.identity))}function wM(e){return Q(e)&&_y(e.source)&&(e.kind==="immutable"||e.kind==="fixed-snapshot"||e.kind==="bracketed"||e.kind==="not-established"||e.kind==="invalidated")}function LM(e,t){let n=e.index,r=t.find(c=>c.kind==="index-generation");if(r){if(!Q(n)||!Zn(n.generation)||r.identity&&!Au(r.identity,n.generation))return!1}else if(n!==void 0)return!1;let i=e.workspaceInstance,o=t.find(c=>c.kind==="live-workspace");if(o?.identity&&(!Zn(i)||!Au(o.identity,i)))return!1;let s=e.wholeContent,a=t.find(c=>c.kind==="repository-snapshot");return!(a?.identity&&(!Zn(s)||!Au(a.identity,s)))}function PM(e,t){return e.kind==="not-established"||e.kind==="invalidated"?!0:e.source==="index-generation"?e.kind==="immutable"&&Q(t.index)&&t.index.source==="immutable":e.source==="repository-snapshot"?e.kind==="fixed-snapshot":e.source==="live-workspace"?e.kind==="bracketed":!1}function Au(e,t){return Ou(e,t)&&e.digest===t.digest}function DM(e,t,n){return e==="index-worktree"?t!==void 0&&n!==void 0:e==="index-only"?t!==void 0&&n===void 0:e==="worktree-only"?t===void 0&&n!==void 0:e==="process-local"&&t===void 0&&n===void 0}function MM(e){return e==="index-worktree"||e==="index-only"||e==="worktree-only"||e==="process-local"}function _y(e){return e==="index-generation"||e==="repository-snapshot"||e==="live-workspace"||e==="process"}function Oy(e){return typeof e=="string"&&!Number.isNaN(Date.parse(e))}function Fu(e,t){return new Set(e.map(t)).size===e.length}function Pa(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.kind==="automated-adjudication"&&t.policyVersion===1&&(t.decidedBy==="agent"||t.decidedBy==="human")&&Jp.includes(t.reasonCode)&&Array.isArray(t.evidence)&&t.evidence.length>0&&t.evidence.every(TM)&&(t.observation===void 0||La(t.observation))&&!!t.invalidateOn&&typeof t.invalidateOn=="object"&&typeof t.invalidateOn.targetContentChange=="boolean"&&typeof t.invalidateOn.detectorMajorChange=="boolean"}function TM(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return(t.kind==="source"||t.kind==="config"||t.kind==="test"||t.kind==="graph")&&typeof t.referent=="string"&&t.referent.trim()!==""&&typeof t.claim=="string"&&t.claim.trim()!==""&&(t.contentHash===void 0||/^[a-f0-9]{64}$/u.test(t.contentHash))&&(t.generation===void 0||typeof t.generation=="string"&&t.generation.length>0)}var Da=class extends Error{constructor(n,r,i){super(`${n} is ${r} characters; the safety limit is ${i} characters`);this.inputKind=n;this.observedCharacters=r;this.limitCharacters=i;this.name="RegExpPatternBudgetError"}inputKind;observedCharacters;limitCharacters;code="SCIP_QUERY_REGEXP_PATTERN_BUDGET"};function kr(e,t,n,r=4096){if(!Number.isSafeInteger(r)||r<0)throw new RangeError(`maxCharacters must be a non-negative safe integer; received ${r}`);if(e.length>r)throw new Da(t,e.length,r);return new RegExp(e,n)}import{createHash as By}from"crypto";import{closeSync as kM,fstatSync as $y,openSync as AM,rmSync as FM}from"fs";import{dirname as NM}from"path";var _M=2e3,OM=10,BM=3,Ta=class extends Error{constructor(n,r,i){super(`Concurrent edit detected for ${n}; expected revision ${Hy(r)}, but found ${Hy(i)}. The latest file was left untouched.`);this.path=n;this.original=r;this.latest=i;this.name="FileRevisionConflictError"}path;original;latest},Do=class extends Error{constructor(n,r){super(`Concurrent edit detected for ${n}: ${r} changed since it was read. The latest file was left untouched; reload it and retry.`);this.path=n;this.field=r;this.name="FileContentConflictError"}path;field};function Mo(e,t,n={}){let r=$M(e,n.lockTimeoutMs??_M,n.monotonicNow??Lt);try{let i=Math.max(0,Math.floor(n.maxRetries??BM));for(let o=0;;o+=1){let s=Ma(e),a=t(s,o);if(a.kind==="unchanged")return{changed:!1,attempts:o+1,previous:s,current:s};n.onBeforeCommit?.({attempt:o,snapshot:s,mutation:a});let c=Ma(e);if(!HM(s.revision,c.revision)){if(o<i)continue;throw new Ta(e,s.revision,c.revision)}try{jM(e,a,s.revision)}catch(l){if(l.code==="EEXIST"){let u=Ma(e);if(o<i)continue;throw new Ta(e,s.revision,u.revision)}throw l}return{changed:!0,attempts:o+1,previous:s,current:Ma(e)}}}finally{r.release()}}function Ma(e){for(let t=0;t<4;t+=1){let n;try{n=AM(e,"r");let r=jy($y(n)),i=Op(n,{maxBytes:dn,inputKind:"revisioned text file"}),o=jy($y(n));if(!Uy(r,o))continue;return{path:e,text:i,revision:{exists:!0,hash:By("sha256").update(i).digest("hex"),identity:o}}}catch(r){if(r.code==="ENOENT")return{path:e,text:"",revision:{exists:!1,hash:By("sha256").update("").digest("hex")}};throw r}finally{n!==void 0&&kM(n)}}throw new Error(`Could not read a stable revision of ${e}; the file is changing continuously.`)}function $M(e,t,n){let r=`${e}.scip-query-write.lock`,i=n()+Math.max(0,t);for(;;){let o=ui(r,{kind:"revisioned-file-mutation",detail:{target:e}});if(o.kind==="acquired")return o.lock;if(n()>=i)throw new Error(`Timed out after ${t}ms waiting to update ${e}; the file was left untouched.`);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,OM)}}function jM(e,t,n){if(t.kind==="delete"){if(!n.exists)return;FM(e),qp(NM(e));return}let r=t.mode??n.identity?.mode;n.exists?Af(e,t.text,{durability:"durable",mode:r}):Ff(e,t.text,{durability:"durable",mode:r})}function HM(e,t){return e.exists===t.exists&&e.hash===t.hash&&(e.identity===void 0?t.identity===void 0:t.identity!==void 0&&Uy(e.identity,t.identity))}function jy(e){return{dev:e.dev,ino:e.ino,size:e.size,mtimeMs:e.mtimeMs,mode:e.mode&511}}function Uy(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.mode===t.mode}function Hy(e){return e.exists?e.hash.slice(0,12):"<absent>"}var tr=".scipquery.json",Wy=2e3,ka=5e3,Bu=ka,Vy=15*6e4,$u={enabled:!0,windowMs:15*6e4,maxRebuilds:2,maxEstimatedWriteBytes:1024*1024*1024},zM={enabled:!1,autoStart:!1,allowExpensiveRebuild:!1,debounceMs:Wy,cooldownMs:Bu,gitPollMs:2e3,idleTimeoutMs:Vy,autoRefresh:!0,ignore:[],resourceBudget:$u};var KM=new Set(["$schema","schemaVersion","collaborationDomainId","languages","indexerConcurrency","watch","indexer","dbPath","entryRoots","semantic","suppressions","declaredCouplings","locality","architecture","coverageContracts","docs"]),WM=new Set(["enabled","autoStart","allowExpensiveRebuild","debounceMs","cooldownMs","gitPollMs","idleTimeoutMs","autoRefresh","ignore","resourceBudget"]),VM=new Set(["enabled","windowMs","maxRebuilds","maxEstimatedWriteBytes"]),YM=new Set(["pathPrefixes","files","symbolPatterns","qualifiedVars"]),JM=new Set(["typescript","rust"]),XM=new Set(["tsconfigs"]),QM=new Set(["rustAnalyzerPath"]),qy=new Set(hl),ZM=new Set(["pnpmWorkspaces","projectMode","projects","configPath","maxWarmSessions","workerIdleMs","workerSoftMemoryMb","workerHeapMb","maxHeapMb"]),eT=new Set(["architecturalBoundarySegments"]),tT=new Set(["boundaries","allowedDependencies","requireCompletePolicy","requireCompleteCoverage","requireAcyclic","requireResolvedBoundaries","requireMinimalPolicy","maxBoundaryFanOut","maxBoundaryFiles","testPaths"]),nT=new Set(["name","paths","subUnits","maxFiles"]),rT=new Set(["snapshotPaths"]),iT=new Set(["name","files","reason"]),oT=new Set(["id","check","file","reason","expiresAt","createdAt","decision"]),sT=new Set(["kind","reasonCode","decidedBy","policyVersion","observation","evidence","invalidateOn"]),aT=new Set(["kind","referent","claim","contentHash","generation"]),cT=new Set(["targetContentChange","detectorMajorChange"]),lT=new Set(["name","file","keys","mustEqual","allowExtra"]),uT=new Set(["type","identifier","marker"]),dT=new Set(["type","path","pattern"]),mT=new Set(["object-literal-keys","string-array","markdown-list"]),pT=new Set(["top-level-dirs","file-glob","registered-commands","builtin-skills"]);function Yy(e){let t=Sn(e,tr);if(!Ri(t))return{};let n;try{n=vt(t,{maxBytes:Ls,inputKind:"scip-query project config"})}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`unable to read ${tr} at ${t}: ${i}`,{cause:r})}return Xy(ku(n),t,"read").config}function T8(e,t={}){let n=[];return ET(e,n),fT(e,n),gT(e,n),hT(e,n,t),yT(e,n),vT(e,n),bT(e,n,t),ST(e,n,t),RT(e,n,t),xT(e,n),n}function Gy(e,t,n,r,i){if(!r)return;let o=GM(r,n),s=qM(r,o);if(s.startsWith("..")||UM(s)){e.push({level:"error",path:t,message:i.outside});return}Ri(o)||e.push({level:"warning",path:t,message:i.missing})}function fT(e,t){let n=e;n.schemaVersion!==void 0&&n.schemaVersion!==Qn&&t.push({level:"error",path:"schemaVersion",message:`Must be ${Qn}; unversioned and v${Xn} files are migrated while loading.`}),n.$schema!==void 0&&(typeof n.$schema!="string"||n.$schema.trim()==="")&&t.push({level:"error",path:"$schema",message:"Must be a non-empty string."}),e.collaborationDomainId!==void 0&&!/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(e.collaborationDomainId)&&t.push({level:"error",path:"collaborationDomainId",message:"Must be a lowercase or uppercase UUID v4 generated for this collaboration domain."});let r=new Set(hl);for(let[i,o]of(e.languages??[]).entries())r.has(o)||t.push({level:"error",path:`languages[${i}]`,message:`Unsupported language: ${o}`});for(let[i,o]of(e.entryRoots?.symbolPatterns??[]).entries())try{kr(o,`entryRoots.symbolPatterns[${i}]`)}catch(s){t.push({level:"error",path:`entryRoots.symbolPatterns[${i}]`,message:s instanceof Error?s.message:String(s)})}e.indexerConcurrency!==void 0&&(!Number.isInteger(e.indexerConcurrency)||e.indexerConcurrency<=0)&&t.push({level:"error",path:"indexerConcurrency",message:"Must be a positive integer."})}function gT(e,t){e.watch?.debounceMs!==void 0&&e.watch.debounceMs<=0&&t.push({level:"error",path:"watch.debounceMs",message:"Must be greater than 0."}),e.watch?.cooldownMs!==void 0&&(!Number.isInteger(e.watch.cooldownMs)||e.watch.cooldownMs<0)?t.push({level:"error",path:"watch.cooldownMs",message:"Must be a non-negative integer."}):e.watch?.cooldownMs!==void 0&&e.watch.cooldownMs<ka&&t.push({level:"warning",path:"watch.cooldownMs",message:`Values below ${ka}ms are raised to the safety floor at runtime.`}),e.watch?.gitPollMs!==void 0&&e.watch.gitPollMs<=0&&t.push({level:"error",path:"watch.gitPollMs",message:"Must be greater than 0."}),e.watch?.idleTimeoutMs!==void 0&&(!Number.isInteger(e.watch.idleTimeoutMs)||e.watch.idleTimeoutMs<0)&&t.push({level:"error",path:"watch.idleTimeoutMs",message:"Must be a non-negative integer; 0 disables idle shutdown."}),e.watch?.autoStart!==void 0&&typeof e.watch.autoStart!="boolean"&&t.push({level:"error",path:"watch.autoStart",message:"Must be a boolean."}),e.watch?.allowExpensiveRebuild!==void 0&&typeof e.watch.allowExpensiveRebuild!="boolean"&&t.push({level:"error",path:"watch.allowExpensiveRebuild",message:"Must be a boolean."}),e.watch?.autoRefresh!==void 0&&typeof e.watch.autoRefresh!="boolean"&&t.push({level:"error",path:"watch.autoRefresh",message:"Must be a boolean."});let n=e.watch?.resourceBudget;n?.enabled!==void 0&&typeof n.enabled!="boolean"&&t.push({level:"error",path:"watch.resourceBudget.enabled",message:"Must be a boolean."});for(let[r,i]of[["windowMs",n?.windowMs],["maxRebuilds",n?.maxRebuilds],["maxEstimatedWriteBytes",n?.maxEstimatedWriteBytes]])i!==void 0&&(!Number.isSafeInteger(i)||i<=0)&&t.push({level:"error",path:`watch.resourceBudget.${r}`,message:"Must be a positive safe integer."})}function hT(e,t,n){let r=e.indexer?.typescript;if(r?.projectMode!==void 0&&r.projectMode!=="single"&&r.projectMode!=="workspace"&&t.push({level:"error",path:"indexer.typescript.projectMode",message:'Must be "single" or "workspace".'}),r?.projects!==void 0)if(!Array.isArray(r.projects))t.push({level:"error",path:"indexer.typescript.projects",message:"Must be an array."});else for(let[s,a]of r.projects.entries()){let c=`indexer.typescript.projects[${s}]`;typeof a!="string"||a.trim()===""?t.push({level:"error",path:c,message:"Project path must be a non-empty string."}):Gy(t,c,a,n.projectRoot,{outside:"Project path must stay inside the project root.",missing:`TypeScript project path does not exist: ${a}`})}r?.projectMode==="workspace"&&r.pnpmWorkspaces===!0&&t.push({level:"warning",path:"indexer.typescript.pnpmWorkspaces",message:'Ignored when projectMode is "workspace"; explicit TypeScript projects are indexed directly.'});for(let[s,a]of[["maxWarmSessions",r?.maxWarmSessions],["workerSoftMemoryMb",r?.workerSoftMemoryMb],["workerHeapMb",r?.workerHeapMb],["maxHeapMb",r?.maxHeapMb]])a!==void 0&&(!Number.isInteger(a)||a<=0)&&t.push({level:"error",path:`indexer.typescript.${s}`,message:"Must be a positive integer."});r?.workerIdleMs!==void 0&&(!Number.isInteger(r.workerIdleMs)||r.workerIdleMs<0)&&t.push({level:"error",path:"indexer.typescript.workerIdleMs",message:"Must be a non-negative integer."});let i=e.semantic?.rust;i?.rustAnalyzerPath!==void 0&&(typeof i.rustAnalyzerPath!="string"||i.rustAnalyzerPath.trim()==="")&&t.push({level:"error",path:"semantic.rust.rustAnalyzerPath",message:"Rust analyzer path must be a non-empty string."});let o=e.indexer?.clojure;if(o?.configPath!==void 0){let s="indexer.clojure.configPath";typeof o.configPath!="string"||o.configPath.trim()===""?t.push({level:"error",path:s,message:"Config path must be a non-empty string."}):Gy(t,s,o.configPath,n.projectRoot,{outside:"Config path must stay inside the project root.",missing:`Clojure indexer config path does not exist: ${o.configPath}`})}}function yT(e,t){if(e.locality===void 0)return;if(!Q(e.locality)){t.push({level:"error",path:"locality",message:"Must be an object."});return}let n=e.locality.architecturalBoundarySegments;if(n!==void 0){if(!Array.isArray(n)){t.push({level:"error",path:"locality.architecturalBoundarySegments",message:"Must be an array."});return}for(let[r,i]of n.entries()){let o=`locality.architecturalBoundarySegments[${r}]`;typeof i!="string"||i.trim()===""?t.push({level:"error",path:o,message:"Boundary segment must be a non-empty string."}):(i.includes("/")||i.includes("\\"))&&t.push({level:"error",path:o,message:"Boundary segment must be a single folder name, not a path."})}}}function bT(e,t,n){if(e.declaredCouplings!==void 0&&!Array.isArray(e.declaredCouplings)){t.push({level:"error",path:"declaredCouplings",message:"Must be an array."});return}for(let[r,i]of(e.declaredCouplings??[]).entries()){let o=`declaredCouplings[${r}]`;if((!i.name||i.name.trim()==="")&&t.push({level:"error",path:`${o}.name`,message:"Declared coupling name is required."}),!Array.isArray(i.files)||i.files.length<2)t.push({level:"error",path:`${o}.files`,message:"Declared coupling needs at least two files."});else for(let[s,a]of i.files.entries())!a||a.trim()===""?t.push({level:"error",path:`${o}.files[${s}]`,message:"Declared coupling file path is required."}):n.projectRoot&&!Ri(Sn(n.projectRoot,a))&&t.push({level:"warning",path:`${o}.files[${s}]`,message:`Declared coupling file does not exist: ${a}`});i.reason!==void 0&&i.reason.trim()===""&&t.push({level:"error",path:`${o}.reason`,message:"Declared coupling reason cannot be blank."})}}function ST(e,t,n){let r=n.now??new Date;e.suppressions!==void 0&&!Array.isArray(e.suppressions)&&t.push({level:"error",path:"suppressions",message:"Must be an array."});for(let[i,o]of(Array.isArray(e.suppressions)?e.suppressions:[]).entries()){let s=`suppressions[${i}]`;if(!Q(o)){t.push({level:"error",path:s,message:"Suppression must be an object."});continue}if((!o.reason||o.reason.trim()==="")&&t.push({level:"error",path:`${s}.reason`,message:"Suppression reason is required."}),o.id!==void 0&&o.id.trim()===""&&t.push({level:"error",path:`${s}.id`,message:"Suppression id cannot be blank."}),o.check!==void 0&&o.check.trim()===""&&t.push({level:"error",path:`${s}.check`,message:"Suppression check cannot be blank."}),!o.id&&(!o.check||!o.file)?t.push({level:"error",path:s,message:"Suppression must include id or both check and file."}):!o.id&&o.check&&o.file&&t.push({level:"warning",path:s,message:"Check+file suppressions waive every matching finding in that file; prefer a stable id when available."}),o.file!==void 0&&(o.file.trim()===""?t.push({level:"error",path:`${s}.file`,message:"Suppression file path cannot be blank."}):n.projectRoot&&!Ri(Sn(n.projectRoot,o.file))&&t.push({level:"warning",path:`${s}.file`,message:`Suppression file does not exist: ${o.file}`})),o.expiresAt){let a=Date.parse(o.expiresAt);Number.isNaN(a)?t.push({level:"error",path:`${s}.expiresAt`,message:"Must be an ISO date string."}):a<=r.getTime()&&t.push({level:"warning",path:`${s}.expiresAt`,message:"Suppression has expired."})}if(o.decision!==void 0&&!Pa(o.decision))t.push({level:"error",path:`${s}.decision`,message:"Must be a valid automated-adjudication decision with reason code, evidence, and invalidation rules."});else if(o.decision&&n.projectRoot)for(let[a,c]of o.decision.evidence.entries())c.kind!=="graph"&&!Ri(Sn(n.projectRoot,c.referent))&&t.push({level:"error",path:`${s}.decision.evidence[${a}].referent`,message:`Suppression counterevidence does not exist: ${c.referent}`})}}function vT(e,t){if(e.architecture===void 0)return;if(!Q(e.architecture)){t.push({level:"error",path:"architecture",message:"Must be an object."});return}let n=e.architecture.boundaries;if(!Array.isArray(n)||n.length===0){t.push({level:"error",path:"architecture.boundaries",message:"Must be a non-empty array."});return}let r=new Set,i=new Set;for(let[a,c]of n.entries()){let l=`architecture.boundaries[${a}]`;if(!Q(c)){t.push({level:"error",path:l,message:"Architecture boundary must be an object."});continue}let u=c.name;typeof u!="string"||u.trim()===""?t.push({level:"error",path:`${l}.name`,message:"Boundary name is required."}):r.has(u)?t.push({level:"error",path:`${l}.name`,message:`Duplicate boundary name: ${u}`}):r.add(u);let d=c.subUnits;d!==void 0&&d!=="directory"&&d!=="file"&&t.push({level:"error",path:`${l}.subUnits`,message:"Must be 'directory' or 'file'."});let m=c.maxFiles;m!==void 0&&(typeof m!="number"||!Number.isInteger(m)||m<0)&&t.push({level:"error",path:`${l}.maxFiles`,message:"Must be a non-negative integer."});let p=c.paths;if(!Array.isArray(p)||p.length===0){t.push({level:"error",path:`${l}.paths`,message:"Boundary paths must be a non-empty array."});continue}for(let[f,g]of p.entries()){let h=`${l}.paths[${f}]`;if(typeof g!="string"||g.trim()===""){t.push({level:"error",path:h,message:"Boundary path must be a non-empty string."});continue}CT(g)||t.push({level:"error",path:h,message:"Boundary path must be project-relative and may use only one trailing /* or /** glob."}),i.has(g)?t.push({level:"error",path:h,message:`Duplicate boundary path: ${g}`}):i.add(g)}}let o=e.architecture.allowedDependencies;if(o!==void 0&&!Q(o))t.push({level:"error",path:"architecture.allowedDependencies",message:"Must be an object keyed by boundary name."});else if(Q(o))for(let[a,c]of Object.entries(o)){let l=`architecture.allowedDependencies.${a}`;if(r.has(a)||t.push({level:"error",path:l,message:`Unknown source boundary: ${a}`}),!Array.isArray(c)){t.push({level:"error",path:l,message:"Dependency row must be an array."});continue}let u=new Set;for(let[d,m]of c.entries()){let p=`${l}[${d}]`;typeof m!="string"||m.trim()===""?t.push({level:"error",path:p,message:"Target boundary name is required."}):r.has(m)?u.has(m)?t.push({level:"error",path:p,message:`Duplicate target boundary: ${m}`}):u.add(m):t.push({level:"error",path:p,message:`Unknown target boundary: ${m}`})}}e.architecture.requireAcyclic!==void 0&&typeof e.architecture.requireAcyclic!="boolean"&&t.push({level:"error",path:"architecture.requireAcyclic",message:"Must be a boolean."});for(let a of["requireCompleteCoverage","requireResolvedBoundaries","requireMinimalPolicy"])e.architecture[a]!==void 0&&typeof e.architecture[a]!="boolean"&&t.push({level:"error",path:`architecture.${a}`,message:"Must be a boolean."});for(let a of["maxBoundaryFanOut","maxBoundaryFiles"]){let c=e.architecture[a];c!==void 0&&(typeof c!="number"||!Number.isInteger(c)||c<0)&&t.push({level:"error",path:`architecture.${a}`,message:"Must be a non-negative integer."})}let s=e.architecture.testPaths;if(s!==void 0&&(!Array.isArray(s)||s.some(a=>typeof a!="string"))&&t.push({level:"error",path:"architecture.testPaths",message:"Must be an array of strings."}),e.architecture.requireCompletePolicy!==void 0&&typeof e.architecture.requireCompletePolicy!="boolean")t.push({level:"error",path:"architecture.requireCompletePolicy",message:"Must be a boolean."});else if(e.architecture.requireCompletePolicy===!0){let a=Q(o)?o:{};for(let c of[...r].sort())Object.hasOwn(a,c)||t.push({level:"error",path:`architecture.allowedDependencies.${c}`,message:"A dependency row is required by architecture.requireCompletePolicy."})}}function CT(e){let t=e.replace(/\\/g,"/");if(t.startsWith("/")||t==="."||t===".."||t.split("/").includes(".."))return!1;let n=t.replace(/\/\*\*?$/,"");return n.length>0&&!/[*?[\]]/.test(n)}function xT(e,t){let n=e.docs?.snapshotPaths;if(n!==void 0){if(!Array.isArray(n)){t.push({level:"error",path:"docs.snapshotPaths",message:"Must be an array."});return}for(let[r,i]of n.entries())(typeof i!="string"||i.trim()==="")&&t.push({level:"error",path:`docs.snapshotPaths[${r}]`,message:"Snapshot path glob must be a non-empty string."})}}function RT(e,t,n){if(e.coverageContracts!==void 0){if(!Array.isArray(e.coverageContracts)){t.push({level:"error",path:"coverageContracts",message:"Must be an array."});return}for(let[r,i]of e.coverageContracts.entries()){let o=`coverageContracts[${r}]`;if(!Q(i)){t.push({level:"error",path:o,message:"Coverage contract must be an object."});continue}(typeof i.name!="string"||i.name.trim()==="")&&t.push({level:"error",path:`${o}.name`,message:"Coverage contract name is required."}),typeof i.file!="string"||i.file.trim()===""?t.push({level:"error",path:`${o}.file`,message:"Coverage contract file is required."}):n.projectRoot&&!Ri(Sn(n.projectRoot,i.file))&&t.push({level:"warning",path:`${o}.file`,message:`Coverage contract file does not exist: ${i.file}`}),zy(t,i.keys,`${o}.keys`,mT,"Unknown coverage-contract key extractor type."),zy(t,i.mustEqual,`${o}.mustEqual`,pT,"Unknown coverage-contract ground-truth source type."),i.allowExtra!==void 0&&typeof i.allowExtra!="boolean"&&t.push({level:"error",path:`${o}.allowExtra`,message:"Must be a boolean."})}}}function zy(e,t,n,r,i){if(!Q(t)){e.push({level:"error",path:n,message:'Must be an object with a "type" field.'});return}if(typeof t.type!="string"||!r.has(t.type)){e.push({level:"error",path:`${n}.type`,message:`${i} Got: ${String(t.type)}`});return}let o={"object-literal-keys":["identifier"],"string-array":["identifier"],"markdown-list":["marker"],"top-level-dirs":["path"],"file-glob":["pattern"],"registered-commands":[],"builtin-skills":[]};for(let s of o[t.type]??[])(typeof t[s]!="string"||t[s].length===0)&&e.push({level:"error",path:`${n}.${s}`,message:`"${t.type}" requires a non-empty string "${s}".`})}function k8(e){return{...zM,...e.watch,cooldownMs:Math.max(ka,e.watch?.cooldownMs??Bu),resourceBudget:{...$u,...e.watch?.resourceBudget}}}function A8(e,t){let n=Sn(e,tr),r=Ky(),i={collaborationDomainId:r,languages:t,watch:{enabled:!0,debounceMs:Wy,cooldownMs:Bu,gitPollMs:2e3,idleTimeoutMs:Vy,autoRefresh:!0,resourceBudget:{...$u}}},o=Mo(n,s=>{if(!s.revision.exists)return{kind:"write",text:xi(i)};let a=Fa(s,i);return a.config.collaborationDomainId?{kind:"unchanged"}:{kind:"write",text:xi({...a.config,collaborationDomainId:r})}});return{configPath:n,changed:o.changed}}function F8(e,t,n=Ky()){let r=Sn(e,tr),i=t,o=Mo(r,s=>{let a=Fa(s,t);if(a.config.collaborationDomainId)return i=a.config,{kind:"unchanged"};let c={...a.config,collaborationDomainId:n};return i=c,{kind:"write",text:xi(c)}});return{configPath:r,config:i,changed:o.changed}}function N8(e,t,n){let r=Sn(e,tr),i=[...n],o=t,s=Mo(r,a=>{let c=Fa(a,t);if(Jy(t.languages,c.config.languages,i))throw new Do(r,"languages");let l={...c.config,languages:i};return o=l,a.revision.exists&&!c.needsMigration&&Aa(l,c.config)?{kind:"unchanged"}:{kind:"write",text:xi(l)}});return{configPath:r,config:o,changed:s.changed}}function _8(e,t,n){let r=Sn(e,tr),i=t,o=Mo(r,s=>{let a=Fa(s,t);if(Jy(t.watch?.enabled,a.config.watch?.enabled,n))throw new Do(r,"watch.enabled");let c={...a.config,watch:{...a.config.watch,enabled:n,...n&&a.config.watch?.autoRefresh===void 0?{autoRefresh:!0}:{}}};return i=c,s.revision.exists&&!a.needsMigration&&Aa(c,a.config)?{kind:"unchanged"}:{kind:"write",text:xi(c)}});return{configPath:r,config:i,changed:o.changed}}function Fa(e,t){if(!e.revision.exists)return{config:wa(t),needsMigration:!0};let n=Xy(ku(e.text),e.path,"update");return{config:n.config,needsMigration:n.needsMigration}}function Aa(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Jy(e,t,n){return!Aa(e,t)&&!Aa(t,n)}function Xy(e,t,n){if(e.kind==="legacy"||e.kind==="supported")return e;if(e.kind==="malformed"){let i=n==="read"?`invalid ${tr} at ${t}: ${e.reason}`:`Cannot update ${t}: the latest project config is ${e.reason}.`;throw new Error(`${i} The file was left untouched.`)}let r=n==="read"?`invalid ${tr} at ${t}`:`Cannot update ${t}: the latest project config is invalid`;throw new Error(`${r} (unsupported ${e.direction} schemaVersion ${e.schemaVersion}; this scip-query reads legacy v${Xn} and current v${Qn}). Upgrade scip-query before retrying; the file was left untouched.`)}function ET(e,t){if(!Q(e))return;let n=e;if(Re(t,n,"",KM),Re(t,n.watch,"watch",WM),Re(t,n.watch?.resourceBudget,"watch.resourceBudget",VM),Re(t,n.entryRoots,"entryRoots",YM),Re(t,n.semantic,"semantic",JM),Re(t,n.semantic?.typescript,"semantic.typescript",XM),Re(t,n.semantic?.rust,"semantic.rust",QM),Re(t,n.locality,"locality",eT),Re(t,n.architecture,"architecture",tT),Re(t,n.docs,"docs",rT),Array.isArray(n.architecture?.boundaries))for(let[r,i]of n.architecture.boundaries.entries())Re(t,i,`architecture.boundaries[${r}]`,nT);if(Q(n.indexer)){Re(t,n.indexer,"indexer",qy);for(let[r,i]of Object.entries(n.indexer))qy.has(r)&&Re(t,i,`indexer.${r}`,ZM)}if(Array.isArray(n.declaredCouplings))for(let[r,i]of n.declaredCouplings.entries())Re(t,i,`declaredCouplings[${r}]`,iT);if(Array.isArray(n.suppressions)){for(let[r,i]of n.suppressions.entries())if(Re(t,i,`suppressions[${r}]`,oT),Q(i.decision)){if(Re(t,i.decision,`suppressions[${r}].decision`,sT),Array.isArray(i.decision.evidence))for(let[o,s]of i.decision.evidence.entries())Re(t,s,`suppressions[${r}].decision.evidence[${o}]`,aT);Re(t,i.decision.invalidateOn,`suppressions[${r}].decision.invalidateOn`,cT)}}if(Array.isArray(n.coverageContracts))for(let[r,i]of n.coverageContracts.entries()){let o=`coverageContracts[${r}]`;Re(t,i,o,lT),Q(i)&&(Re(t,i.keys,`${o}.keys`,uT),Re(t,i.mustEqual,`${o}.mustEqual`,dT))}}function Re(e,t,n,r){if(Q(t))for(let i of Object.keys(t))r.has(i)||e.push({level:"warning",path:n?`${n}.${i}`:i,message:"Unknown config key."})}import{existsSync as Na,lstatSync as IT}from"fs";import{resolve as wT}from"path";function X8(e){return e.state==="fresh"?!0:e.state!=="stale"?!1:!e.reason.startsWith("SQLite generation requires repair")}function Qy(e,t,n,r={}){let i=new Date().toISOString();if(!Na(n.dbPath))return{state:"missing",checkedAt:i,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Na(n.metaPath))return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let o=yr(Ve(n.metaPath,"reindex metadata"));if(o.kind==="unsupported")return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Reindex metadata version ${o.version} is unsupported by this scip-query build.`,remedy:"Upgrade scip-query or run: scip-query reindex"};if(o.kind==="malformed")return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Could not decode reindex metadata: ${o.reason}`,remedy:"Run: scip-query reindex"};let s=o.metadata,a=t.languages??Kf(e),c=s.fingerprint,l=n.cacheDir&&r.gitContext&&Ll(r.gitContext,n.cacheDir,c)?c:void 0,u=n.cacheDir&&r.gitContext&&l&&PT(l,a,t)&&DT(e,l,t)?r.gitObservation?.context===r.gitContext?r.gitContext:$p(r.gitContext):void 0,d=r.gitObservation&&r.gitObservation.context===r.gitContext?r.gitObservation.projectFileInventorySequence:void 0,m=u?.clean&&jp(e,void 0,{cachedInventoryAfterSequence:d})?u:void 0,p=n.cacheDir&&m&&l&&Ll(m,n.cacheDir,l)?l:LT(e,a,t),f=[...s.indexedLanguages??[]].sort(),g=o.capabilities.publishableGeneration&&Np(Wi(s.fingerprint),p)&&JSON.stringify(f)===JSON.stringify(p.languages),h=wl(n.dbPath,n.metaPath),b=h.state==="invalid"||h.state==="drifted",S=g?Wf(n.dbPath,p,f):void 0,y=S?.state==="incomplete",x=g&&!b&&!y;return{state:x?"fresh":"stale",checkedAt:i,metaPath:n.metaPath,updatedAt:s.updatedAt,lastRefresh:s.lastRefresh,reason:b?`SQLite generation requires repair: ${h.reason}`:y?`SQLite generation is missing ${S.missingDocumentCount} indexed source document(s): ${S.missingPaths.join(", ")}`:g?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:x?void 0:"Run: scip-query reindex"}}catch(o){return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Could not read reindex metadata: ${o instanceof Error?o.message:String(o)}`,remedy:"Run: scip-query reindex"}}}function Q8(e){let t=new Date().toISOString();if(!Na(e.dbPath))return{state:"missing",checkedAt:t,metaPath:e.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!Na(e.metaPath))return{state:"unknown",checkedAt:t,metaPath:e.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let n=yr(Ve(e.metaPath,"reindex metadata"));if(n.kind==="unsupported")return{state:"unknown",checkedAt:t,metaPath:e.metaPath,reason:`Reindex metadata version ${n.version} is unsupported by this scip-query build.`,remedy:"Upgrade scip-query or run: scip-query reindex"};if(n.kind==="malformed")return{state:"unknown",checkedAt:t,metaPath:e.metaPath,reason:`Could not decode reindex metadata: ${n.reason}`,remedy:"Run: scip-query reindex"};let r=n.metadata,i=[...r.indexedLanguages??[]].sort(),o=Wi(r.fingerprint),s=[...o?.languages??[]].sort(),a=n.capabilities.publishableGeneration&&o!==null&&JSON.stringify(i)===JSON.stringify(s),c=wl(e.dbPath,e.metaPath),l=c.state==="invalid"||c.state==="drifted",u=a&&!l;return{state:u?"fresh":"stale",checkedAt:t,metaPath:e.metaPath,updatedAt:r.updatedAt,lastRefresh:r.lastRefresh,reason:l?`SQLite generation requires repair: ${c.reason}`:a?"Watcher accepted the newly published index generation with no later changes pending.":"Published index metadata is not a complete queryable generation.",remedy:u?void 0:"Run: scip-query reindex"}}catch(n){return{state:"unknown",checkedAt:t,metaPath:e.metaPath,reason:`Could not read reindex metadata: ${n instanceof Error?n.message:String(n)}`,remedy:"Run: scip-query reindex"}}}function LT(e,t,n){return Vp(e,t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath})}function PT(e,t,n){let r=MT(t,n);return e.version===r.version&&JSON.stringify([...e.languages].sort())===JSON.stringify(r.languages)&&e.pnpmWorkspaces===r.pnpmWorkspaces&&e.typescriptProjectMode===r.typescriptProjectMode&&JSON.stringify([...e.typescriptProjects].sort())===JSON.stringify(r.typescriptProjects)&&e.clojureConfigPath===r.clojureConfigPath}function DT(e,t,n){if(!(t.languages.includes("typescript")||!!t.clojureConfigPath))return!0;let i=Ds(e);if(t.clojureConfigPath){let o=un(t.clojureConfigPath);if(!i.includes(o))return!1;try{if(!IT(wT(e,o)).isFile())return!1}catch{return!1}}return!t.languages.includes("typescript")||Up(e,n.indexer?.typescript?.projectMode,n.indexer?.typescript?.projects??[],i)}function MT(e,t){return Yp(e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{existsSync as TT,readdirSync as kT}from"fs";import{createHash as AT}from"crypto";import{join as Uu}from"path";function Hu(e){let t=0,n=0,r=0,i=0,o=0,s=[];for(let l of e)switch(l.state){case"legacy":t+=1;break;case"current":n+=1;break;case"unsupported-older":r+=1,s.push(ju(l));break;case"unsupported-future":i+=1,s.push(ju(l));break;case"malformed":o+=1,s.push(ju(l));break}let a=t+n,c=r+i+o;return{complete:c===0,total:e.length,accepted:a,legacy:t,current:n,unsupportedOlder:r,unsupportedFuture:i,malformed:o,omitted:c,issues:s}}function ju(e){if(e.state==="legacy"||e.state==="current")throw new Error(`accepted record ${e.path} cannot become a compatibility issue`);return{path:e.path,state:e.state,reason:e.reason??e.state}}var tb=Uu(".scipquery","suppressions"),Zy="scip-query-suppression",eb=1,_a=2;function FT(e){return Uu(e,tb)}function NT(e){if(e.id&&e.id.trim()!=="")return`${e.id.trim()}.json`;let t=`${e.check??""}\0${e.file??""}`;return`CHECK-${AT("sha256").update(t).digest("hex").slice(0,12).toUpperCase()}.json`}function _T(e){return NT(e).slice(0,-5)}function OT(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return{state:"malformed",error:"not a suppression object"};let n=e;if(n.schemaVersion===void 0&&(n.kind!==void 0||n.suppressionIdentity!==void 0||n.writer!==void 0))return{state:"malformed",error:"suppression envelope metadata requires schemaVersion"};if(n.schemaVersion!==void 0){if(!Number.isSafeInteger(n.schemaVersion))return{state:"malformed",error:"schemaVersion must be a positive safe integer"};if(n.schemaVersion!==eb&&n.schemaVersion!==_a)return{state:n.schemaVersion>_a?"unsupported-future":"unsupported-older",error:`unsupported schemaVersion ${String(n.schemaVersion)}`};if(n.kind!==void 0&&n.kind!==Zy)return{state:"malformed",error:`kind must be ${Zy}`}}if(n.schemaVersion===eb&&n.decision!==void 0)return{state:"malformed",error:"schemaVersion 1 cannot carry automated adjudication metadata"};if(n.schemaVersion===_a&&!Pa(n.decision))return{state:"malformed",error:"schemaVersion 2 requires a valid automated adjudication decision"};if(typeof n.reason!="string"||n.reason.trim()==="")return{state:"malformed",error:"missing reason"};if(!n.id&&!n.check)return{state:"malformed",error:"needs an id or a check"};let r=BT(n);if(n.schemaVersion===void 0)return{state:"legacy",suppression:r,record:n,schemaVersion:0};let i=_T(r);return n.suppressionIdentity!==i||t!==void 0&&n.suppressionIdentity!==t?{state:"malformed",error:"suppressionIdentity does not match the suppression target or filename"}:!n.writer||n.writer.tool!=="scip-query"||typeof n.writer.version!="string"||n.writer.version.trim()===""?{state:"malformed",error:"missing valid writer metadata"}:typeof n.createdAt!="string"||!Number.isFinite(Date.parse(n.createdAt))?{state:"malformed",error:"missing valid createdAt timestamp"}:n.updatedAt!==void 0&&(typeof n.updatedAt!="string"||!Number.isFinite(Date.parse(n.updatedAt)))?{state:"malformed",error:"invalid updatedAt timestamp"}:{state:n.schemaVersion===_a?"current":"legacy",suppression:r,record:n,schemaVersion:n.schemaVersion}}function nb(e){let t=FT(e);if(!TT(t))return{suppressions:[],compatibility:Hu([]),warnings:[]};let n=[],r=[];for(let o of kT(t).sort()){if(!o.endsWith(".json"))continue;let s=Uu(t,o),a=`${tb}/${o}`,c;try{c=JSON.parse(Ve(s,"suppression record"))}catch{r.push({path:a,state:"malformed",reason:"malformed JSON"});continue}let l=OT(c,o.slice(0,-5));if("error"in l){r.push({path:a,state:l.state,reason:l.error});continue}r.push({path:a,state:l.state}),n.push(l.suppression)}let i=Hu(r);return{suppressions:n,compatibility:i,warnings:i.issues.map(o=>`${o.path}: ${o.reason} \u2014 ignored`)}}function BT(e){return{...typeof e.id=="string"?{id:e.id}:{},...typeof e.check=="string"?{check:e.check}:{},...typeof e.file=="string"?{file:e.file}:{},reason:e.reason,...typeof e.expiresAt=="string"?{expiresAt:e.expiresAt}:{},...typeof e.createdAt=="string"?{createdAt:e.createdAt}:{},...e.decision?{decision:e.decision}:{}}}function Ba(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var qu,Oa;function S9(e){qu=e}function $a(){return Oa}function rb(e=Ba(),t=void 0){if(t===void 0&&qu?.projectRoot===e)return qu;let n=Yy(e),r=Gp(e,n),i=process.env.SCIP_QUERY_INDEX_DB;if(i)return{projectRoot:e,config:n,paths:r,dbPath:i,dbPathSource:"env",gitContext:t};if(Gu(r.dbPath))return{projectRoot:e,config:n,paths:r,dbPath:r.dbPath,dbPathSource:"configured",gitContext:t};let o=jT(e,"index.db");return{projectRoot:e,config:n,paths:r,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:GT(o,r.dbPath),gitContext:t}}function v9(e){return rb(e).dbPath}function C9(e,t,n,r={}){if(Gu(n.dbPath)&&r.gitContext?.clean===!1&&r.watcherGeneration!==void 0&&qf(n.dbPath)===r.watcherGeneration)return Jf(e,t,n,r.gitContext);let i=Qy(e,t,n,{gitContext:r.gitContext,gitObservation:r.gitObservation});return i.state==="fresh"?{kind:"local-fresh",freshness:i}:Yf(e,t,n,r.gitContext)}function x9(e){return!e.startsWith("__")&&!HT.has(e)}function R9(e){return e==="search"||e==="code"}var HT=new Set(["capabilities","check-deps","config-validate","continue","doctor","init","install-skills","reindex","setup","setup-agent","status","suppress","uninstall","watch"]);function UT(){try{return qT(Ba(),{warnOnRootFallback:!0})}catch(e){console.error(`error: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}function qT(e,t={}){let{config:n,paths:r,dbPath:i,dbPathSource:o,rootFallbackWarning:s,gitContext:a}=rb(e);if(!Gu(i))throw new Error("No index.db found. Run: scip-query reindex");t.warnOnRootFallback&&o==="root-fallback"&&s&&console.error(s);let c=nb(e).suppressions,l={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??r.indexPath,projectRoot:e,collaborationDomainId:n.collaborationDomainId,sharedEvidenceDbPath:Vf(e,n,a),entryRoots:n.entryRoots,semantic:n.semantic,suppressions:[...n.suppressions??[],...c],declaredCouplings:n.declaredCouplings,locality:n.locality,architecture:n.architecture,coverageContracts:n.coverageContracts,docs:n.docs},u=zf(e);return new Gf(l,u)}function GT(e,t){let n="unknown time";try{n=$T(e).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${e}, modified ${n}) because the configured index was not found at ${t}. This fallback may be stale; run 'scip-query reindex' to refresh the configured index.`}function zu(e){return Bp(()=>{let t=UT(),n=Oa;Oa=t;try{return e(t)}finally{Oa=n,t.close()}})}function E9(e,t){return t.concat([e])}function Ku(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(0)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function I9(e){switch(e.state){case"idle":return"Watching (idle)";case"waiting":{let t=Math.round((e.reindexAt-Date.now())/1e3);return`${e.changedFiles} file(s) changed, reindexing in ${t}s...`}case"indexing":return`Reindexing... (${Math.round((Date.now()-e.startedAt)/1e3)}s)`;case"cooldown":return`Cooldown (${Math.round((e.until-Date.now())/1e3)}s)${e.dirty?" \u2014 changes pending":""}`;case"budget-paused":return`Automatic reindex paused by resource budget (${Math.max(0,Math.round((e.until-Date.now())/1e3))}s; ${e.reason}; ${e.rebuilt} rebuilds, ${Ku(e.estimatedWriteBytes)} estimated writes)${e.dirty?" \u2014 changes pending":""}`;case"draining":return`Stopping safely \u2014 ${e.reason}`;default:return zT(e)}}function zT(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}var KT=new Map([[8,"\u2408"],[9,"\u2409"],[10,"\u2424"],[13,"\u240D"]]),L9=6500,P9=8e3,D9=6500,M9=3500;function ib(e,t={}){let n=t.allowNewlines??!0,r=t.allowTabs??!0,i="";for(let o=0;o<e.length;){let s=e.charCodeAt(o);if(s===27){o=WT(e,o);continue}if(s===155){o=ob(e,o+1);continue}if(s===144||s===152||s===157||s===158||s===159){o=sb(e,o+1);continue}if(JT(s)){s===10&&n?i+=`
|
|
54
|
-
`:s===9&&r?i+=" ":i+=KT.get(s)??"\uFFFD",o+=1;continue}if(XT(s)){i+="\uFFFD",o+=1;continue}i+=e[o],o+=1}return i}function Mt(e){return ib(e,{allowNewlines:!1,allowTabs:!1})}function Vu(e,t=n=>process.stdout.write(n)){t(`${e}
|
|
55
|
-
`)}function T9(e=console){let t={log:e.log.bind(e),error:e.error.bind(e),warn:e.warn.bind(e)};return e.log=(...n)=>t.log(...n.map(Wu)),e.error=(...n)=>t.error(...n.map(Wu)),e.warn=(...n)=>t.warn(...n.map(Wu)),()=>{e.log=t.log,e.error=t.error,e.warn=t.warn}}function Wu(e){return typeof e=="string"?ib(e):e}function WT(e,t){let n=e.charCodeAt(t+1);if(Number.isNaN(n))return e.length;if(n===91)return ob(e,t+2);if(n===80||n===88||n===93||n===94||n===95)return sb(e,t+2);let r=t+1;for(;r<e.length&&VT(e.charCodeAt(r));)r+=1;return r<e.length&&YT(e.charCodeAt(r))?r+1:t+1}function ob(e,t){let n=t;for(;n<e.length;){let r=e.charCodeAt(n);if(n+=1,r>=64&&r<=126)return n}return e.length}function sb(e,t){let n=t;for(;n<e.length;){let r=e.charCodeAt(n);if(r===7||r===156)return n+1;if(r===27&&e.charCodeAt(n+1)===92)return n+2;n+=1}return e.length}function VT(e){return e>=32&&e<=47}function YT(e){return e>=48&&e<=126}function JT(e){return e<=31||e>=127&&e<=159}function XT(e){return e===1564||e===8206||e===8207||e>=8234&&e<=8238||e>=8294&&e<=8297}function ja(e){return e+1}function QT(e,t){return`${ja(e)}-${ja(t)}`}function Yu(e,t,n){return`${Mt(e)}:${QT(t,n)}`}function F9(e,t=180){let n=Mt(e).replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var Ju={empty(e){console.log(Mt(e))},list(e,t){for(let n of e)console.log(Mt(t(n)))},groupedByFile(e,t,n=r=>r.relativePath){let r="";for(let i of e){let o=n(i);o!==r&&(r&&console.log(""),console.log(Mt(o)),r=o),console.log(Mt(t(i)))}},sectionedReport(e){let t=!0;for(let n of e)if(!(n.skipIfEmpty&&n.rows.length===0)){t||console.log(""),t=!1,n.title!==void 0&&console.log(`\u2550\u2550\u2550 ${Mt(n.title)} \u2550\u2550\u2550`),n.explanation!==void 0&&console.log(Mt(n.explanation));for(let r of n.rows){let i=n.preserveRowNewlines?r.split(`
|
|
56
|
-
`):[r];for(let o of i)console.log(Mt(o))}}},table(e,t,n){console.log(` ${e.map(Mt).join(" ")}`);let r=n??e.map(i=>i.length);console.log(` ${r.map(i=>"\u2500".repeat(i)).join(" ")}`);for(let i of t)console.log(Mt(i))}};import{availableParallelism as l5}from"os";import{fileURLToPath as il}from"url";import{existsSync as Ha,readdirSync as lb}from"fs";import{join as To}from"path";var ZT={files:new Set,pathPrefixes:[]},ek={reasonsByFile:new Map},Xu=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,tk=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,ub=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],nk=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),rk=4,ik=ge("package-surface",{clearGroups:["whole-project"]}),ok=ge("package-operational-surface",{clearGroups:["whole-project"]});function db(e){return ik.get(e,()=>ak(e.config.projectRoot))}function Cn(e,t){let n=db(e);return n.files.has(t)?!0:n.pathPrefixes.some(r=>t.startsWith(r))}function mb(e,t){return db(e).files.has(t)}function sk(e){return ok.get(e,()=>ck(e.config.projectRoot))}function pb(e,t){return sk(e).reasonsByFile.get(t)??[]}function ak(e){let t=new Set,n=[];for(let{manifest:r,packageRoot:i}of fb(e))for(let o of lk(r))bb(e,i,o,t,n);return t.size===0&&n.length===0?ZT:{files:t,pathPrefixes:n}}function ck(e){let t=new Map;for(let{manifest:n,packageRoot:r}of fb(e)){let i=uk(n);for(let s of i)ab(e,r,s,"package binary",t);let o=n.scripts;if(!(!o||typeof o!="object")){for(let[s,a]of Object.entries(o))if(typeof a=="string")for(let c of dk(a))ab(e,r,c,`package script "${s}"`,t)}}return t.size===0?ek:{reasonsByFile:t}}function fb(e){let t=[],n=hb(e,"");return n&&t.push({manifest:n,packageRoot:""}),gb(e,"",t,0),t}function gb(e,t,n,r){if(r>=rk)return;let i=To(e,t);if(Ha(i))for(let o of lb(i,{withFileTypes:!0})){if(!o.isDirectory()||nk.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=hb(e,s);a&&n.push({manifest:a,packageRoot:s}),gb(e,s,n,r+1)}}function hb(e,t){let n;try{n=Ye(e,To(t,"package.json"),{maxBytes:8*1024*1024,inputKind:"package manifest"})}catch(r){if(!Je(r))throw r;return null}try{let r=JSON.parse(n);return r&&typeof r=="object"?r:null}catch{return null}}function lk(e){let t=[];for(let r of["main","module","types","browser"])typeof e[r]=="string"&&t.push(e[r]);let n=e.bin;if(typeof n=="string")t.push(n);else if(n&&typeof n=="object")for(let r of Object.values(n))typeof r=="string"&&t.push(r);return yb(e.exports,t),t}function uk(e){let t=e.bin;return typeof t=="string"?[t]:!t||typeof t!="object"?[]:Object.values(t).filter(n=>typeof n=="string")}function dk(e){let t=[],n=/(?:^|&&|\|\||;)\s*(?:(?:cross-env|env)(?:\s+[A-Za-z_][A-Za-z0-9_]*=\S+)*\s+)?(?:node|bun|tsx|ts-node|vite-node|python3?|deno\s+run)\s+(?:(?:--?[A-Za-z0-9-]+(?:=\S+)?)\s+)*["']?([^"'`\s]+\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs|py))["']?/g;for(let r of e.matchAll(n)){let i=r[1];i&&!i.startsWith("node_modules/")&&!i.startsWith("./node_modules/")&&t.push(i)}return t}function ab(e,t,n,r,i){let o=new Set;bb(e,t,n,o,[]);for(let s of o){let a=i.get(s)??[];a.includes(r)||a.push(r),i.set(s,a)}}function yb(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))yb(n,t)}function bb(e,t,n,r,i){let o=n.replace(/\\/g,"/").replace(/^\.\//,"");if(o===""||o.startsWith(".."))return;let s=o.indexOf("*");if(s>=0){let c=o.slice(0,s);for(let l of cb(c))l!==""&&i.push(vn(t,l));return}let a=o.replace(tk,"");for(let c of cb(a)){c===a&&c===o&&r.add(vn(t,o));for(let l of ub)mk(e,r,t,c+l)}r.add(vn(t,o))}function cb(e){let t=[e];return Xu.test(e)&&(t.push(e.replace(Xu,"src/")),t.push(e.replace(Xu,""))),t}function mk(e,t,n,r){let i=vn(n,r);if(t.add(i),!r.startsWith("src/")||Ha(To(e,i)))return;let o=ub.find(u=>r.endsWith(u));if(!o)return;let s=r.slice(0,-o.length);pk(e,t,n,s,o);let a=s.lastIndexOf("/");if(a<=4)return;let c=s.slice(0,a),l=s.slice(a+1);for(let u of Sb(e,n,c,`${l}${o}`))t.add(u)}function pk(e,t,n,r,i){let o=vn(n,`${r}/index${i}`);Ha(To(e,o))&&t.add(o)}function Sb(e,t,n,r){let i=To(e,t,n);if(!Ha(i))return[];let o=[];for(let s of lb(i,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...Sb(e,t,a,r)):s.isFile()&&s.name===r&&o.push(vn(t,a))}return o}function vn(e,t){return e?`${e}/${t}`:t}import{existsSync as Qu,readdirSync as fk}from"fs";import{dirname as gk,join as Zu}from"path";var hk={rootFiles:new Set,sourcePrefixes:[]},yk=new Set([".git",".scipquery","node_modules","target"]),bk=6,Sk=ge("rust-library-surface",{clearGroups:["whole-project"]});function vb(e,t,n){if(!n.endsWith(".rs")||!xk(vk(e),n))return!1;let r=U(e,n).find(i=>i.symbol===t);return r?Rk(V(e,n)[r.startLine]??""):!1}function vk(e){return Sk.get(e,()=>Ck(e.config.projectRoot))}function Ck(e){let t=new Set,n=new Set;for(let r of Ek(e)){let i=Ye(e,Zu(r,"Cargo.toml"),{maxBytes:8388608,inputKind:"Cargo manifest"}),o=Ik(i),s=vn(r,"src/lib.rs"),a=o?vn(r,o):!wk(i)&&Ct(e,s)?s:null;if(!a)continue;t.add(a);let c=gk(a).replaceAll("\\","/");n.add(c==="."?"":`${c}/`)}return t.size===0?hk:{rootFiles:t,sourcePrefixes:[...n].sort()}}function xk(e,t){return t.endsWith(".rs")?e.rootFiles.has(t)?!0:Lk(t)?!1:e.sourcePrefixes.some(n=>t.startsWith(n)):!1}function Rk(e){return/^\s*pub\s+(?!\()/.test(e)}function Ek(e){if(!Qu(e))return[];let t=[];return Cb(e,"",t,0),t}function Cb(e,t,n,r){let i=Zu(e,t);if(Qu(i)&&(Qu(Zu(i,"Cargo.toml"))&&n.push(t),!(r>=bk)))for(let o of fk(i,{withFileTypes:!0})){if(!o.isDirectory()||yk.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name;Cb(e,s,n,r+1)}}function Ik(e){let t=!1;for(let n of e.split(`
|
|
57
|
-
`)){let r=n.replace(/\s+#.*$/,"").trim(),i=/^\[([^\]]+)\]$/.exec(r);if(i){t=i[1]==="lib";continue}if(!t)continue;let o=/^path\s*=\s*["']([^"']+)["']/.exec(r)?.[1];if(o)return o.replaceAll("\\","/").replace(/^\.\//,"")}return null}function wk(e){let t=!1;for(let n of e.split(`
|
|
58
|
-
`)){let r=n.replace(/\s+#.*$/,"").trim(),i=/^\[([^\]]+)\]$/.exec(r);if(i){t=i[1]==="package";continue}if(t&&/^autolib\s*=\s*false\b/.test(r))return!0}return!1}function Lk(e){return/(?:^|\/)src\/main\.rs$/.test(e)||/(?:^|\/)src\/bin\//.test(e)||/(?:^|\/)(?:examples|tests|benches)\//.test(e)}function Ei(e){return q(e)==="barrel"}function Rb(e){return Pk.get(e,()=>{let n=Z(e,{includeIgnored:!1}).filter(s=>{let a=q(s);return a==="entry"||a==="worker"});if(n.length===0)return new Set;let r=Me(e),i=new Set,o=new Set;for(;n.length>0;){let s=n.shift();if(!i.has(s)){i.add(s),q(s)==="barrel"&&o.add(s);for(let a of r.get(s)??[])i.has(a)||n.push(a)}}return o})}var Pk=ge("live-barrels",{clearGroups:["whole-project"]});function ed(e,t){return Rb(e).has(it(t))}function Eb(e){let t=Rb(e);return Z(e,{includeIgnored:!1}).filter(n=>Ei(n)&&!t.has(n)&&!Dk(e,n))}function Dk(e,t){let n=it(t),r=On(e).forFile(n,{facts:!0}).facts?.callables;return r&&r.length>0?!0:(e.get(`SELECT COUNT(*) AS n
|
|
59
|
-
FROM defn_enclosing_ranges der
|
|
60
|
-
JOIN documents d ON d.id = der.document_id
|
|
61
|
-
WHERE d.relative_path = ?
|
|
62
|
-
AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function Ue(e,t){let n=it(t),r=q(t);return r==="entry"||r==="worker"||td(n)||ed(e,n)}function Ii(e,t,n){let r=it(n),i=[];Cn(e,r)&&i.push("package-surface-file"),kk(e,t,r)&&i.push("transitive-package-surface"),vb(e,t,r)&&i.push("rust-public-library"),zk(t,r)&&i.push("framework-entrypoint");let o=e.config.entryRoots;return o&&(o.files?.some(s=>it(s)===r)&&i.push("configured-file"),o.pathPrefixes?.some(s=>r.startsWith(it(s)))&&i.push("configured-path-prefix"),o.qualifiedVars?.some(s=>Wk(t,s))&&i.push("configured-qualified-var"),o.symbolPatterns?.some(s=>{try{return kr(s,"entryRoots.symbolPatterns entry").test(t)}catch{return!1}})&&i.push("configured-symbol-pattern")),i}function Te(e,t,n){return Ii(e,t,n).length>0}var Mk=ge("package-surface-reachability",{clearGroups:["whole-project"]}),Tk=ge("explicit-package-surface-reachability",{clearGroups:["whole-project"]});function kk(e,t,n){let r=Ak(e).get(n);return r===void 0?!1:r===null||r.has(z(t))}function Ib(e,t,n){let r=Fk(e).get(n);return r===void 0?!1:r===null||r.has(z(t))}function Ak(e){return Mk.get(e,()=>wb(e,t=>Cn(e,t)))}function Fk(e){return Tk.get(e,()=>wb(e,t=>mb(e,t)))}function wb(e,t){let n=new Map,r=[];for(let i of Z(e,{includeIgnored:!1}))t(i)&&(n.set(i,null),r.push(i));for(;r.length>0;){let i=r.shift(),o=n.get(i);if(o!==void 0)for(let s of Qi(e,i)){if(!s.sourcePath||e.isIgnored(s.sourcePath))continue;let a=Nk(o,s);a!==void 0&&_k(n,s.sourcePath,a)&&r.push(s.sourcePath)}}return n}function Nk(e,t){if(e===null)return t.kind==="named"?new Set(t.names):null;if(t.kind==="star")return new Set(e);if(t.kind==="star-as")return t.names.some(r=>e.has(r))?null:void 0;let n=t.names.filter(r=>e.has(r));return n.length>0?new Set(n):void 0}function _k(e,t,n){if(!e.has(t))return e.set(t,n),!0;let r=e.get(t);if(r===void 0)return!1;if(r===null||n===null)return r===null?!1:(e.set(t,null),!0);let i=!1;for(let o of n)r.has(o)||(r.add(o),i=!0);return i}var Lb=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),Ok=new Set(["default","generateMetadata","generateStaticParams"]),Bk=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),$k=new Set(["default","middleware","config"]),jk=new Set(["register","onRequestError"]),Hk=new Set(["onRouterTransitionStart"]),Uk=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),qk=new Set(["load","actions","entries",...Lb]),Gk=new Set(["default"]);function zk(e,t){let n=z(e);return n===""?!1:Pb(t)?Lb.has(n):Db(t)?Ok.has(n):Mb(t)?Bk.has(n):Tb(t)?$k.has(n):kb(t)?jk.has(n):Ab(t)?Hk.has(n):Fb(t)?Uk.has(n):Nb(t)?qk.has(n):Kk(t)?Gk.has(n):!1}function td(e){return Pb(e)||Db(e)||Mb(e)||Tb(e)||kb(e)||Ab(e)||Fb(e)||Nb(e)}function Pb(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Db(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Mb(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Tb(e){return nd(e,"(?:middleware|proxy)\\.(?:ts|js|mts|mjs)")}function kb(e){return nd(e,"instrumentation\\.(?:ts|js|mts|mjs)")}function Ab(e){return nd(e,"instrumentation-client\\.(?:ts|js|mts|mjs)")}function nd(e,t){return new RegExp(`^(?:src/)?${t}$`).test(e)||new RegExp(`(?:^|/)src/${t}$`).test(e)||new RegExp(`(?:^|/)(?:apps|services|packages)/[^/]+/(?:src/)?${t}$`).test(e)}function Fb(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Nb(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function Kk(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function Wk(e,t){let n=t.lastIndexOf("/");if(n<0)return!1;let r=t.slice(0,n),i=t.slice(n+1);return e.includes(xb(r)+"/")&&e.includes(xb(i)+".")}function xb(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function _b(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=Z(e,{includeIgnored:!1}),o=zt(e),s=t??Le(e),a=new Set(s.map(l=>l.symbolId)),c=eA(s);return Vk(e,r,i,o,a,c),Yk(e,r,s,a),Zk(e,r,i,o,a,c),n.semantic!==!1&&n.semanticEvidence&&nA(r,n.semanticEvidence.callerMap(e,tA(s))),r}function Vk(e,t,n,r,i,o){for(let s of n){if(!se(s))continue;let a=Gt(e,s);if(a)for(let c of a){if(o&&!o.has(c.calleeLeaf))continue;let l=_t(s,r.get(c.calleeLeaf)??[]);if(!l||l.length===0)continue;let u=$n(e,s,l,c.memberAccess,c.calleeQualifier);u&&i.has(u.symbolId)&&u.file!==s&&rd(t,u.symbolId,s)}}}function Yk(e,t,n,r){let i=Xk(n);for(let o of Jk(e,r))e.isIgnored(o.relative_path)||Qk(o,i.get(o.symbol_id))||rd(t,o.symbol_id,o.relative_path)}function Jk(e,t){return Hs(e,t?[...t]:void 0)}function Xk(e){let t=new Map;for(let n of e)t.set(n.symbolId,{docId:n.documentId,startLine:n.startLine,endLine:n.endLine});return t}function Qk(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function Zk(e,t,n,r,i,o){for(let s of n){if(se(s)!=="rust")continue;let a=ni(e,s,{includeRustAttributeNames:!0});if(a.length!==0)for(let{name:c}of a){if(o&&!o.has(c))continue;let l=r.get(c);if(l)for(let u of l)i.has(u.symbolId)&&u.file!==s&&rd(t,u.symbolId,s)}}}function rd(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function eA(e){let t=new Set;for(let n of e){let r="leaf"in n&&typeof n.leaf=="string"?n.leaf:"symbol"in n&&typeof n.symbol=="string"?z(n.symbol):"";r&&t.add(r)}return t.size>0?t:null}function tA(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function nA(e,t){for(let[n,r]of t){let i=e.get(n);i||(i=new Set,e.set(n,i));for(let o of r)i.add(o)}}function id(e,t,n={}){return _b(e,t,n)}function ko(e,t,n={}){return Pf(e,t,n)}function Ob(e,t,n={}){let r=id(e,t,{semantic:n.semantic,semanticEvidence:n.semanticEvidence});return n.sourceFallback===!1?r:xn(r,ko(e,t))}function xn(e,t){let n=new Map;for(let[r,i]of e)n.set(r,new Set(i));for(let[r,i]of t){let o=n.get(r)??new Set;for(let s of i)o.add(s);n.set(r,o)}return n}function Bb(e,t,n){let r=t.identifierResolution==="strict"?Cl:Lf,i=t.candidateNames?Ef(t.candidateNames):null,o=0,s=0,a=0,c=0,l="";for(let u of t.paths)if(o+=1,l=u,!(!se(u)&&!(t.includeVueSfc&&lf(u)))&&!e.isIgnored(u)&&!t.skipPath?.(u))try{if(i&&!If(W(e,u),i))continue;s+=1;let m=(f,g,h,b)=>{if(t.candidateNames&&!t.candidateNames.has(f))return;a+=1;let S=t.resolveTargets?t.resolveTargets({sourceFile:u,name:f,kind:g,defaultTargets:b}):b();for(let y of S)c+=1,n({sourceFile:u,name:f,target:y,occurrences:h,kind:g})},p=ai(e,u);for(let[f,g]of p)m(f,"identifier",g.length,()=>r(e,u,f));for(let f of ni(e,u,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let g=f.kind==="cross-language-dispatch"?()=>Cl(e,u,f.name):()=>r(e,u,f.name);m(f.name,f.kind,f.occurrences,g)}}finally{t.afterPath?.(u),o%10===0&&N("source-reference-scan.progress",()=>{},()=>({scannedPaths:o,currentPath:l,candidateMatchedPaths:s,visitedNames:a,visitedHits:c}))}}function ee(e){return e.endLine-e.startLine+1}function $b(e,t={}){let{scope:n,files:r,minLoc:i=1,maxLoc:o=Number.POSITIVE_INFINITY,excludeSymbol:s,excludeEntrySurfaces:a=!1,excludeTypesFiles:c=!1,excludeRootedSymbols:l=!1,requireFunctionLikeSymbol:u=!1,requireCallableSymbol:d=!1,excludeRustTraitImplMembers:m=!1,includeSuppressed:p=!1,sortByLocDesc:f=!1}=t,g=[],h=rA(e,{scope:n,files:r,requireFunctionLikeSymbol:u,requireCallableSymbol:d}),b=new Map,S=new Map,y=v=>{let C=b.get(v);if(C!==void 0)return C;let R=Ue(e,v);return b.set(v,R),R},x=v=>{let C=S.get(v);if(C!==void 0)return C;let R=q(v);return S.set(v,R),R};for(let v of h){let C=v.relativePath;if(e.isIgnored(C)||a&&y(C)||!iA(v,{requireFunctionLikeSymbol:u,requireCallableSymbol:d})||s!==void 0&&v.symbol===s)continue;let R=ee(v);R<i||R>o||c&&oA(C)||l&&Te(e,v.symbol,C)||m&&je(v.symbol)||x(C)!=="test"&&(ii(v.symbol)||!p&&As(e,C,v.startLine)||g.push(v))}return f?g.sort((v,C)=>ee(C)-ee(v)):g}function rA(e,t){return t.files!==void 0?[...new Set(t.files.map(r=>r.replace(/\\/g,"/")))].sort().filter(r=>!t.scope||r.includes(t.scope)).flatMap(r=>U(e,r)):t.requireCallableSymbol?Zi(e,{scope:t.scope,symbolMatches:Xe,sqlPrefilter:"callable"}):t.requireFunctionLikeSymbol?Zi(e,{scope:t.scope,symbolMatches:Se,sqlPrefilter:"function-like"}):bf(e,t.scope)}function iA(e,t){return t.requireCallableSymbol?Xe(e.symbol):t.requireFunctionLikeSymbol?Se(e.symbol):e.isFunctionLike}function oA(e){return(e.split("/").pop()??"").includes("types")}var H=class{constructor(t){this.db=t}db;scopedDefinitions(t){return yf(this.db,t)}definitionsForFile(t){return U(this.db,t)}productionCallableDefinitions(t={}){return $b(this.db,t)}calleeMap(t,n={}){return Er(this.db,t,{...n,semanticEvidence:re})}crossFileCallerMap(t,n={}){return id(this.db,t,{...n,semanticEvidence:re})}sourceFallbackCallerFiles(t,n={}){return ko(this.db,t,n)}callerFileMap(t,n={}){return Ob(this.db,t,{...n,semanticEvidence:re})}frameworkReferencedSymbolIds(t){let n=new Map;for(let i of t){if(!i.leaf)continue;let o=n.get(i.leaf)??[];o.push(i.symbolId),n.set(i.leaf,o)}let r=new Set;for(let i of Z(this.db,{includeIgnored:!1}))if(se(i)==="rust")for(let{name:o}of ni(this.db,i,{includeRustAttributeNames:!0}))for(let s of n.get(o)??[])r.add(s);return r}symbolsWithNonSelfCallees(t,n={}){if(t.length===0)return new Set;let r=new Map(t.map(o=>[o.symbolId,o.symbol])),i=this.calleeMap(t,n);return new Set([...i.entries()].filter(([o,s])=>{let a=r.get(o);return s.some(c=>c.symbol!==a)}).map(([o])=>o))}fileDependencyGraph(t){return Me(this.db,t)}fileKind(t){return q(t)}hasSuppressionComment(t){return As(this.db,t.relativePath,t.startLine)}sourceFiles(){return ti(this.db)}scanSourceReferences(t,n){Bb(this.db,t,n)}callableSignature(t){let n=On(this.db).forFile(t.relativePath,{facts:!0}).facts?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};import{statSync as sA}from"fs";function Ar(e){let t=e.get("SELECT COUNT(*) as c FROM documents").c,n=e.get("SELECT COUNT(*) as c FROM global_symbols").c,r=e.get("SELECT COUNT(*) as c FROM mentions WHERE role = 1").c,i=e.get("SELECT COUNT(*) as c FROM mentions WHERE role != 1").c;return{documents:t,symbols:n,definitions:r,references:i,...aA(e.generation.databasePath)}}function aA(e){try{let t=sA(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function cA(e,t){return Ml(e).filter(n=>lA({pattern:t,relativePath:n})).map(n=>({relativePath:n}))}function lA(e,t){let n=typeof e=="string"?{pattern:e,relativePath:t}:e;if(typeof n.pattern!="string"||typeof n.relativePath!="string")throw new TypeError("pathMatchesGlob requires pattern and relativePath.");let r=un(n.pattern),i=un(n.relativePath);if(!/[*?]/.test(r))return i.includes(r);let o=r.includes("/")?r:`**/${r}`;return Ua(o.split("/"),i.split("/"))}function Ua(e,t){if(e.length===0)return t.length===0;let[n,...r]=e;return n==="**"?Ua(r,t)||t.length>0&&Ua(e,t.slice(1)):t.length===0||!uA(n??"",t[0]??"")?!1:Ua(r,t.slice(1))}function uA(e,t){let n="^";for(let r of e)r==="*"?n+="[^/]*":r==="?"?n+="[^/]":n+=dA(r);return n+="$",new RegExp(n).test(t)}function dA(e){return/[\\^$.*+?()[\]{}|]/.test(e)?`\\${e}`:e}function Hb(e,t,n){let r=[],i=[],o=new Map;for(let s of[...e].sort(n)){let a=s.channel??"default",c=t[a]??Number.MAX_SAFE_INTEGER,l=o.get(a)??0;if(l>=c){i.push(s);continue}r.push(s),o.set(a,l+1)}return{selected:r,omitted:i}}function qa(e,t,n,r,i=!1){let o=[...e],s=[],a=new Set,c=0;for(;o.length>0&&s.length<t;){let l=o.filter(m=>c+m.evidenceCharacters<=n||i&&s.length===0);if(l.length===0)break;let u=l.filter(m=>m.roles.includes("location")||m.roles.includes("definition")).sort(r);l.sort((m,p)=>jb(p,a)-jb(m,a)||r(m,p));let d=u[0]??l[0];s.push(d),c+=d.evidenceCharacters;for(let m of Ub(d))a.add(m.key);o.splice(o.indexOf(d),1)}return{selected:s,omitted:o.sort(r)}}function jb(e,t){let n=Ub(e).reduce((o,s)=>o+(t.has(s.key)?0:s.weight),0),r=Math.max(0,8-e.priority)*20,i=Math.min(500,Math.ceil(e.evidenceCharacters/160));return n+r-i}function Ub(e){return[...e.reasons.map(mA),...e.roles.map(t=>({key:`role:${t}`,weight:pA(t)})),{key:`file:${e.relativePath}`,weight:180},{key:`scope:${fA(e.relativePath)}`,weight:120},{key:`kind:${e.fileKind}`,weight:40},...e.symbols.map(t=>({key:`symbol:${t}`,weight:100})),...e.behaviorSignals.map(t=>({key:`behavior:${t}`,weight:70}))]}function mA(e){let t=e.indexOf(":"),n=t<0?e:e.slice(0,t);return n==="dependency"||n==="consumer"?{key:`reason:${n}`,weight:220}:{key:`reason:${e}`,weight:n==="location"||n==="definition"?1400:800}}function pA(e){switch(e){case"location":return 1200;case"definition":return 1100;case"reference":return 600;case"caller":case"callee":return 550;case"dependency":case"consumer":return 500;case"search":return 400;default:return 300}}function fA(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}var qb=64,Gb=12;function Ga(e,t,n={}){if(t.length===0)return[];let r=n.context??6;if(!Number.isSafeInteger(r)||r<0)throw new RangeError(`context must be a non-negative safe integer; received ${r}`);let i=n.limit??12;if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`limit must be a positive safe integer; received ${i}`);let o=t.map(s=>{if(s.length===0)throw new Error("The source search pattern must not be empty.");return{pattern:s,regexp:n.regexp?kr(s,"source search pattern",n.ignoreCase?"iu":"u"):null,literal:n.ignoreCase?s.toLocaleLowerCase():s,identities:[],fileCoverage:[],textByPath:new Map}});if(!n.regexp&&!n.ignoreCase){let s=o.map(c=>Buffer.from(c.pattern,"utf8")),a=Xs(e,{scope:n.scope,literalBytes:s.length===1?s[0]:s},(c,l)=>{let u=Fn(c.text);if(u.length!==0)for(let d of l){let m=o[d];m&&zb(e,m,c,u,n)}});return o.map(c=>Kb(c,a,r,i,n))}return o.map(s=>{let a=Xs(e,{scope:n.scope},c=>{let l=Fn(c.text);l.length>0&&zb(e,s,c,l,n)});return Kb(s,a,r,i,n)})}function zb(e,t,n,r,i){let o=[];for(let l=0;l<r.length;l+=1){let u=r[l]??"",d=u.endsWith("\r")?u.slice(0,-1):u;(t.regexp?t.regexp.test(d):(i.ignoreCase?d.toLocaleLowerCase():d).includes(t.literal))&&o.push(l)}if(o.length===0)return;let s=n.relativePath;t.textByPath.set(s,n.text);let a=n.freshness.semantic.state!=="stale"&&n.freshness.semantic.basis!=="no-compiler-document"?U(e,s):[],c=K(e,s)?.callables??[];for(let l of o){let u=Ne(a,l),d=Nn(c,l),m=u&&!me(u.symbol)?u:null,p=m?.startLine??d?.startLine??u?.startLine??l,f=m?.endLine??d?.endLine??u?.endLine??l,g=po(e,s,l,p,f);t.identities.push({relativePath:s,focusLine:l,ownerSymbol:m?.symbol??null,ownerShort:m?T(m.symbol):d?.name??(u?T(u.symbol):null),ownerStartLine:g.startLine,ownerEndLine:g.endLine,fileKind:q(s),freshness:n.freshness})}t.fileCoverage.push({relativePath:s,matchingLines:o.length,returnedMatches:0,freshness:n.freshness})}function Kb(e,t,n,r,i){e.identities.sort(Vb);let o=e.identities.length>qb?Wb(e.identities,qb):e.identities,a=(r===Number.MAX_SAFE_INTEGER?e.identities:i.ranking?Wb(e.identities,r):e.identities.slice(0,r)).flatMap(u=>{let d=e.textByPath.get(u.relativePath),m=d===void 0?null:gA(u.relativePath,d,u.focusLine,n);return m?[{...m,...u}]:[]}),c=new Map;for(let u of a)c.set(u.relativePath,(c.get(u.relativePath)??0)+1);for(let u of e.fileCoverage)u.returnedMatches=c.get(u.relativePath)??0;let l=hA(e.fileCoverage);return{pattern:e.pattern,mode:i.regexp?"regexp":"literal",identities:e.identities,...o.length<e.identities.length?{identityManifest:o}:{},identityCoverage:{mode:o.length===e.identities.length?"complete":"bounded",returned:o.length,total:e.identities.length,omitted:e.identities.length-o.length},matches:a,matchingLines:e.identities.length,matchingFiles:e.fileCoverage.length,omittedMatches:Math.max(0,e.identities.length-a.length),fileCoverage:e.fileCoverage,scopeHints:l.slice(0,Gb),omittedScopeHints:Math.max(0,l.length-Gb),scannedFiles:t.scannedTextFiles,textCoverage:{basis:"current-project-text-files",candidateFiles:t.candidateFiles,scannedTextFiles:t.scannedTextFiles,scannedBytes:t.scannedBytes,skippedBinaryPaths:t.skippedBinaryPaths,skippedUnreadablePaths:t.skippedUnreadablePaths,skippedOversizedPaths:t.skippedOversizedPaths,semanticFiles:t.semanticFiles}}}function gA(e,t,n,r){let i=t.split(`
|
|
63
|
-
`),o=t.endsWith(`
|
|
64
|
-
`)?i.length-1:i.length;if(n<0||n>=o)return null;let s=Math.max(0,n-r),a=Math.min(o-1,n+r);return{relativePath:e,startLine:s,endLine:a,focusLine:n,source:i.slice(s,a+1).join(`
|
|
65
|
-
`)}}function hA(e){let t=new Map;for(let n of e){let r=yA(n.relativePath),i=t.get(r)??{matchingLines:0,matchingFiles:0};i.matchingLines+=n.matchingLines,i.matchingFiles+=1,t.set(r,i)}return[...t.entries()].map(([n,r])=>({scope:n,...r})).sort((n,r)=>r.matchingLines-n.matchingLines||r.matchingFiles-n.matchingFiles||n.scope.localeCompare(r.scope))}function yA(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function Wb(e,t){let n=e.map((i,o)=>({...i,priority:xe(i.fileKind),sequence:o,evidenceCharacters:1,roles:["search"],reasons:["search"],symbols:i.ownerSymbol?[i.ownerSymbol]:[],behaviorSignals:[]})),r=[];for(let i of[0,1,2]){let o=t-r.length;if(o===0)break;let s=n.filter(a=>xe(a.fileKind)===i);r.push(...qa(s,o,Number.MAX_SAFE_INTEGER,Vb).selected)}return r.map(({priority:i,sequence:o,evidenceCharacters:s,roles:a,reasons:c,symbols:l,behaviorSignals:u,...d})=>d)}function Vb(e,t){return xe(e.fileKind)-xe(t.fileKind)||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||e.relativePath.localeCompare(t.relativePath)||e.focusLine-t.focusLine}function bA(e,t,n={}){if(t.length===0)throw new Error("The source search pattern must not be empty.");return Ga(e,[t],n)[0]}function za(e,t){return ee(e)-ee(t)||e.relativePath.localeCompare(t.relativePath)}function he(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function wi(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}`;t.has(i)||(t.add(i),n.push(r))}return n}function ke(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))]}function qe(e){return e.replace(/^#/u,"").replace(/\(\)$/u,"")}var Yb=new WeakMap,Jb=new WeakMap,Xb=new WeakMap,Qb=new WeakMap,Zb=new WeakMap;function eS(e,t){let n=Jb.get(e);n||(n=new Map,Jb.set(e,n));let r=n.get(t);if(r)return r;let i=J(e,t)?.rootNode;if(!i)return n.set(t,[]),[];let o=new Set;Qt(i,l=>{if(l.type!=="call_expression")return;let u=l.childForFieldName("function")??l.namedChild(0),d=/^([A-Za-z_$][\w$]*(?:\.Service)?)\.of$/u.exec(u?.text.replace(/\s+/gu,"")??"");d&&o.add(d[1])});let s=ae(e,t).filter(l=>!!l.sourcePath),a=new Set;for(let l of o){let u=/^([A-Za-z_$][\w$]*)\.Service$/u.exec(l);if(u){for(let d of s)d.localName===u[1]&&a.add(d.sourcePath);continue}if(l==="Service"){U(e,t).some(d=>d.leaf==="Service")&&a.add(t);for(let d of s)(d.localName??d.importedName)==="Service"&&a.add(d.sourcePath)}}let c=ad([...a]).sort();return n.set(t,c),c}function nr(e,t,n={}){let i=Gt(e,t)?.filter(p=>!n.ranges||n.ranges.some(f=>p.line>=f.startLine&&p.line<=f.endLine));if(!i)return{targets:[],unresolvedCallsites:0};let o=ae(e,t).filter(p=>!!p.sourcePath),s=NA(W(e,t)??""),a=J(e,t)?.rootNode??null,c=a?vA(a):tS(),l=new Map,u=zt(e),d=[],m=0;for(let p of i){if(!p.memberAccess)continue;let f=_t(t,u.get(p.calleeLeaf)??[]);if(n.excludeIndexedTargets!==!1&&$n(e,t,f,!0,p.calleeQualifier))continue;let g=p.calleeQualifier,h=AA(e,t,p,o);if(h){d.push(h);continue}let b=SA(e,t,p,o,CA(c,p.calleeQualifier,p.line));if(b.length>0){d.push(...b);continue}let S=xA(e,t,p);if(S.length>0){d.push(...S);continue}let y=g?s.get(g)??g:null,v=(y?ad(o.filter(R=>(R.localName??R.importedName)===y).map(R=>R.sourcePath)):[]).flatMap(R=>{let E=l.get(R);return E||(E=Et(e,R)??[],l.set(R,E)),E.filter(w=>w.name===p.calleeLeaf).map(w=>({file:R,callable:w}))});if(v.length!==1){m+=1;continue}let C=v[0];d.push({calleeLeaf:p.calleeLeaf,line:p.line,sourceFile:t,targetFile:C.file,targetStartLine:C.callable.startLine,targetEndLine:C.callable.endLine,resolution:"direct-import-receiver",strength:"candidate"})}return{targets:d,unresolvedCallsites:m}}function SA(e,t,n,r,i){let o=n.calleeQualifier;if(!o||!/^[A-Za-z_$][\w$]*$/u.test(o))return[];if(i.size!==1)return[];let s=[...i][0],a=ad(r.filter(u=>u.localName===s||u.importedName===s).map(u=>u.sourcePath));if(a.length!==1)return[];let c=a[0],l=wA(e,c,n.calleeLeaf);return l.map(u=>({calleeLeaf:u.name,line:n.line,sourceFile:t,targetFile:u.file,targetStartLine:u.startLine,targetEndLine:u.endLine,serviceFile:c,resolutionAlternativeCount:l.length,resolution:"imported-service-object-member",strength:"candidate"}))}function tS(){return{declarations:new Map,callbacks:[]}}function vA(e){let t=tS();return Qt(e,n=>{if(n.type==="variable_declarator"){let c=n.childForFieldName("name")??n.namedChild(0),l=n.childForFieldName("value")??n.namedChild(1);if(c?.type!=="identifier"||!l)return;let u=new Set;if(Qt(l,d=>{if(d.type!=="member_expression")return;let m=d.childForFieldName("object")??d.namedChild(0),p=d.childForFieldName("property")??d.namedChild(1);m?.type==="identifier"&&p?.text==="Service"&&u.add(m.text)}),u.size===1){let d=t.declarations.get(c.text)??[];d.push({line:n.startPosition.row,alias:[...u][0]}),t.declarations.set(c.text,d)}return}if(!["arrow_function","function_expression","generator_function"].includes(n.type))return;let r=n.childForFieldName("parameters")??n.childForFieldName("parameter");if(!r)return;let i=n.parent;for(;i&&i.type!=="call_expression";)i=i.parent;if(!i)return;let o=i.childForFieldName("function")??i.namedChild(0),s=/^([A-Za-z_$][\w$]*)\.Service\.use$/u.exec(o?.text??"");if(!s)return;let a=new Set;Qt(r,c=>{c.type==="identifier"&&a.add(c.text)}),a.size!==0&&t.callbacks.push({startLine:n.startPosition.row,endLine:n.endPosition.row,receivers:a,alias:s[1]})}),t}function CA(e,t,n){if(!t||!/^[A-Za-z_$][\w$]*$/u.test(t))return new Set;let r=new Set((e.declarations.get(t)??[]).filter(i=>i.line<=n).map(i=>i.alias));for(let i of e.callbacks)i.startLine<=n&&i.endLine>=n&&i.receivers.has(t)&&r.add(i.alias);return r}function xA(e,t,n){let r=n.calleeQualifier;if(!r||!/^[A-Za-z_$][\w$]*$/u.test(r))return[];let i=J(e,t)?.rootNode;if(!i)return[];let o=RA(e,t,i,n.line,n.calleeLeaf,r),s=o?IA(o,r):null;if(!s)return[];if(!EA(s))return[];let a=(Et(e,t)??[]).filter(p=>p.startLine<=s.startPosition.row&&p.endLine>=s.endPosition.row).sort((p,f)=>p.endLine-p.startLine-(f.endLine-f.startLine))[0];if(!a)return[];let c=U(e,t).filter(p=>p.isFunctionLike&&p.leaf===a.name);if(c.length!==1)return[];let l=c[0],u=Qb.get(e);u||(u=new Map,Qb.set(e,u));let d=`${l.symbol}\0${n.calleeLeaf}`,m=u.get(d);if(!m){let p=[];for(let f of eo(e,l)){let g=J(e,f.file)?.rootNode;if(!g)continue;let h=g.descendantsOfType("call_expression").filter(y=>y.startPosition.row>f.line||y.endPosition.row<f.line?!1:(y.childForFieldName("function")??y.namedChild(0))?.text.replace(/\s+/gu,"").replace(/<[^<>]*>$/u,"").match(/[A-Za-z_$][\w$]*$/u)?.[0]===l.leaf);if(h.length!==1)continue;let S=h[0].childForFieldName("arguments")?.namedChildren.find(y=>Fr(y).type==="object");if(S)for(let y of Fr(S).namedChildren){if(y.type==="shorthand_property_identifier"&&y.text===n.calleeLeaf){p.push(...Ka(e,f.file,n.calleeLeaf,y,y));continue}if(y.type!=="pair")continue;let x=y.childForFieldName("key")??y.namedChild(0),v=y.childForFieldName("value")??y.namedChild(1);Wa(x?.text)!==n.calleeLeaf||!v||p.push(...Ka(e,f.file,n.calleeLeaf,v,y))}}m=p.filter((f,g,h)=>h.findIndex(b=>b.file===f.file&&b.startLine===f.startLine&&b.endLine===f.endLine&&b.name===f.name)===g),u.set(d,m)}return m.map(p=>({calleeLeaf:p.name,line:n.line,sourceFile:t,targetFile:p.file,targetStartLine:p.startLine,targetEndLine:p.endLine,resolutionAlternativeCount:m.length,resolution:"factory-callback-member",strength:m.length===1?"exact":"candidate"}))}function RA(e,t,n,r,i,o){let s=Xb.get(e);s||(s=new Map,Xb.set(e,s));let a=s.get(t);if(!a){a=new Map;for(let c of n.descendantsOfType("call_expression")){let l=c.childForFieldName("function")??c.namedChild(0),u=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(l?.text.replace(/\s+/gu,"")??"");if(u)for(let d=c.startPosition.row;d<=c.endPosition.row;d+=1){let m=`${d}\0${u[1]}\0${u[2]}`,p=a.get(m);(!p||c.endIndex-c.startIndex<p.endIndex-p.startIndex)&&a.set(m,c)}}s.set(t,a)}return a.get(`${r}\0${o}\0${i}`)??null}function EA(e){return e.descendantsOfType("return_statement").some(t=>{let n=t.childForFieldName("argument")??t.namedChild(0);return!!(n&&Fr(n).type==="object")})}function IA(e,t){let n=e.parent;for(;n;){if(/(?:function|method|lambda)/u.test(n.type)||n.type==="arrow_function"){let r=n.childForFieldName("parameters")??n.childForFieldName("parameter"),i=!1;if(r&&Qt(r,o=>{o.type==="identifier"&&o.text===t&&(i=!0)}),i)return n}n=n.parent}return null}function Ka(e,t,n,r,i){if(r.type==="identifier")return(Et(e,t)??[]).filter(c=>c.name===r.text).map(c=>({...c,file:t}));let o=od(e,t,r.text);if(o.length>0)return o;if(!sd(r))return[];let a=(Et(e,t)??[]).filter(c=>c.startLine>=i.startPosition.row&&c.endLine<=i.endPosition.row&&(c.name===n||c.name.startsWith("source@"))).sort((c,l)=>c.endLine-c.startLine-(l.endLine-l.startLine))[0];return[a?{...a,file:t}:{name:n,file:t,startLine:i.startPosition.row,endLine:i.endPosition.row}]}function wA(e,t,n){let r=Zb.get(e);r||(r=new Map,Zb.set(e,r));let i=`${t}\0${n}`,o=r.get(i);if(o)return o;let s=DA(e,t).flatMap(a=>LA(e,a,t,n));return r.set(i,s),s}function LA(e,t,n,r){let i=J(e,t)?.rootNode,o=Et(e,t)??[];if(!i)return[];let s=MA(e,t,n);if(s.size===0)return[];let a=new Set,c=[],l=[],u=[];return Qt(i,m=>{if(PA(m,s)){if(m.type==="pair"){let p=m.childForFieldName("key")??m.namedChild(0),f=m.childForFieldName("value")??m.namedChild(1);if(Wa(p?.text)!==r||!f)return;if(f.type==="identifier")a.add(f.text);else if(sd(f))c.push({name:r,startLine:m.startPosition.row,endLine:m.endPosition.row});else{let g=TA(e,t,f.text),h=od(e,t,f.text);if(g.length>0)u.push(...g);else if(h.length>0)u.push(...h);else{let b=kA(m);b&&l.push(b)}}return}m.type==="shorthand_property_identifier"&&m.text===r&&a.add(r)}}),[...o.filter(m=>a.has(m.name)).map(m=>({...m,file:t})),...c.map(m=>({...m,file:t})),...l.map(m=>({...m,file:t})),...u].filter((m,p,f)=>f.findIndex(g=>g.file===m.file&&g.name===m.name&&g.startLine===m.startLine&&g.endLine===m.endLine)===p)}function PA(e,t){let n=e,r=null;for(;n;){if(n.type==="object"&&(r=n),n.type==="call_expression"){if(!r)return!1;let i=n.childForFieldName("function")??n.namedChild(0);return i?t.has(i.text.replace(/\.of$/u,""))&&i.text.endsWith(".of"):!1}n=n.parent}return!1}function DA(e,t){let n=Yb.get(e);n||(n=new Map,Yb.set(e,n));let r=n.get(t);if(r)return r;let i=new Set([t]),o=U(e,t).filter(a=>a.leaf==="Service"&&a.isTypeLike);for(let a of o)for(let c of eo(e,a))i.add(c.file);let s=[...i].sort();return n.set(t,s),s}function MA(e,t,n){let r=new Set;Fe(t,n)&&r.add("Service");for(let i of ae(e,t)){if(!i.sourcePath||!Fe(i.sourcePath,n))continue;if(i.kind==="namespace"&&i.localName){r.add(`${i.localName}.Service`);continue}(i.importedName==="default"?i.localName:i.importedName)==="Service"?r.add(i.localName??i.importedName):i.localName&&i.importedName!=="default"&&r.add(`${i.localName}.Service`)}return r}function od(e,t,n){let r=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!r)return[];let i=J(e,t)?.rootNode;if(!i)return[];let o=nS(i,r[1]),s=o?rS(o):null;if(!s)return[];let a=s.childForFieldName("function")??s.namedChild(0),c=a?iS(e,t,a.text):[];if(c.length!==1)return[];let l=c[0],u=J(e,l.relativePath)?.rootNode;if(!u)return[];let d=vl(u,l.startLine,l.endLine);if(!d)return[];let m=[];for(let p of d.descendantsOfType("return_statement")){let f=p.childForFieldName("argument")??p.namedChild(0);if(!f)continue;let g=Fr(f);if(g.type==="object")for(let h of g.namedChildren){if(h.type==="shorthand_property_identifier"&&h.text===r[2]){for(let y of Et(e,l.relativePath)??[])y.name===r[2]&&m.push({...y,file:l.relativePath});continue}if(h.type!=="pair")continue;let b=h.childForFieldName("key")??h.namedChild(0),S=h.childForFieldName("value")??h.namedChild(1);if(!(Wa(b?.text)!==r[2]||!S))if(S.type==="identifier")for(let y of Et(e,l.relativePath)??[])y.name===S.text&&m.push({...y,file:l.relativePath});else sd(S)&&m.push({name:r[2],startLine:h.startPosition.row,endLine:h.endPosition.row,file:l.relativePath})}}return m.filter((p,f,g)=>g.findIndex(h=>h.file===p.file&&h.name===p.name&&h.startLine===p.startLine&&h.endLine===p.endLine)===f)}function TA(e,t,n){let r=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!r)return[];let i=J(e,t)?.rootNode;if(!i)return[];let o=nS(i,r[1]),s=o?rS(o):null,a=s?.childForFieldName("function")??s?.namedChild(0),c=a?iS(e,t,a.text):[];if(c.length!==1||!s)return[];let l=c[0],u=J(e,l.relativePath)?.rootNode;if(!u)return[];let d=vl(u,l.startLine,l.endLine);if(!d)return[];let m=new Set,p=d.childForFieldName("parameters")??d.childForFieldName("parameter");if(p&&Qt(p,R=>{R.type==="identifier"&&m.add(R.text)}),m.size===0)return[];let f=od(e,t,n);if(f.length===0)return[];let g=(Et(e,l.relativePath)??[]).filter(R=>R.startLine>=l.startLine&&R.endLine<=l.endLine),h=(Gt(e,l.relativePath)??[]).filter(R=>R.line>=l.startLine&&R.line<=l.endLine),b=new Set,S=f.map(R=>({name:R.name,startLine:R.startLine,endLine:R.endLine})),y=new Set;for(;S.length>0&&y.size<32;){let R=S.shift(),E=`${R.name}\0${R.startLine}\0${R.endLine}`;if(!y.has(E)){y.add(E);for(let w of h.filter(I=>I.line>=R.startLine&&I.line<=R.endLine)){if(w.memberAccess&&w.calleeQualifier&&m.has(w.calleeQualifier)){b.add(w.calleeLeaf);continue}if(w.memberAccess)continue;let I=g.filter(k=>k.name===w.calleeLeaf);I.length===1&&S.push(I[0])}}}if(b.size===0)return[];let v=s.childForFieldName("arguments")?.namedChildren.find(R=>Fr(R).type==="object");if(!v)return[];let C=[];for(let R of Fr(v).namedChildren){if(R.type==="shorthand_property_identifier"&&b.has(R.text)){C.push(...Ka(e,t,R.text,R,R));continue}if(R.type!=="pair")continue;let E=R.childForFieldName("key")??R.namedChild(0),w=R.childForFieldName("value")??R.namedChild(1),I=Wa(E?.text);!I||!b.has(I)||!w||C.push(...Ka(e,t,I,w,R))}return C.filter((R,E,w)=>w.findIndex(I=>I.file===R.file&&I.name===R.name&&I.startLine===R.startLine&&I.endLine===R.endLine)===E)}function nS(e,t){for(let n of e.descendantsOfType("variable_declarator"))if((n.childForFieldName("name")??n.namedChild(0))?.text===t)return n.childForFieldName("value")??n.namedChild(1);return null}function rS(e){return e.type==="call_expression"?e:e.descendantsOfType("call_expression")[0]??null}function iS(e,t,n){let r=n.replace(/\s+/gu,"").replace(/<[^<>]*>$/u,""),i=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(r);if(i){let d=ae(e,t).filter(f=>f.localName===i[1]&&f.sourcePath);if(d.length!==1||!d[0].sourcePath)return[];let m=d[0].sourcePath,p=qn(e,m,i[2]).filter(f=>f.isFunctionLike);return p.length>0?p:(Et(e,m)??[]).filter(f=>f.name===i[2]).map(f=>({...f,relativePath:m}))}if(!/^[A-Za-z_$][\w$]*$/u.test(r))return[];let o=U(e,t).filter(d=>d.leaf===r&&d.isFunctionLike);if(o.length>0)return o;let s=(Et(e,t)??[]).filter(d=>d.name===r).map(d=>({...d,relativePath:t}));if(s.length>0)return s;let a=ae(e,t).filter(d=>d.localName===r&&d.sourcePath&&d.kind!=="namespace");if(a.length!==1||!a[0].sourcePath)return[];let c=a[0].sourcePath,l=a[0].importedName==="default"?r:a[0].importedName,u=qn(e,c,l).filter(d=>d.isFunctionLike);return u.length>0?u:(Et(e,c)??[]).filter(d=>d.name===l).map(d=>({...d,relativePath:c}))}function sd(e){return["arrow_function","function_expression","generator_function"].includes(e.type)||e.descendantsOfType(["arrow_function","function_expression","generator_function"]).length>0}function kA(e){let t=e.parent;for(;t;){if(t.type==="variable_declarator"){let n=t.childForFieldName("name")??t.namedChild(0);if(n?.type==="identifier")return{name:n.text,startLine:t.startPosition.row,endLine:t.endPosition.row}}t=t.parent}return null}function Wa(e){return e?e.replace(/^(?:['"])(.*)(?:['"])$/u,"$1"):null}function AA(e,t,n,r){let i=/^this\.([A-Za-z_$][\w$]*)$/u.exec(n.calleeQualifier??"");if(!i)return null;let o=J(e,t)?.rootNode;if(!o)return null;let s=FA(o,n.line);if(!s)return null;let a=new Set;if(Qt(s,g=>{if(g.type!=="assignment_expression")return;let h=g.childForFieldName("left")??g.namedChild(0),b=g.childForFieldName("right")??g.namedChild(g.namedChildCount-1);if(h?.text.replace(/\s+/gu,"")!==`this.${i[1]}`||!b)return;let S=Fr(b);if(S.type!=="new_expression")return;let x=(S.childForFieldName("constructor")??S.namedChild(0))?.text.match(/[A-Za-z_$][\w$]*$/u)?.[0];x&&a.add(x)}),a.size!==1)return null;let c=[...a][0],l=r.filter(g=>g.localName===c);if(l.length!==1)return null;let u=l[0].importedName==="default"?c:l[0].importedName,d=l[0].importedName==="default"?qn(e,l[0].sourcePath,c):[],m=d.length===1?d[0].leaf:u,p=U(e,l[0].sourcePath).filter(g=>g.isFunctionLike&&g.leaf===n.calleeLeaf&&pf(g.symbol)===m);if(p.length!==1)return null;let f=p[0];return{calleeLeaf:n.calleeLeaf,line:n.line,sourceFile:t,targetFile:f.relativePath,targetStartLine:f.startLine,targetEndLine:f.endLine,targetSymbol:f.symbol,resolution:"constructed-member-receiver",strength:"exact"}}function FA(e,t){let n=[];return Qt(e,r=>{["class","class_declaration","class_definition"].includes(r.type)&&r.startPosition.row<=t&&r.endPosition.row>=t&&n.push(r)}),n.sort((r,i)=>r.endPosition.row-r.startPosition.row-(i.endPosition.row-i.startPosition.row))[0]??null}function Fr(e){let t=e;for(;["parenthesized_expression","as_expression","type_assertion","satisfies_expression"].includes(t.type)&&t.namedChildCount===1;)t=t.namedChild(0);return t}function Qt(e,t){t(e);for(let n of e.namedChildren)Qt(n,t)}function NA(e){let t=new Map,n=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*([A-Za-z_$][\w$]*)\s*;/gu;for(let r of e.matchAll(n)){let i=r[1],o=r[2];i&&o&&t.set(i,o)}return t}function ad(e){let t=[];for(let n of e)t.some(r=>Fe(r,n))||t.push(n);return t}import{existsSync as OA}from"fs";import{SymbolRole as BA}from"@c4312/scip";import{deserializeSCIP as _A}from"@c4312/scip";function oS(e,t){return _A(Qr(e,{inputKind:t,maxBytes:Xr}))}var cd=new WeakMap;function Rn(e,t,n,r){let i=K(e,t),o=(i?.callSites??[]).filter(p=>p.line>=n&&p.line<=r);if(!i||o.length===0)return{available:!!i,targets:[],resolvedCallsites:0,unresolvedCallsites:0};let s=ud(e);if(!s)return{available:!1,targets:[],resolvedCallsites:0,unresolvedCallsites:o.length};let a=(s.byFile.get(t)??[]).filter(p=>p.sourceLine>=n&&p.sourceLine<=r).map(p=>({...p,calleeLeaf:p.definition.leaf})),c=sS(o.map(p=>({line:p.line,leaf:p.calleeLeaf}))),l=sS(a.map(p=>({line:p.sourceLine,leaf:p.calleeLeaf}))),u=new Set([...c].flatMap(([p,f])=>l.get(p)===f?[p]:[])),d=a.filter(p=>u.has(cS(p.sourceLine,p.calleeLeaf))),m=[...u].reduce((p,f)=>p+(c.get(f)??0),0);return{available:!0,targets:d,resolvedCallsites:m,unresolvedCallsites:Math.max(0,o.length-m)}}function ld(e,t,n,r){let i=ud(e);return i?{available:!0,targets:(i.byFile.get(t)??[]).filter(o=>o.sourceLine>=n&&o.sourceLine<=r)}:{available:!1,targets:[]}}function aS(e,t,n,r){let i=ud(e);return i?{available:!0,targets:(i.byFile.get(t)??[]).filter(o=>o.sourceLine>=n&&o.sourceLine<=r&&Va(e,o.definition)).map(o=>({...o,calleeLeaf:o.definition.leaf}))}:{available:!1,targets:[]}}function ud(e){if(cd.has(e))return cd.get(e)??null;let t=$A(e);return cd.set(e,t),t}function $A(e){if(!e.generation.indexPath||!OA(e.generation.indexPath))return null;try{let t=Le(e),n=new Map(t.map(o=>[o.symbol,o])),r=oS(e.generation.indexPath,"SCIP source-range call-target index"),i=new Map;for(let o of r.documents??[]){let s=o.relativePath;if(!s||e.isIgnored(s))continue;let a=[];for(let c of o.occurrences??[]){if(!c.symbol||(c.symbolRoles&BA.Definition)!==0)continue;let l=n.get(c.symbol),u=c.range?.[0];!l||!Number.isInteger(u)||a.push({sourceLine:u,definition:l})}i.set(s,a)}return{byFile:i}}catch{return null}}function Va(e,t){if(!t.isFunctionLike)return!1;let n=K(e,t.relativePath);return!n||n.callables.some(r=>r.name===t.leaf&&r.startLine===t.startLine&&r.endLine===t.endLine)?!0:jA(t)}function jA(e){let t=e.documentation;if(!t)return!1;let n=e.leaf.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`\\bfunction\\s+${n}\\s*(?:<[^>]*>)?\\s*\\(`,"u").test(t)||new RegExp(`\\b(?:const|let|var)\\s+${n}\\s*:\\s*(?:<[^>]*>\\s*)?\\([^\\n]*\\)\\s*=>`,"u").test(t)}function sS(e){let t=new Map;for(let n of e){let r=cS(n.line,n.leaf);t.set(r,(t.get(r)??0)+1)}return t}function cS(e,t){return`${e}\0${t}`}var HA=16,UA=4,dd=3e3,qA=800,GA=new Set(["assignment","const_declaration","const_item","field_declaration","lexical_declaration","local_declaration_statement","local_variable_declaration","static_item","variable_declaration"]);function fS(e,t,n={}){let r=n.maxSteps??HA;if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`maxSteps must be a positive safe integer; received ${r}`);let i=new Map(t.nodes.map(M=>[M.id,M])),o=XA(n.focusLocations??[]),s=new Set,a=new Map(t.edges.map(M=>[M.id,M])),c=En(t.paths.flatMap(M=>M.nodeIds)),l=En(t.anchors.filter(M=>M.status==="matched").flatMap(M=>M.nodeIds)),u=t.nodes.filter(M=>M.disposition==="emitted"&&M.attributes.upstreamCausalPath===!0).sort((M,$)=>Number($.attributes.upstreamCausalDistance??0)-Number(M.attributes.upstreamCausalDistance??0)||M.id.localeCompare($.id)).map(M=>M.id),d=new Set(u),m=Math.max(0,r-l.length),f=zA(t,l,o,m).slice(0,m),g=new Set(f),h=new Set(f),b=new Set([...c,...u,...l]),S=t.edges.filter(M=>M.disposition==="emitted"&&M.kind!=="structural-membership"),y=t.edges.filter(M=>M.disposition!=="excluded"&&M.disposition!=="unsupported"&&M.kind!=="structural-membership"),x=new Set([...t.paths.flatMap(M=>M.edgeIds),...S.filter(M=>d.has(M.fromNodeId)&&d.has(M.toNodeId)).map(M=>M.id)]),v=t.paths.some(M=>M.edgeIds.length>0),C=new Set(l);for(let M of f)C.add(M);for(let M of t.paths){let $=M.nodeIds[0],Y=a.get(M.edgeIds[0]??""),oe=M.nodeIds[1];$&&oe&&Y?.fromNodeId===$&&Y.toNodeId===oe&&C.add($)}if(t.paths.every(M=>M.nodeIds.length===0))for(let M of t.anchors)for(let $ of M.nodeIds)C.add($);let R=nF(l,y,i,UA),E=En(S.filter(M=>M.kind==="call"&&l.includes(M.fromNodeId)).map(M=>M.toNodeId)),w=new Set(En([...R,...v?[]:E]));for(let M of w)C.add(M);let I=En(S.flatMap(M=>b.has(M.fromNodeId)||b.has(M.toNodeId)?[M.fromNodeId,M.toNodeId]:[])),k=t.nodes.filter(M=>M.disposition==="emitted"&&M.kind!=="structural-region"&&S.some($=>$.fromNodeId===M.id||$.toNodeId===M.id)).map(M=>M.id),D=En([...u,...c,...l,...f,...w,...I,...k]).filter(M=>i.has(M)),F=[];for(let M of D)v&&!b.has(M)&&!g.has(M)&&!w.has(M)||F.length>=r&&!b.has(M)||F.push(M);let L=new Set(F),A=new Map(F.map(M=>[M,iF(M)])),P=new Set([...c,...u]),j=new Set(t.anchors.flatMap(M=>M.nodeIds)),B=F.map((M,$)=>{let Y=i.get(M),oe=JA(Y,o);for(let Ae of oe)s.add(Li(Y.location.file,Ae));return{id:A.get(M),nodeId:M,order:$,role:j.has(M)?"anchor":P.has(M)?"connector":"junction",kind:Y.kind,label:Y.label,location:Y.location,behavior:KA(e,Y,j.has(M),[...new Set([...oe,...YA(e,Y,y,i,x,C)])],oe,C.has(Y.id)&&(oe.length===0||j.has(Y.id)),w.has(Y.id),h.has(Y.id)&&oe.length===0)}}),X=new Map;for(let M of t.paths)for(let $=0;$<M.edgeIds.length;$+=1){let Y=a.get(M.edgeIds[$]),oe=M.nodeIds[$],Ae=M.nodeIds[$+1];!Y||!oe||!Ae||X.set(Y.id,Y.fromNodeId===oe&&Y.toNodeId===Ae?"forward":"reverse")}let O=y.filter(M=>L.has(M.fromNodeId)&&L.has(M.toNodeId)).sort((M,$)=>rF(M,$,t)).map((M,$)=>({id:oF(M.id),edgeId:M.id,order:$,kind:M.kind,fromStepId:A.get(M.fromNodeId),toStepId:A.get(M.toNodeId),directed:!0,pathTraversal:X.get(M.id)??"adjacent",evidence:M.evidence})),te=new Map(O.map(M=>[M.edgeId,M.id])),ie=t.paths.map(M=>({id:M.id,status:M.status,stepIds:M.nodeIds.flatMap($=>{let Y=A.get($);return Y?[Y]:[]}),transitionIds:M.edgeIds.flatMap($=>{let Y=te.get($);return Y?[Y]:[]})})),we=B.flatMap(M=>M.location?[`${M.location.file}:${M.location.line+1}`]:[]),De=t.anchors.some(M=>M.status==="ambiguous"),Ft=ie.some(M=>M.status==="connected"||M.status==="candidate"),tt=ie.some(M=>M.status==="partial");return{status:B.length===0?"unavailable":De?"ambiguous":Ft&&!tt?"connected":tt?"partial":"connected",steps:B,transitions:O,paths:ie,coverage:{candidateNodes:D.length,returnedNodes:F.length,omittedNodeIds:D.filter(M=>!L.has(M)),returnedTransitions:O.length,withheldStatements:B.reduce((M,$)=>M+($.behavior?.coverage.omittedStatements??0),0),requestedFocusLocations:o,matchedFocusLocations:o.filter(M=>s.has(Li(M.file,M.line))),unmatchedFocusLocations:o.filter(M=>!s.has(Li(M.file,M.line)))},behaviorCommand:pS(we,"behavior"),exactSourceCommand:pS(we,"source")}}function zA(e,t,n,r){if(r<=0||n.length===0)return[];let i=new Set(t),o=new Set(n.map(s=>Li(s.file,s.line)));return En(e.edges.filter(s=>s.disposition!=="excluded"&&s.disposition!=="unsupported"&&["call","runtime-boundary"].includes(s.kind)&&i.has(s.fromNodeId)&&s.evidence.some(a=>!["candidate","unknown"].includes(a.strength)&&a.location&&o.has(Li(a.location.file,a.location.line)))).sort((s,a)=>{let c=s.evidence.find(u=>u.location)?.location,l=a.evidence.find(u=>u.location)?.location;return(c?.file??"").localeCompare(l?.file??"")||(c?.line??Number.MAX_SAFE_INTEGER)-(l?.line??Number.MAX_SAFE_INTEGER)||s.id.localeCompare(a.id)}).map(s=>s.toNodeId)).slice(0,r)}function KA(e,t,n,r,i,o,s,a){if(!t.location||!["symbol","source-construct","runtime-boundary-participant"].includes(t.kind))return null;let c=t.location.endLine??t.location.line,l=V(e,t.location.file),u=r.length>0?r:[t.location.line],d=t.kind==="runtime-boundary-participant"?ot(e,t.location.file,0,Math.max(0,l.length-1),[t.location.line]):ot(e,t.location.file,t.location.line,c,u),m=r.filter(w=>w>=d.startLine&&w<=d.endLine),p=mi(e,t.location.file,d.startLine,d.endLine,m),f=p??(m.length>0?mi(e,t.location.file,d.startLine,d.endLine,m,{requireSavings:!1}):null),g=m.length>0?QA(e,t,d.startLine,d.endLine,m,f,o):null,h=l.slice(d.startLine,d.endLine+1).join(`
|
|
66
|
-
`).length,b=yn(e,t.location.file,d.startLine,d.endLine),S=l.slice(d.startLine,d.endLine+1).some((w,I)=>w.length>qA&&(b.get(d.startLine+I)??[]).some(k=>["binding","branch","loop","call","return","throw","mutation"].includes(k))),y=w=>WA(e,t,d.startLine,d.endLine,i.filter(I=>I>=d.startLine&&I<=d.endLine),w),x=(s||t.kind==="runtime-boundary-participant"||t.anchorIds.length>0)&&h<=dd,v=n&&(m.length===0||x);if(p&&(a||v))return y(lS(p));if(!a&&!v&&g&&!S&&!x&&g.renderedCharacters<(f?.outlineCharacters??h))return y(g);if(p)return y(lS(p));let C=l.slice(d.startLine,d.endLine+1),R=C.join(`
|
|
67
|
-
`),E=yn(e,t.location.file,d.startLine,d.endLine);return y({kind:"source",constructKind:"source construct",signature:C.find(w=>w.trim().length>0)?.trim()??t.label,lines:C.map((w,I)=>({line:d.startLine+I,endLine:d.startLine+I,depth:0,signals:E.get(d.startLine+I)??[],text:w,copied:!0})),coverage:{sourceStatements:C.length,representedStatements:C.length,copiedStatements:C.length,omittedStatements:0},rawCharacters:R.length,renderedCharacters:R.length})}function WA(e,t,n,r,i,o){if(!t.location)return o;let s=ld(e,t.location.file,n,r);if(!s.available)return o;let a=yn(e,t.location.file,n,r),c=V(e,t.location.file),l=new Set(i);for(let S of i){let y=Ya(c[S]??"");if(!y)continue;let x=fn(e,t.location.file,y).find(v=>v>S&&v<=r);x!==void 0&&l.add(x)}let u=[...new Map(s.targets.flatMap(S=>{let y=S.definition,x=y.relativePath===t.location.file&&y.startLine<=r&&y.endLine>=n;if(y.isTypeLike||x)return[];let v=Va(e,y),C=i.length>0&&v&&a.get(S.sourceLine)?.includes("return"),R=v&&l.has(S.sourceLine);return v&&!C&&!R?[]:[[y.symbol,{definition:y,kind:C?"return-value-transformer":R?"focused-causal-target":"compiler-referenced-declaration"}]]})).values()].sort((S,y)=>S.definition.relativePath.localeCompare(y.definition.relativePath)||S.definition.startLine-y.definition.startLine||S.definition.symbol.localeCompare(y.definition.symbol)),d=[],m=u.filter(({kind:S})=>S!=="compiler-referenced-declaration").map(({definition:S})=>({owner:S,depth:1})),p=new Set,f=new Set(u.map(({definition:S})=>S.symbol));for(;m.length>0;){let S=m.shift();if(!S||p.has(S.owner.symbol))continue;p.add(S.owner.symbol);let{owner:y,depth:x}=S,v=ld(e,y.relativePath,y.startLine,y.endLine);if(!v.available)continue;let C=yn(e,y.relativePath,y.startLine,y.endLine),R=V(e,y.relativePath);for(let E of v.targets){let w=E.definition,I=w.relativePath===y.relativePath&&w.startLine<=y.endLine&&w.endLine>=y.startLine;if(w.isTypeLike||I)continue;let k=Va(e,w),D=Ya(R[E.sourceLine]??""),F=k&&D!==null&&fn(e,y.relativePath,D).some(A=>A>E.sourceLine&&A<=y.endLine&&(C.get(A)??[]).some(P=>["branch","return","throw"].includes(P))),L=k&&((C.get(E.sourceLine)??[]).some(A=>["branch","return","throw"].includes(A))||F);k&&!L||(f.has(w.symbol)||(f.add(w.symbol),d.push({definition:w,kind:k?"focused-causal-target":"compiler-referenced-declaration"})),k&&x<2&&m.push({owner:w,depth:x+1}))}}let g=[...new Map([...u,...d].map(S=>[S.definition.symbol,S])).values()].sort((S,y)=>S.definition.relativePath.localeCompare(y.definition.relativePath)||S.definition.startLine-y.definition.startLine||S.definition.symbol.localeCompare(y.definition.symbol)),h=[],b=[];for(let{definition:S,kind:y}of g){let x=y==="compiler-referenced-declaration"?VA(e,S.relativePath,S.startLine,S.endLine):{startLine:S.startLine,endLine:S.endLine},v=V(e,S.relativePath).slice(x.startLine,x.endLine+1).join(`
|
|
68
|
-
`),C=y==="compiler-referenced-declaration"?null:mi(e,S.relativePath,S.startLine,S.endLine,[]),R=C?[C.signature,...C.lines.map(D=>`${D.line+1}${D.signals.length>0?`[${D.signals.join(",")}]`:""} ${D.text}`)].join(" | "):null,E=R&&R.length<v.length?R:v,w={symbol:S.symbol,label:S.leaf,file:S.relativePath,line:x.startLine,endLine:x.endLine},I=y==="compiler-referenced-declaration"?1e3:8e3,k=y==="compiler-referenced-declaration"?12:120;if(E.length>I||x.endLine-x.startLine>k){b.push({...w,reason:"source-too-large"});continue}h.push({kind:y,...w,text:E})}return{...o,...h.length===0?{}:{supportingDeclarations:h},...b.length===0?{}:{omittedSupportingDeclarations:b}}}function VA(e,t,n,r){let i=J(e,t);if(!i)return{startLine:n,endLine:r};let o=[];gS(i.rootNode,a=>{GA.has(a.type)&&a.startPosition.row<=n&&a.endPosition.row>=r&&o.push(a)});let s=o.sort((a,c)=>a.endPosition.row-a.startPosition.row-(c.endPosition.row-c.startPosition.row)||a.endIndex-a.startIndex-(c.endIndex-c.startIndex))[0];return s?{startLine:s.startPosition.row,endLine:s.endPosition.row}:{startLine:n,endLine:r}}function gS(e,t){t(e);for(let n of e.namedChildren)gS(n,t)}function lS(e){return{kind:"outline",constructKind:e.constructKind,signature:e.signature,lines:e.lines,coverage:e.coverage,rawCharacters:e.rawCharacters,renderedCharacters:e.outlineCharacters}}function YA(e,t,n,r,i,o){if(!t.location||!["symbol","source-construct","runtime-boundary-participant"].includes(t.kind))return[];let s=new Set,a=new Set(K(e,t.location.file)?.callSites.map(c=>c.line)??[]);if(t.kind==="runtime-boundary-participant"&&s.add(t.location.line),o.has(t.id))for(let c of no(e,{files:[t.location.file]}))c.source.startLine>=t.location.line&&c.source.startLine<=(t.location.endLine??t.location.line)&&s.add(c.source.startLine);for(let c of n){if(c.fromNodeId!==t.id&&c.toNodeId!==t.id)continue;let l=r.get(c.fromNodeId===t.id?c.toNodeId:c.fromNodeId),u=o.has(t.id)&&["call","reference","runtime-boundary"].includes(c.kind)&&c.fromNodeId===t.id,d=(l?.anchorIds.length??0)>0;if(!i.has(c.id)&&!u&&!d)continue;let m=c.evidence.flatMap(b=>b.location?.file===t.location.file?[b.location.line]:[]),p=m.filter(b=>a.has(b));for(let b of p.length>0?p:m)s.add(b);let f=l?.attributes.leaf;if(typeof f!="string"||f.length===0)continue;let g=fn(e,t.location.file,f).filter(b=>b>=t.location.line&&b<=(t.location.endLine??t.location.line)),h=g.find(b=>a.has(b))??g[0];h!==void 0&&s.add(h)}return[...s].sort((c,l)=>c-l)}function JA(e,t){if(!e.location)return[];let n=e.location.endLine??e.location.line;return t.filter(r=>r.file===e.location.file&&r.line>=e.location.line&&r.line<=n).map(r=>r.line)}function XA(e){let t=new Map;for(let n of e){if(!n.file||!Number.isSafeInteger(n.line)||n.line<0)throw new RangeError(`Behavior focus locations require a repository file and non-negative line; received ${JSON.stringify(n)}.`);t.set(Li(n.file,n.line),{file:n.file,line:n.line})}return[...t.values()].sort((n,r)=>n.file.localeCompare(r.file)||n.line-r.line)}function Li(e,t){return`${e}\0${t}`}function QA(e,t,n,r,i,o,s){if(!t.location)return null;let a=V(e,t.location.file),c=yn(e,t.location.file,n,r),l=[...c].filter(([,L])=>L.length>0).map(([L])=>L).sort((L,A)=>L-A),u=i.map(L=>(c.get(L)??[]).length>0?L:l.find(A=>A>L&&A-L<=8)??L),d=new Set([...i,...u]),m=s?_l(e,t.location.file,n,r,{minimumBodyLines:0}):null,p=o?[...new Map(u.flatMap(L=>o.lines.filter(A=>A.text.length<=500&&A.signals.some(P=>["branch","loop","catch","finally"].includes(P))&&L>=A.line&&L<=A.endLine).sort((A,P)=>A.endLine-A.line-(P.endLine-P.line)||A.line-P.line).slice(0,2).map(A=>[`${A.line}\0${A.endLine}`,A]))).values()]:sa(e,t.location.file,n,r,u);for(let L of m?.lines??[])d.add(L.line);for(let L of p)d.add(L.line);for(let[L,A]of c)A.includes("call")&&A.includes("shape")&&d.add(L);let f=[];for(let L of u){let A=Ya(a[L]??"");if(!A)continue;let P=fn(e,t.location.file,A).filter(O=>O>L&&O<=r),j=P[0];j!==void 0&&d.add(j);let B=P.find(O=>(c.get(O)??[]).some(te=>te==="branch"||te==="loop"));if(B===void 0)continue;d.add(B);let X=(o?.lines??[]).find(O=>O.line===B)??{line:B,endLine:Math.min(r,B+40),depth:0,signals:c.get(B)??[],text:(a[B]??"").trim(),copied:!0},G=o?.lines??a.slice(X.line,X.endLine+1).map((O,te)=>{let ie=X.line+te;return{line:ie,endLine:ie,depth:0,signals:c.get(ie)??[],text:O.trim(),copied:!0}});f.push({focusLine:L,governingUse:B,lines:G.filter(O=>O.line>=X.line&&O.line<=X.endLine&&O.text.length<=500&&O.signals.some(te=>["binding","branch","call","mutation"].includes(te)))})}for(let L of f.sort((A,P)=>P.governingUse-P.focusLine-(A.governingUse-A.focusLine)||A.focusLine-P.focusLine).slice(0,2))for(let A of L.lines.slice(0,14))d.add(A.line);let g=new Set(["binding","branch","loop","call","return","throw","mutation"]);for(let L of p)for(let A of o?.lines??[])A.line<L.line||A.line>L.endLine||A.signals.some(P=>g.has(P))&&d.add(A.line);let h=a.slice(n,r+1).flatMap((L,A)=>{let P=Ya(L);return P?[{name:P,line:n+A}]:[]}),b=!0;for(;b;){b=!1;for(let L of h)if([...d].some(P=>eF(a[P]??"",L.name))){d.has(L.line)||(d.add(L.line),b=!0);for(let P of fn(e,t.location.file,L.name))P<n||P>r||d.has(P)||(c.get(P)??[]).some(j=>g.has(j))&&(d.add(P),b=!0)}}for(let L of o?.lines??[])if(L.signals.some(A=>["branch","loop","catch","finally"].includes(A))&&d.has(L.line))for(let A of o?.lines??[])A.line<L.line||A.line>L.endLine||A.signals.some(P=>g.has(P))&&d.add(A.line);let S=K(e,t.location.file),y=new Set(S?.callSites.map(L=>L.line)??[]),x=c,v=new Map([...o?.lines??[],...p].filter(L=>L.signals.some(A=>["branch","loop","catch","finally"].includes(A))).map(L=>[L.line,L])),C=new Map((o?.lines??[]).filter(L=>L.text.length<=500&&L.signals.includes("shape")&&(L.signals.includes("call")||L.signals.includes("mutation")||L.signals.includes("return"))).sort((L,A)=>L.endLine-L.line-(A.endLine-A.line)||L.line-A.line).map(L=>[L.line,L])),R=new Map((m?.lines??[]).map(L=>[L.line,L.signals.filter(A=>A!=="lifecycle")])),E=[...d].filter(L=>L>=n&&L<=r).sort((L,A)=>L-A).map(L=>{let A=v.get(L)??C.get(L);return{line:L,endLine:A?.endLine??L,depth:A?.depth??0,signals:ZA([...x.get(L)??[],...o?.lines.filter(P=>L>=P.line&&L<=P.endLine).flatMap(P=>P.signals)??[],...R.get(L)??[],...i.includes(L)?["anchor"]:[],...y.has(L)?["call"]:[]]),text:A?.text??(a[L]??"").trim(),copied:A?.copied??!0}}).filter(L=>L.text.length>0);if(E.length===0)return null;let w=m?.candidateLines??_l(e,t.location.file,n,r,{minimumBodyLines:0})?.candidateLines??0,I=Math.max(o?.coverage.sourceStatements??0,w,E.length),k=o?.signature??(a[n]??t.label).trim(),D=k.length+E.reduce((L,A)=>L+A.text.length+A.signals.join(",").length+12,0),F=a.slice(n,r+1).join(`
|
|
69
|
-
`).length;return{kind:"connector-slice",constructKind:o?.constructKind??"source construct",signature:k,lines:E,coverage:{sourceStatements:I,representedStatements:E.length,copiedStatements:E.length,omittedStatements:Math.max(0,I-E.length)},rawCharacters:F,renderedCharacters:D}}function ZA(e){let t=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],n=new Set(e);return t.filter(r=>n.has(r))}function Ya(e){return/\b(?:const|let|var)\s+([\p{L}_$][\p{L}\p{N}_$]*)\s*(?:=|\bof\b|\bin\b)/u.exec(e)?.[1]??null}function eF(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`(?:^|[^\\p{L}\\p{N}_$])${n}(?:$|[^\\p{L}\\p{N}_$])`,"u").test(e)}function tF(e,t,n){return En(e.flatMap(r=>{let i=n.get(r),o=t.filter(s=>s.kind==="call"&&s.toNodeId===r).map(s=>({edge:s,node:n.get(s.fromNodeId)})).filter(s=>s.node!==void 0&&["symbol","source-construct","runtime-boundary-participant"].includes(s.node.kind)&&s.node.location!==null).sort((s,a)=>{let c=uS(a.edge)-uS(s.edge);if(c!==0)return c;let l=dS(s.node,i)?0:1,u=dS(a.node,i)?0:1,d=(s.node.location?.endLine??s.node.location?.line??0)-(s.node.location?.line??0),m=(a.node.location?.endLine??a.node.location?.line??0)-(a.node.location?.line??0);return l-u||d-m||s.node.label.localeCompare(a.node.label)});return o[0]?[o[0].node.id]:[]}))}function uS(e){let t={exact:4,mixed:3,derived:2,candidate:1,unknown:0};return Math.max(0,...e.evidence.map(n=>t[n.strength]))}function dS(e,t){return!e.location||!t?.location?!1:mS(e.location.file)===mS(t.location.file)}function mS(e){return e.split("/").filter(Boolean).slice(0,2).join("/")}function nF(e,t,n,r){let i=new Set(e),o=new Set,s=[],a=En(e);for(let c=0;c<r&&a.length>0;c+=1){let l=a.filter(d=>!o.has(d));for(let d of l)o.add(d);let u=tF(l,t,n);a=[];for(let d of u)!i.has(d)&&!s.includes(d)&&s.push(d),o.has(d)||a.push(d)}return s}function rF(e,t,n){let r=new Map(n.paths.flatMap(i=>i.edgeIds).map((i,o)=>[i,o]));return(r.get(e.id)??Number.MAX_SAFE_INTEGER)-(r.get(t.id)??Number.MAX_SAFE_INTEGER)||e.id.localeCompare(t.id)}function iF(e){return`step:${e}`}function oF(e){return`transition:${e}`}function pS(e,t){return e.length===0?null:`scip-query inspect ${e.map(n=>`--at ${sF(n)}`).join(" ")} --view ${t}`}function sF(e){return`'${e.replace(/'/gu,`'"'"'`)}'`}function En(e){return[...new Set(e)]}var hS=4,aF=3,cF=12,lF=48,uF=64,Or=10,Nr=6,dF=24,mF=320,md=6,pF=12,fF=1,gF=4,hF=7,yF=12,yd="source-construct:",bF=96,SF=32,yS=4,vF=32,CF=8,bS=new Set(["a","an","and","are","as","at","be","become","becomes","by","can","does","for","from","how","in","into","is","it","its","of","on","or","that","the","their","then","this","through","to","what","when","where","which","with"]);function xF(e,t,n={}){let r=kS(t),i=a0(t);if(r.length===0)throw new Error("Anchor discovery requires at least one non-trivial repository term.");let o=n.limit??hS,s=n.full===!0;if(!Number.isSafeInteger(o)||o<=0)throw new RangeError(`anchor group limit must be a positive safe integer; received ${o}`);let a=new H(e),c=a.scopedDefinitions(n.scope).filter(O=>!me(O.symbol)),l=[...c],u=new Map(l.map(O=>[O.symbol,O])),d=new Map;for(let O of c)SS(d,O,r);let m=ag(e,{scope:n.scope});for(let O of m.files){let ie=U(e,O.relativePath).filter(De=>!me(De.symbol));if(ie.length===0)continue;let we=Fn(O.text);for(let De=0;De<we.length;De+=1){let Ft=at(we[De]??""),tt=r.filter($=>Ft.has($));if(tt.length===0)continue;let M=Ne(ie,De);if(!(!M||me(M.symbol)))for(let $ of tt)Ao(d,M,$,"source",O.relativePath,De)}}let p=vS(d),f=[...d.values()].map(O=>Ja(O,p,i)).sort(Ge),g=EF(m.files,f,r),h=-1;for(let O of g){let te=U(e,O.relativePath),ie=te.filter(M=>!me(M.symbol)),we=K(e,O.relativePath)?.callables??[],De=new Map,Ft=M=>{let $=`${M.startLine}\0${M.endLine}\0${M.name}`,Y=De.get($);if(Y)return Y;let oe=RF(O.relativePath,te,M,()=>h--);return oe?(De.set($,oe),l.push(oe),u.set(oe.symbol,oe),SS(d,oe,r),oe):null};for(let M of we){let $=at(M.name);r.some(Y=>$.has(Y))&&Ft(M)}if(we.length===0)continue;let tt=Fn(O.text);for(let M=0;M<tt.length;M+=1){let $=at(tt[M]??""),Y=r.filter(gr=>$.has(gr));if(Y.length===0)continue;let oe=Nn(we,M),Ae=oe?Ft(oe):null;if(!Ae)continue;let Ut=CS(ie,M);if(CS(Ut?[Ut,Ae]:[Ae],M)?.symbol===Ae.symbol)for(let gr of Y)Ao(d,Ae,gr,"source",O.relativePath,M)}}let b=vS(d),S=new Map(m.files.map(O=>[O.relativePath,O.text.split(/\r?\n/u)]));for(let O of d.values()){let te=S.get(O.definition.relativePath);te&&(O.sourceCharacters=te.slice(O.definition.startLine,O.definition.endLine+1).join(`
|
|
70
|
-
`).length)}let y=[...d.values()].map(O=>Ja(O,b,i)).sort(Ge),x=Math.min(y.length,Math.max(cF,o*aF)),v=s?y:Pi([...y.slice(0,x),...[...y].sort(fd).slice(0,Math.max(lF,x)),...e0(y,r),...t0(y,r,b)]),C=v.length,R=v.map(O=>u.get(O.symbol)).filter(O=>O?.isFunctionLike===!0),E=IF(l),w=wF(e,a,v,R,u,E,new Set(d.keys()),n.semantic!==!1),I=DF(w,v,d,b,u),k=MF(I,b,r),D=GF(e,a,w,d,b,l,u,n.semantic!==!1),L=[...kF(e,a,I,u,b,n.semantic!==!1),...k,...I,...D].map(O=>({...O,queryPathMatches:r0(O)})).sort((O,te)=>_r(O,te,b)),A=s?L:i0(L,o,b),P=r.filter(O=>b.has(O)),j=r.filter(O=>!b.has(O)),B=Math.max(0,y.length-C),X=Math.max(0,L.length-A.length)+B,G=s?y.length:Math.min(y.length,o+hS);return{query:t,queryPathFragments:i,normalizedTerms:r,matchedTerms:P,unmatchedTerms:j,groups:A,candidateRoots:y,candidateRootCount:y.length,analyzedRootCount:C,omittedRootCount:B,omittedGroupCount:X,scannedFiles:m.files.length,scannedBytes:m.scannedBytes,recoveryCommand:X===0?null:`scip-query anchors ${ec(t)}${n.scope?` --scope ${ec(n.scope)}`:""} --limit ${G}`}}function kS(e){let t=tc(e).filter(n=>!bS.has(n.toLocaleLowerCase())).map(bd).filter(n=>n.length>=3&&!bS.has(n));return[...new Set(t)]}function SS(e,t,n){let r=at(t.leaf),i=at(t.relativePath),o=at(t.documentation??"");for(let a of n)r.has(a)&&Ao(e,t,a,"symbol"),i.has(a)&&Ao(e,t,a,"path"),o.has(a)&&Ao(e,t,a,"documentation");let s=e.get(t.symbol);s&&(s.symbolPhraseLength=l0(t.leaf,n))}function Ao(e,t,n,r,i,o){let s=e.get(t.symbol)??{definition:t,matches:new Map,symbolPhraseLength:0},a=s.matches.get(n)??{sources:new Set,locations:new Map};a.sources.add(r),i!==void 0&&o!==void 0&&a.locations.set(`${i}\0${o}`,{file:i,line:o}),s.matches.set(n,a),e.set(t.symbol,s)}function vS(e){let t=new Map;for(let n of e.values())for(let r of n.matches.keys())t.set(r,(t.get(r)??0)+1);return t}function RF(e,t,n,r){let i=t[0]?.documentId;if(i===void 0||t.find(a=>a.isFunctionLike&&a.leaf===n.name&&a.startLine===n.startLine&&a.endLine===n.endLine))return null;let s=r();return{documentId:i,symbolId:s,symbol:`${yd}${e}:${n.startLine}:${n.endLine}:${n.name}`,relativePath:e,startLine:n.startLine,startChar:0,endLine:n.endLine,endChar:0,leaf:n.name,parentTypeName:null,isFunctionLike:!0,isTypeLike:!1,kind:null,documentation:null,enclosingSymbol:null}}function EF(e,t,n){let r=new Set(t.slice(0,bF).map(s=>s.file)),i=new Set(n),o=e.map(s=>{let a=at(s.relativePath),c=s.relativePath.slice(s.relativePath.lastIndexOf("/")+1).replace(/\.[^.]+$/u,""),l=at(c),u=[...a].filter(m=>i.has(m)).length,d=[...l].filter(m=>i.has(m)).length;return{file:s,score:d*4+u}}).filter(s=>s.score>0).sort((s,a)=>a.score-s.score||xe(q(s.file.relativePath))-xe(q(a.file.relativePath))||s.file.relativePath.localeCompare(a.file.relativePath)).slice(0,SF);for(let s of o)r.add(s.file.relativePath);return e.filter(s=>r.has(s.relativePath))}function IF(e){let t=new Map;for(let n of e){if(!Zt(n))continue;let r=`${n.relativePath}\0${qe(n.leaf)}`,i=t.get(r)??[];i.push(n),t.set(r,i)}return t}function CS(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,r)=>n.endLine-n.startLine-(r.endLine-r.startLine)||Number(Zt(r))-Number(Zt(n))||n.startLine-r.startLine||n.symbol.localeCompare(r.symbol))[0]}function Zt(e){return e.symbol.startsWith(yd)}function rr(e){return Zt(e)?e.leaf:T(e.symbol)}function Ja(e,t,n=[]){let r=e.definition,i=[...e.matches.entries()].map(([l,u])=>({term:l,sources:[...u.sources].sort(u0),locations:[...u.locations.values()].sort(_S).slice(0,3)})).sort((l,u)=>l.term.localeCompare(u.term)),o=i.filter(l=>l.sources.some(u=>u!=="source")).map(l=>l.term),s=i.filter(l=>l.sources.includes("symbol")).map(l=>l.term),a=i.reduce((l,u)=>l+1/Math.max(1,t.get(u.term)??1),0),c=i.filter(l=>l.sources.includes("symbol")).reduce((l,u)=>l+1/Math.max(1,t.get(u.term)??1),0);return{symbol:r.symbol,label:rr(r),leaf:r.leaf,file:r.relativePath,line:r.startLine,endLine:r.endLine,kind:r.isFunctionLike?"callable":r.isTypeLike?"type":"symbol",fileKind:q(r.relativePath),matches:i,focusLocations:p0(e,t),matchedTerms:i.map(l=>l.term),symbolMatchedTerms:s,symbolPhraseLength:e.symbolPhraseLength,identityMatchedTerms:o,rarity:a,symbolRarity:c,queryPathMatches:c0(r.relativePath,n),...e.sourceCharacters===void 0?{}:{sourceCharacters:e.sourceCharacters}}}function wF(e,t,n,r,i,o,s,a){let c=r.filter(g=>!Zt(g)),l=t.calleeMap(c,{additive:!1,semantic:a}),u=new Map,d=new Map;for(let g of n){let h=i.get(g.symbol),b=h?Zt(h)?xS(e,h,i,o,1):Xa(e,h,l.get(h.symbolId)??[],i,1,s):[];u.set(g.symbol,b);for(let S of b){let y=i.get(S.toSymbol);y?.isFunctionLike&&(!h||!Zt(h)||Zt(y))&&d.set(y.symbol,y)}}let m=[...d.values()],p=t.calleeMap(m.filter(g=>!Zt(g)),{additive:!1,semantic:a}),f=new Map;for(let g of m)f.set(g.symbol,Zt(g)?xS(e,g,i,o,2):Xa(e,g,p.get(g.symbolId)??[],i,2,s));return n.map(g=>{let h=u.get(g.symbol)??[],b=h.flatMap(y=>f.get(y.toSymbol)??[]),S=In([...h,...b]);return{root:g,relations:S,nodeSymbols:new Set([g.symbol,...S.flatMap(y=>[y.fromSymbol,y.toSymbol])])}})}function Xa(e,t,n,r,i,o=new Set){let s=new Map;for(let a of n){let c=r.get(a.symbol);if(!c?.isFunctionLike||c.symbol===t.symbol||a.source==="ast-callsite"&&!PF(e,t,c,a.callsiteLine))continue;let l=s.get(c.symbol);(!l||s0(a,l)<0)&&s.set(c.symbol,a)}return[...s.entries()].map(([a,c])=>{let l=r.get(a);return{kind:"call",fromSymbol:t.symbol,fromLabel:T(t.symbol),fromFile:t.relativePath,toSymbol:l.symbol,toLabel:T(l.symbol),toFile:l.relativePath,depth:i,strength:hd(c.source),evidence:c.source,callsiteLine:c.callsiteLine??LF(e,t,l)}}).sort((a,c)=>Number(o.has(c.toSymbol))-Number(o.has(a.toSymbol))||en(a,c)).slice(0,uF)}function xS(e,t,n,r,i){let o=Rn(e,t.relativePath,t.startLine,t.endLine).targets.flatMap(s=>{let a=n.get(s.definition.symbol)??s.definition;return!a.isFunctionLike||a.symbol===t.symbol?[]:[{kind:"call",fromSymbol:t.symbol,fromLabel:rr(t),fromFile:t.relativePath,toSymbol:a.symbol,toLabel:rr(a),toFile:a.relativePath,depth:i,strength:"exact",evidence:"scip-occurrence-callsite",callsiteLine:s.sourceLine}]});for(let s of nr(e,t.relativePath,{ranges:[{startLine:t.startLine,endLine:t.endLine}],excludeIndexedTargets:!1}).targets){let a=[...r.get(`${s.targetFile}\0${qe(s.calleeLeaf)}`)??[],...U(e,s.targetFile).filter(c=>c.isFunctionLike&&qe(c.leaf)===s.calleeLeaf)].find(c=>c.startLine===s.targetStartLine&&c.endLine===s.targetEndLine);!a||a.symbol===t.symbol||o.push({kind:"call",fromSymbol:t.symbol,fromLabel:rr(t),fromFile:t.relativePath,toSymbol:a.symbol,toLabel:rr(a),toFile:a.relativePath,depth:i,strength:s.strength==="exact"?"exact":"derived",evidence:"ast-member-import-candidate",callsiteLine:s.line})}for(let s of K(e,t.relativePath)?.callSites??[]){if(s.line<t.startLine||s.line>t.endLine||s.memberAccess)continue;let a=(r.get(`${t.relativePath}\0${qe(s.calleeLeaf)}`)??[]).filter(l=>l.symbol!==t.symbol);if(a.length!==1)continue;let c=a[0];o.push({kind:"call",fromSymbol:t.symbol,fromLabel:rr(t),fromFile:t.relativePath,toSymbol:c.symbol,toLabel:rr(c),toFile:c.relativePath,depth:i,strength:"derived",evidence:"ast-callsite",callsiteLine:s.line})}return In(o).sort(en)}function LF(e,t,n){let r=qe(n.leaf);return K(e,t.relativePath)?.callSites.find(i=>i.line>=t.startLine&&i.line<=t.endLine&&qe(i.calleeLeaf)===r)?.line??null}function PF(e,t,n,r){if(r===void 0)return!1;let i=qe(n.leaf);return K(e,t.relativePath)?.callSites.some(o=>{if(o.line!==r)return!1;if(qe(o.calleeLeaf)===i)return!0;let s=ri(e,t.relativePath,o.calleeLeaf);return s!==null&&qe(s.importedName)===i&&Fe(s.sourcePath,n.relativePath)})??!1}function DF(e,t,n,r,i){let o=new Map(t.map((u,d)=>[u.symbol,d])),s=t.map((u,d)=>d),a=u=>{let d=u;for(;s[d]!==d;)d=s[d];for(;s[u]!==u;){let m=s[u];s[u]=d,u=m}return d},c=(u,d)=>{let m=a(u),p=a(d);m!==p&&(s[p]=m)};for(let u of e){let d=o.get(u.root.symbol);if(d!==void 0)for(let m of u.nodeSymbols){let p=o.get(m);p!==void 0&&c(d,p)}}let l=new Map;for(let u=0;u<t.length;u+=1){let d=a(u),m=l.get(d)??[];m.push(t[u]),l.set(d,m)}return[...l.values()].map((u,d)=>{let m=new Set(u.map(y=>y.symbol)),p=In(e.filter(y=>m.has(y.root.symbol)).flatMap(y=>y.relations)).sort(en),f=new Map(u.map(y=>[y.symbol,y]));for(let y of new Set(p.flatMap(x=>[x.fromSymbol,x.toSymbol]))){let x=n.get(y);if(x)f.has(y)||f.set(y,Ja(x,r));else{let v=i.get(y);v&&f.set(y,FS(v))}}let g=XF(u,p,f),h=u.filter(y=>p.some(x=>x.fromSymbol===y.symbol)).length,b=[...new Set(u.flatMap(y=>y.matchedTerms))].sort(),S=JF(p,g,m,f);return{id:`anchor-set:${d+1}:${No(u[0])}`,kind:"connected-flow",roots:[...u].sort(Ge),keyAnchors:g,candidateOwnerCount:g.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:[],matchedTerms:b,relations:S,relationCount:p.length,orchestrationRootCount:h,omittedRelations:Math.max(0,p.length-Or),systemMapCommand:Oo(g,p,b)}})}function MF(e,t,n){let r=new Map(n.map((o,s)=>[o,s])),i=[];for(let o=0;o<e.length;o+=1){let s=e[o],a=RS(s);if(a.size!==0)for(let c=o+1;c<e.length;c+=1){let l=e[c],u=RS(l),d=[...a].filter(v=>u.has(v));if(d.length===0||![...a].some(v=>!u.has(v))||![...u].some(v=>!a.has(v)))continue;let m=TF(s,l);if(m.length<2)continue;let p=In([...s.relations,...l.relations]).sort(en),f=p.slice(0,Or),g=Pi([...s.roots,...l.roots]).sort(Ge),h=[...new Set([...s.matchedTerms,...l.matchedTerms])].sort(),b=d.sort((v,C)=>(r.get(v)??Number.MAX_SAFE_INTEGER)-(r.get(C)??Number.MAX_SAFE_INTEGER)||v.localeCompare(C)),S=+(s.relationCount>0)+ +(l.relationCount>0),y=+((s.orchestrationRootCount??0)>0)+ +((l.orchestrationRootCount??0)>0),x=Math.min(...b.map(v=>t.get(v)??Number.MAX_SAFE_INTEGER));i.push({sharedOrder:Math.min(...b.map(v=>r.get(v)??Number.MAX_SAFE_INTEGER)),sharedFrequency:x,connectedSides:S,orchestrationSides:y,group:{id:`parallel-paths:${No(s.roots[0])}:${No(l.roots[0])}`,kind:"parallel-paths",roots:g,keyAnchors:m,candidateOwnerCount:m.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:[...s.upstreamEntries,...l.upstreamEntries],matchedTerms:h,relations:f,relationCount:p.length,parallelConnectedSides:S,parallelOrchestrationSides:y,parallelSharedPathTerms:b,parallelSharedPathFrequency:x,orchestrationRootCount:(s.orchestrationRootCount??0)+(l.orchestrationRootCount??0),omittedRelations:Math.max(0,p.length-f.length),systemMapCommand:Oo(m,p,h)}})}}return i.sort((o,s)=>o.sharedFrequency-s.sharedFrequency||s.orchestrationSides-o.orchestrationSides||s.connectedSides-o.connectedSides||o.sharedOrder-s.sharedOrder||s.group.matchedTerms.length-o.group.matchedTerms.length||_r(o.group,s.group,t)).slice(0,yF).map(o=>o.group)}function RS(e){return new Set(e.roots.flatMap(t=>t.matches.filter(n=>n.sources.includes("path")).map(n=>n.term)))}function TF(e,t){return Pi([ES(e),ES(t)].filter(n=>n!==void 0))}function ES(e){let t=new Set(e.keyAnchors.map(r=>r.symbol)),n=new Map;for(let r of e.relations)!t.has(r.fromSymbol)||!t.has(r.toSymbol)||n.set(r.fromSymbol,(n.get(r.fromSymbol)??0)+1);return[...e.keyAnchors].sort((r,i)=>+((n.get(i.symbol)??0)>0)-+((n.get(r.symbol)??0)>0)||IS(i)-IS(r)||i.identityMatchedTerms.length-r.identityMatchedTerms.length||i.symbolMatchedTerms.length-r.symbolMatchedTerms.length||(n.get(i.symbol)??0)-(n.get(r.symbol)??0)||Ge(r,i))[0]}function IS(e){return e.matchedTerms.length+e.identityMatchedTerms.length*2+(e.queryPathMatches?.length??0)*4}function kF(e,t,n,r,i,o){let s=Ys(e);if(!s||s.links.length===0||n.length<2)return[];let a=new Map(s.observations.map(p=>[p.id,p])),c=new Map,l=new Map,u=[...n].sort((p,f)=>_r(p,f,i)).slice(0,pF),d=s.links.filter(p=>p.strength!=="candidate").sort((p,f)=>ir(f.strength)-ir(p.strength)||f.matchedKeyParts.length-p.matchedKeyParts.length||p.id.localeCompare(f.id));for(let p of u)for(let f of d){let g=a.get(f.from),h=a.get(f.to);if(!g||!h||!AF(p,g,r))continue;let b=FF(p,g,r);if(!b)continue;let S=c.get(h.id)??OF(e,t,h,r,o,gF);if(c.set(h.id,S),S.reachedSymbols.size===0)continue;let y=n.filter(L=>L.id!==p.id&&NF(L).some(A=>S.reachedSymbols.has(A))&&pd(b,L)>=2).sort((L,A)=>pd(b,A)-pd(b,L)||_r(L,A,i)).slice(0,fF);if(y.length===0)continue;let x=[p.id,g.id,...y.map(L=>L.id).sort()].join("\0");if(l.has(x))continue;let v=new Set(y.flatMap(_o)),C=UF(Fo(h),v,S.relations);if(C.length===0)continue;let R=HF(g,h,f.joinRule,f.matchedKeyParts,f.strength),E=In([R,...S.relations,...p.relations,...y.flatMap(L=>L.relations)]),w=qF([R,...C],E,p,y),I=Pi([b,...y.flatMap(L=>L.roots)]).sort(Ge),k=Pi([b,...y.flatMap(L=>L.keyAnchors)]).slice(0,hF),D=[...new Set([...b.matchedTerms,...y.flatMap(L=>L.matchedTerms)])].sort(),F=_F(e,t,b,r,o);I.length===0||k.length<2||l.set(x,{id:`cross-boundary-set:${No(b)}:${l.size+1}`,kind:"cross-boundary-flow",roots:I,keyAnchors:k,candidateOwnerCount:k.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:F,matchedTerms:D,relations:w,relationCount:E.length,omittedRelations:Math.max(0,E.length-w.length),systemMapCommand:Oo(k,E,D)})}let m=new Map;for(let[p,f]of l){let g=p.slice(0,p.indexOf("\0")),h=m.get(g);(!h||_r(f,h,i)<0)&&m.set(g,f)}return[...m.values()]}function AF(e,t,n){let r=new Set(_o(e));return t.owner.symbol&&r.has(t.owner.symbol)?!0:[...r].map(i=>n.get(i)).some(i=>i?.relativePath===t.source.file&&i.startLine<=t.source.startLine&&i.endLine>=t.source.endLine)}function FF(e,t,n){let r=Pi([...e.roots,...e.keyAnchors]);if(t.owner.symbol){let i=r.find(o=>o.symbol===t.owner.symbol);if(i)return i}return r.find(i=>{let o=n.get(i.symbol);return o?.relativePath===t.source.file&&o.startLine<=t.source.startLine&&o.endLine>=t.source.endLine})??null}function _o(e){return[...new Set([...e.roots.map(t=>t.symbol),...e.keyAnchors.map(t=>t.symbol),...e.relations.flatMap(t=>[t.fromSymbol,t.toSymbol])])]}function NF(e){return[...new Set([...e.roots,...e.keyAnchors].map(t=>t.symbol))]}function pd(e,t){let n=at(e.leaf),r=[...t.roots,...t.keyAnchors].map(o=>at(o.leaf)),i=0;for(let o of r){let s=0;for(let a of n)o.has(a)&&(s+=1);i=Math.max(i,s)}return i}function _F(e,t,n,r,i){let o=r.get(n.symbol);if(!o?.isFunctionLike)return[];let s=t.callerFileMap([o],{semantic:i,sourceFallback:!0}).get(o.symbolId);if(!s)return[];let a=at(n.leaf);return[...s].filter(c=>c!==n.file&&q(c)!=="test").flatMap(c=>{let l=K(e,c);return(l?.callSites??[]).filter(u=>qe(u.calleeLeaf)===qe(n.leaf)).flatMap(u=>{let d=(l?.callables??[]).filter(p=>p.startLine<=u.line&&p.endLine>=u.line).sort((p,f)=>p.endLine-p.startLine-(f.endLine-f.startLine)||p.startLine-f.startLine)[0];if(!d)return[];let m=[...at(d.name)].filter(p=>a.has(p)).length;return m>=2?[{name:d.name,file:c,line:d.startLine,endLine:d.endLine,callsiteLine:u.line,overlap:m}]:[]})}).sort((c,l)=>l.overlap-c.overlap||c.file.localeCompare(l.file)||c.line-l.line).slice(0,1).map(({name:c,file:l,line:u,endLine:d,callsiteLine:m})=>({name:c,file:l,line:u,endLine:d,callsiteLine:m}))}function OF(e,t,n,r,i,o){let s=BF(e,n,r),a=s.map(({definition:m,evidence:p,line:f})=>({kind:"call",fromSymbol:Fo(n),fromLabel:Qa(n),fromFile:n.source.file,toSymbol:m.symbol,toLabel:T(m.symbol),toFile:m.relativePath,depth:1,strength:p==="scip-occurrence-callsite"?"exact":"derived",evidence:p,callsiteLine:f})),c=$F(e,n);a.push(...c.relations);let l=AS([...s.map(m=>m.definition),...c.definitions]),u=l,d=new Set(u.map(m=>m.symbol));for(let m=2;m<=o+1&&u.length>0;m+=1){let p=t.calleeMap(u,{additive:!1,semantic:i}),f=new Map;for(let g of u){let h=Xa(e,g,p.get(g.symbolId)??[],r,m);a.push(...h);for(let b of h){let S=r.get(b.toSymbol);S?.isFunctionLike&&!d.has(S.symbol)&&f.set(S.symbol,S)}}u=[...f.values()];for(let g of u)d.add(g.symbol)}return{entryDefinitions:l,relations:In(a),reachedSymbols:new Set([...l.map(m=>m.symbol),...a.flatMap(m=>[m.fromSymbol,m.toSymbol])])}}function BF(e,t,n){let r=t.owner.symbol?n.get(t.owner.symbol):void 0;if(r?.isFunctionLike&&!me(r.symbol))return[{definition:r,evidence:"scip-occurrence-callsite",line:t.source.startLine}];let i=V(e,t.source.file),o=ot(e,t.source.file,0,Math.max(0,i.length-1),[t.source.startLine]),s=Rn(e,t.source.file,o.startLine,o.endLine).targets.map(u=>({definition:u.definition,evidence:"scip-occurrence-callsite",line:u.sourceLine})),a=K(e,t.source.file),c=zt(e),l=(a?.callSites??[]).flatMap(u=>{if(u.line<o.startLine||u.line>o.endLine)return[];let d=_t(t.source.file,c.get(u.calleeLeaf)??[]),m=$n(e,t.source.file,d,u.memberAccess,u.calleeQualifier),p=m?n.get(m.symbol):void 0;return p?.isFunctionLike?[{definition:p,evidence:"ast-callsite",line:u.line}]:[]});return jF([...s,...l])}function $F(e,t){let n=V(e,t.source.file),r=ot(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine]),i=nr(e,t.source.file,{ranges:[r],excludeIndexedTargets:!1}).targets,o=[],s=[];for(let a of i){let c=`source-construct:${a.targetFile}:${a.targetStartLine}:${a.targetEndLine}:${a.calleeLeaf}`;s.push({kind:"call",fromSymbol:Fo(t),fromLabel:Qa(t),fromFile:t.source.file,toSymbol:c,toLabel:a.calleeLeaf,toFile:a.targetFile,depth:1,strength:"derived",evidence:"ast-member-import-candidate",callsiteLine:a.line});let l=Rn(e,a.targetFile,a.targetStartLine,a.targetEndLine).targets;for(let u of l)o.push(u.definition),s.push({kind:"call",fromSymbol:c,fromLabel:a.calleeLeaf,fromFile:a.targetFile,toSymbol:u.definition.symbol,toLabel:T(u.definition.symbol),toFile:u.definition.relativePath,depth:2,strength:"exact",evidence:"scip-occurrence-callsite",callsiteLine:u.sourceLine})}return{definitions:AS(o),relations:In(s)}}function jF(e){return[...new Map(e.map(t=>[t.definition.symbol,t])).values()]}function AS(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function Fo(e){return e.owner.symbol??e.id}function Qa(e){return e.owner.name??`${e.source.file}:${e.source.startLine+1}`}function HF(e,t,n,r,i){return{kind:"runtime-boundary",fromSymbol:Fo(e),fromLabel:Qa(e),fromFile:e.source.file,toSymbol:Fo(t),toLabel:Qa(t),toFile:t.source.file,depth:1,strength:i,evidence:`runtime-boundary:${n}`,callsiteLine:e.source.startLine,runtimeBoundaryKey:r.map(o=>`${o.name}=${o.value}`).join(" ")}}function UF(e,t,n){let r=new Map;for(let s of n){let a=r.get(s.fromSymbol)??[];a.push(s),r.set(s.fromSymbol,a)}let i=[{symbol:e,path:[]}],o=new Set([e]);for(;i.length>0;){let s=i.shift();if(s.path.length>0&&t.has(s.symbol))return s.path;for(let a of(r.get(s.symbol)??[]).sort(en))o.has(a.toSymbol)||(o.add(a.toSymbol),i.push({symbol:a.toSymbol,path:[...s.path,a]}))}return[]}function qF(e,t,n,r){let i=In(e),o=new Set([n,...r].flatMap(s=>[..._o(s),...s.keyAnchors.map(a=>a.symbol)]));for(let s of t){if(i.length>=Or)break;!o.has(s.fromSymbol)&&!o.has(s.toSymbol)||i.some(a=>a.fromSymbol===s.fromSymbol&&a.toSymbol===s.toSymbol)||i.push(s)}return i.slice(0,Or)}function GF(e,t,n,r,i,o,s,a){let c=n.filter(u=>!u.root.symbol.startsWith(yd)).map(u=>({root:u.root,relations:u.relations.filter(d=>d.depth===1&&d.fromSymbol===u.root.symbol)}));return zF(c).flatMap((u,d)=>{let m=new Set(u.map(P=>P.root.symbol)),p=new Map;for(let P of u)for(let j of new Set(P.relations.map(B=>B.toSymbol)))p.set(j,(p.get(j)??0)+1);let f=[...p].filter(([,P])=>P>=2).sort(([P,j],[B,X])=>X-j||KF(P,B,r,i,s)).map(([P])=>s.get(P)).filter(P=>P?.isFunctionLike===!0).slice(0,dF);if(f.length===0)return[];let g=t.callerFileMap(f,{semantic:a,sourceFallback:!0}),h=new Set;for(let P of f){h.add(P.relativePath);for(let j of g.get(P.symbolId)??[])h.add(j)}let b=o.filter(P=>P.isFunctionLike&&h.has(P.relativePath)).sort(WF).slice(0,mF),S=t.calleeMap(b,{additive:!1,semantic:a}),y=new Set(f.map(P=>P.symbol)),x=In(b.flatMap(P=>Xa(e,P,S.get(P.symbolId)??[],s,1,y).filter(j=>y.has(j.toSymbol)))),v=new Map;for(let P of x){let j=v.get(P.fromSymbol)??new Set;j.add(P.toSymbol),v.set(P.fromSymbol,j)}let C=new Set([...v].filter(([P,j])=>j.size>=2||m.has(P)).map(([P])=>P)),R=x.filter(P=>C.has(P.fromSymbol));if(C.size<2||R.length===0)return[];let w=[...new Set(R.map(P=>P.toSymbol))].map(P=>Za(P,r,i,s)).filter(P=>P!==null).sort(Ge),I=[...C].map(P=>Za(P,r,i,s)).filter(P=>P!==null),k=VF(I,R),D=k.slice(0,md),F=k.slice(md);if(w.length===0||D.length===0)return[];let L=[...new Set([...w.flatMap(P=>P.matchedTerms),...u.flatMap(P=>P.root.matchedTerms)])].sort(),A=YF(R,D);return[{id:`effect-owner-set:${d+1}:${No(w[0])}`,kind:"shared-callee-owners",roots:w,keyAnchors:D,candidateOwnerCount:k.length,omittedCandidateOwners:F,ownerRecoveryCommands:f0(F,md),upstreamEntries:[],matchedTerms:L,relations:A,relationCount:R.length,omittedRelations:Math.max(0,R.length-A.length),systemMapCommand:Oo(D,R,L)}]})}function zF(e){let t=e.map((s,a)=>a),n=s=>{for(;t[s]!==s;)t[s]=t[t[s]],s=t[s];return s},r=(s,a)=>{let c=n(s),l=n(a);c!==l&&(t[l]=c)},i=e.map(s=>new Set(s.relations.map(a=>a.toSymbol)));for(let s=0;s<e.length;s+=1)for(let a=s+1;a<e.length;a+=1){let c=0;for(let l of i[s]??[])if((i[a]??new Set).has(l)&&(c+=1),c>=2)break;c>=2&&r(s,a)}let o=new Map;for(let s=0;s<e.length;s+=1){let a=n(s),c=o.get(a)??[];c.push(e[s]),o.set(a,c)}return[...o.values()].filter(s=>s.length>=2)}function KF(e,t,n,r,i){let o=Za(e,n,r,i),s=Za(t,n,r,i);return o?s?Ge(o,s):-1:s?1:e.localeCompare(t)}function WF(e,t){return xe(q(e.relativePath))-xe(q(t.relativePath))||e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine}function Za(e,t,n,r){let i=t.get(e);if(i)return Ja(i,n);let o=r.get(e);return o?FS(o):null}function VF(e,t){let n=new Map;for(let i of t){let o=n.get(i.toSymbol)??new Set;o.add(i.fromSymbol),n.set(i.toSymbol,o)}let r=new Map;for(let i of t){let o=n.get(i.toSymbol)?.size??1;r.set(i.fromSymbol,(r.get(i.fromSymbol)??0)+o*o)}return[...e].sort((i,o)=>Number(i.leaf.startsWith("#"))-Number(o.leaf.startsWith("#"))||o.identityMatchedTerms.length-i.identityMatchedTerms.length||(r.get(o.symbol)??0)-(r.get(i.symbol)??0)||Ge(i,o))}function YF(e,t){let n=new Map(t.map((s,a)=>[s.symbol,a])),r=t.map(s=>e.filter(a=>a.fromSymbol===s.symbol).sort(en)),i=[],o=0;for(;i.length<Or&&r.some(s=>o<s.length);){for(let s of r){let a=s[o];if(a&&i.push(a),i.length>=Or)break}o+=1}return i.sort((s,a)=>n.get(s.fromSymbol)-n.get(a.fromSymbol)||en(s,a))}function JF(e,t,n,r){let i=new Map(t.map((a,c)=>[a.symbol,c])),o=new Map;for(let a of e)o.set(a.fromSymbol,(o.get(a.fromSymbol)??0)+1);return[...e].sort((a,c)=>{let l=u=>{let d=0;return i.has(u.fromSymbol)&&(d+=100),n.has(u.toSymbol)&&(d+=60),d+=Math.min(40,(o.get(u.toSymbol)??0)*8),(r.get(u.toSymbol)?.matchedTerms.length??0)>0&&(d+=25),u.fromFile!==u.toFile&&(d+=15),u.strength==="exact"&&(d+=5),d};return l(c)-l(a)||en(a,c)}).slice(0,Or).sort((a,c)=>(i.get(a.fromSymbol)??Nr)-(i.get(c.fromSymbol)??Nr)||a.depth-c.depth||(a.callsiteLine??Number.MAX_SAFE_INTEGER)-(c.callsiteLine??Number.MAX_SAFE_INTEGER)||en(a,c))}function FS(e){return{symbol:e.symbol,label:rr(e),leaf:e.leaf,file:e.relativePath,line:e.startLine,endLine:e.endLine,kind:e.isFunctionLike?"callable":e.isTypeLike?"type":"symbol",fileKind:q(e.relativePath),matches:[],focusLocations:[],matchedTerms:[],symbolMatchedTerms:[],symbolPhraseLength:0,identityMatchedTerms:[],rarity:0,symbolRarity:0}}function XF(e,t,n){let r=[...e].sort(Ge),i=[],o=new Map;for(let u of t)o.set(u.fromSymbol,(o.get(u.fromSymbol)??0)+1);let s=new Set,a=new Set,c=u=>{if(!(!u||i.some(d=>d.symbol===u.symbol))){i.push(u);for(let d of u.matchedTerms)s.add(d);for(let d of u.symbolMatchedTerms)a.add(d)}},l=r.filter(u=>u.symbolPhraseLength>=2&&(o.get(u.symbol)??0)>=2);for(;i.length<Math.min(2,Nr);){let u=l.filter(d=>!i.some(m=>m.symbol===d.symbol)).sort((d,m)=>m.symbolMatchedTerms.filter(p=>!a.has(p)).length-d.symbolMatchedTerms.filter(p=>!a.has(p)).length||m.symbolPhraseLength-d.symbolPhraseLength||(o.get(m.symbol)??0)-(o.get(d.symbol)??0)||fd(d,m))[0];if(!u||i.length>0&&u.symbolMatchedTerms.every(d=>a.has(d)))break;c(u)}if(c(r[0]),i.length>=2){let u=QF(i[0].symbol,i[1].symbol,t,n);for(let d of u?.slice(1,-1)??[]){if(i.length>=Nr)break;c(n.get(d))}if(i.length<Nr){let d=new Set(i.map(f=>f.symbol)),m=new Set(t.filter(f=>f.depth===1&&d.has(f.fromSymbol)&&d.has(f.toSymbol)).map(f=>f.fromSymbol)),p=t.filter(f=>f.depth===1&&m.has(f.fromSymbol)&&!d.has(f.toSymbol)).map(f=>({relation:f,candidate:n.get(f.toSymbol)})).filter(f=>f.candidate!==void 0&&f.candidate.symbolPhraseLength>=2&&f.candidate.symbolMatchedTerms.length>=2).sort((f,g)=>(o.get(f.relation.fromSymbol)??0)-(o.get(g.relation.fromSymbol)??0)||fd(f.candidate,g.candidate))[0]?.candidate;c(p)}}else for(;i.length<Math.min(3,Nr);){let u=r.filter(d=>!i.some(m=>m.symbol===d.symbol)).sort((d,m)=>m.matchedTerms.filter(p=>!s.has(p)).length-d.matchedTerms.filter(p=>!s.has(p)).length||Ge(d,m))[0];if(!u||u.matchedTerms.every(d=>s.has(d)))break;c(u)}for(;i.length>=2&&i.length<Nr;){let u=new Set(i.map(m=>m.symbol)),d=[...n.values()].filter(m=>!u.has(m.symbol)&&(o.get(m.symbol)??0)>0&&t.some(p=>u.has(p.fromSymbol)&&p.toSymbol===m.symbol)).sort((m,p)=>p.identityMatchedTerms.length-m.identityMatchedTerms.length||p.symbolMatchedTerms.length-m.symbolMatchedTerms.length||p.matchedTerms.length-m.matchedTerms.length||(o.get(p.symbol)??0)-(o.get(m.symbol)??0)||Ge(m,p))[0];if(!d)break;c(d)}if(i.length<2){let u=i[0],d=u?r.filter(m=>m.symbol!==u.symbol).map(m=>({root:m,path:ZF(m.symbol,u.symbol,t)})).filter(m=>m.path!==null).sort((m,p)=>+(p.root.file!==u.file)-+(m.root.file!==u.file)||m.path.length-p.path.length||Ge(m.root,p.root))[0]?.root:void 0;c(d)}return i}function QF(e,t,n,r){let i=new Map;for(let a of n){let c=i.get(a.fromSymbol)??new Set;c.add(a.toSymbol),i.set(a.fromSymbol,c);let l=i.get(a.toSymbol)??new Set;l.add(a.fromSymbol),i.set(a.toSymbol,l)}let o=[{path:[e],cost:0}],s=new Map([[e,0]]);for(;o.length>0;){o.sort((u,d)=>u.cost-d.cost||u.path.length-d.path.length);let{path:a,cost:c}=o.shift(),l=a.at(-1);if(l===t)return a;for(let u of i.get(l)??[]){let d=r.get(u),m=u===t?1:!d||d.matchedTerms.length===0?9:d.symbolPhraseLength>=2?1:d.identityMatchedTerms.length>=2?2:4,p=c+m;p>=(s.get(u)??Number.POSITIVE_INFINITY)||(s.set(u,p),o.push({path:[...a,u],cost:p}))}}return null}function ZF(e,t,n){let r=new Map;for(let s of n){let a=r.get(s.fromSymbol)??[];a.push(s.toSymbol),r.set(s.fromSymbol,a)}let i=[[e]],o=new Set([e]);for(;i.length>0;){let s=i.shift(),a=s.at(-1);if(a===t)return s;for(let c of r.get(a)??[])o.has(c)||(o.add(c),i.push([...s,c]))}return null}function Ge(e,t){return(t.queryPathMatches?.length??0)-(e.queryPathMatches?.length??0)||t.identityMatchedTerms.length-e.identityMatchedTerms.length||t.matchedTerms.length-e.matchedTerms.length||t.rarity-e.rarity||Di(e.kind)-Di(t.kind)||xe(e.fileKind)-xe(t.fileKind)||e.file.localeCompare(t.file)||e.line-t.line}function fd(e,t){return t.symbolPhraseLength-e.symbolPhraseLength||t.symbolMatchedTerms.length-e.symbolMatchedTerms.length||Di(e.kind)-Di(t.kind)||t.symbolRarity-e.symbolRarity||Ge(e,t)}function e0(e,t){return t.flatMap(n=>{let r=e.filter(s=>s.matchedTerms.includes(n)).sort((s,a)=>n0(s,a,n)),i=[],o=new Set;for(let s of r)if(!o.has(s.file)&&(i.push(s),o.add(s.file),i.length>=yS))return i;for(let s of r)if(!i.some(a=>a.symbol===s.symbol)&&(i.push(s),i.length>=yS))break;return i})}function t0(e,t,n){let r=new Set(t),i=new Map;for(let o of e){if(o.kind!=="callable")continue;let s=o.file.slice(o.file.lastIndexOf("/")+1).replace(/\.[^.]+$/u,"");if(![...at(s)].some(c=>r.has(c)))continue;let a=i.get(o.file)??[];a.push(o),i.set(o.file,a)}return[...i.entries()].map(([o,s])=>{let a=o.slice(o.lastIndexOf("/")+1).replace(/\.[^.]+$/u,""),c=[...at(a)].filter(l=>r.has(l));return{file:o,fileCandidates:s,sharedFrequency:Math.min(...c.map(l=>n.get(l)??Number.MAX_SAFE_INTEGER))}}).sort((o,s)=>xe(o.fileCandidates[0].fileKind)-xe(s.fileCandidates[0].fileKind)||o.sharedFrequency-s.sharedFrequency||o.file.localeCompare(s.file)).flatMap(({fileCandidates:o})=>[...o].sort(Ge).slice(0,CF)).slice(0,vF)}function n0(e,t,n){return wS(e,n)-wS(t,n)||xe(e.fileKind)-xe(t.fileKind)||t.symbolPhraseLength-e.symbolPhraseLength||Di(e.kind)-Di(t.kind)||Ge(e,t)}function wS(e,t){let n=e.matches.find(r=>r.term===t)?.sources??[];return Math.min(...n.map(gd),Number.MAX_SAFE_INTEGER)}function Pi(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function _r(e,t,n){let r=new Set(e.roots.flatMap(o=>o.symbolMatchedTerms)),i=new Set(t.roots.flatMap(o=>o.symbolMatchedTerms));return(t.queryPathMatches?.length??0)-(e.queryPathMatches?.length??0)||MS(e.kind)-MS(t.kind)||PS(e)-PS(t)||DS(e)-DS(t)||(e.kind==="parallel-paths"&&t.kind==="parallel-paths"?(e.parallelSharedPathFrequency??Number.MAX_SAFE_INTEGER)-(t.parallelSharedPathFrequency??Number.MAX_SAFE_INTEGER)||(t.parallelOrchestrationSides??0)-(e.parallelOrchestrationSides??0)||(t.parallelSharedPathTerms?.length??0)-(e.parallelSharedPathTerms?.length??0):0)||LS(t,n)-LS(e,n)||t.matchedTerms.length-e.matchedTerms.length||Math.max(...t.roots.map(o=>o.symbolPhraseLength))-Math.max(...e.roots.map(o=>o.symbolPhraseLength))||i.size-r.size||Ge(e.roots[0],t.roots[0])||t.roots.length-e.roots.length||e.relationCount-t.relationCount||e.id.localeCompare(t.id)}function LS(e,t){return e.matchedTerms.reduce((n,r)=>n+1/Math.max(1,t.get(r)??1),0)}function r0(e){return[...new Set(e.roots.flatMap(t=>t.queryPathMatches??[]))].sort()}function PS(e){let t=e.keyAnchors.length>0?e.keyAnchors:e.roots;return Math.max(...t.map(n=>xe(n.fileKind)))}function DS(e){return e.kind==="parallel-paths"?2-(e.parallelConnectedSides??0):e.kind!=="connected-flow"||e.relationCount>0?0:1}function i0(e,t,n){let r=e.slice(0,t);if(t<2||r.some(o=>o.kind==="shared-callee-owners"))return r;let i=e.filter(o=>o.kind==="shared-callee-owners");for(let o of r){if(o.kind==="shared-callee-owners"||o.kind==="parallel-paths")continue;let s=new Set(_o(o)),a=i.map(l=>({group:l,overlap:o0(l,s)})).filter(({overlap:l})=>l>0).sort(({group:l,overlap:u},{group:d,overlap:m})=>m-u||_r(l,d,n))[0]?.group;if(!a)continue;let c=r.length-1;for(;c>=0&&r[c]===o;)c-=1;return c<0?r:(r[c]=a,[...r].sort((l,u)=>_r(l,u,n)))}return r}function o0(e,t){return _o(e).filter(n=>t.has(n)).length}function MS(e){switch(e){case"cross-boundary-flow":return 0;case"parallel-paths":case"connected-flow":return 1;case"shared-callee-owners":return 2}}function en(e,t){return e.depth-t.depth||ir(t.strength)-ir(e.strength)||e.fromLabel.localeCompare(t.fromLabel)||e.toLabel.localeCompare(t.toLabel)||(e.callsiteLine??Number.MAX_SAFE_INTEGER)-(t.callsiteLine??Number.MAX_SAFE_INTEGER)}function s0(e,t){return ir(hd(t.source))-ir(hd(e.source))||(e.callsiteLine??Number.MAX_SAFE_INTEGER)-(t.callsiteLine??Number.MAX_SAFE_INTEGER)||e.symbol.localeCompare(t.symbol)}function In(e){let t=new Map;for(let n of e){let r=`${n.fromSymbol}\0${n.toSymbol}`,i=t.get(r);(!i||en(n,i)<0)&&t.set(r,n)}return[...t.values()]}function tc(e){return e.replace(/([\p{Ll}\d])([\p{Lu}])/gu,"$1 $2").replace(/([\p{Lu}]+)([\p{Lu}][\p{Ll}])/gu,"$1 $2").match(/[\p{L}\d]+/gu)??[]}function a0(e){let t=e.match(/[\p{L}\d_.-]+(?:\/[\p{L}\d_.-]+)+/gu)??[];return[...new Set(t.map(n=>n.replace(/[.;:!?]+$/gu,"").toLocaleLowerCase()))]}function c0(e,t){let n=e.replace(/\\/gu,"/").toLocaleLowerCase();return t.filter(r=>{let i=n.indexOf(r);if(i<0)return!1;let o=i===0?"/":n[i-1],s=n[i+r.length];return o==="/"&&(s===void 0||s==="/")})}function l0(e,t){let n=tc(e).map(bd),r=0;for(let i=0;i<n.length;i+=1)for(let o=0;o<t.length;o+=1){let s=0;for(;i+s<n.length&&o+s<t.length&&n[i+s]===t[o+s];)s+=1;r=Math.max(r,s)}return r}function at(e){return new Set(tc(e).flatMap(NS).filter(t=>t.length>=3))}function NS(e){let t=bd(e);return t.length>4&&t.endsWith("e")?[t,t.slice(0,-1)]:[t]}function bd(e){let t=e.toLocaleLowerCase();return t.length>5&&t.endsWith("ies")?`${t.slice(0,-3)}y`:t.length>4&&t.endsWith("ied")?`${t.slice(0,-3)}y`:t.length>4&&t.endsWith("ed")?TS(t.slice(0,-2)):t.length>5&&t.endsWith("ing")?TS(t.slice(0,-3)):t.length>4&&t.endsWith("ers")||t.length>3&&t.endsWith("s")&&!t.endsWith("ss")?t.slice(0,-1):t}function TS(e){if(e.length<2)return e;let t=e.at(-1),n=e.at(-2);return t===n&&!"aeiou".includes(t)?e.slice(0,-1):e}function u0(e,t){return gd(e)-gd(t)}function gd(e){switch(e){case"symbol":return 0;case"path":return 1;case"documentation":return 2;case"source":return 3}}function Di(e){return e==="callable"?0:e==="type"?1:2}function hd(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function ir(e){return e==="exact"?2:1}function _S(e,t){return e.file.localeCompare(t.file)||e.line-t.line}function No(e){return`${e.file}:${e.line+1}`}function Oo(e,t=[],n=[]){let r=e.map(s=>`--symbol ${ec(`${s.file}:${s.line+1}-${s.endLine+1}`)}`),i=new Set(e.map(s=>s.symbol)),o=e.flatMap(s=>(s.sourceCharacters??0)>dd?d0(s,t,n,i).map(a=>`--focus-at ${ec(`${a.file}:${a.line+1}`)}`):[]);return`scip-query system-map ${[...r,...o,"--relation call","--relation runtime-boundary"].join(" ")}`}function d0(e,t,n,r){let i=new Set(n),o=t.filter(l=>l.fromSymbol===e.symbol&&l.callsiteLine!==null&&l.callsiteLine>=e.line&&l.callsiteLine<=e.endLine).map(l=>({file:e.file,line:l.callsiteLine,connectsAnchor:r.has(l.toSymbol),overlap:new Set(tc(m0(l.toLabel)).flatMap(NS).filter(u=>i.has(u))).size,strength:l.strength})).filter(l=>l.overlap>0).sort((l,u)=>Number(u.connectsAnchor)-Number(l.connectsAnchor)||u.overlap-l.overlap||l.line-u.line||ir(u.strength)-ir(l.strength)),s=o.filter(l=>l.connectsAnchor),a=[...s.length>0?s:o,...s.length>0?[]:e.focusLocations.map(l=>({...l,connectsAnchor:!1,overlap:0,strength:"derived"}))],c=[];for(let l of a)if(!c.some(u=>u.file===l.file&&u.line===l.line)&&(c.push({file:l.file,line:l.line}),c.length>=3))break;return c}function m0(e){return e.slice(Math.max(e.lastIndexOf(":"),e.lastIndexOf("."))+1)}function p0(e,t){let n=new Map;for(let[o,s]of e.matches)for(let a of s.locations.values()){if(a.file!==e.definition.relativePath||a.line<e.definition.startLine||a.line>e.definition.endLine)continue;let c=`${a.file}\0${a.line}`,l=n.get(c)??{...a,matchedTerms:new Set};l.matchedTerms.add(o),n.set(c,l)}let r=[...n.values()].sort((o,s)=>s.matchedTerms.size-o.matchedTerms.size||[...s.matchedTerms].reduce((a,c)=>a+1/Math.max(1,t.get(c)??1),0)-[...o.matchedTerms].reduce((a,c)=>a+1/Math.max(1,t.get(c)??1),0)||_S(o,s)),i=[];for(let o of r)if(!i.some(s=>s.file===o.file&&Math.abs(s.line-o.line)<8)&&(i.push(o),i.length>=3))break;return i.map(o=>({file:o.file,line:o.line,matchedTerms:[...o.matchedTerms].sort()}))}function f0(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(Oo(e.slice(r,r+t)));return n}function ec(e){return`'${e.replaceAll("'",`'"'"'`)}'`}import{createHash as iv}from"crypto";function Bo(e,t,n={}){let r=ne(e,t);if(!r)return null;let i=n.semantic!==!1,o=Gn(e,r,{semantic:i,semanticEvidence:re}).filter(l=>Se(l.symbol)).slice(0,50),s=wi(Pt(e,r,{limit:50,additive:!0,callableOnly:!0,semantic:i,semanticEvidence:re})),a=o.map(l=>({symbol:l.symbol,shortName:T(l.symbol),file:l.file,relationship:l.source!=="caller-map-inversion"?"reference-candidate":l.callEvidence==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:l.source==="caller-map-inversion"&&l.callEvidence!=="scip-chunk"?"exact":"candidate",evidenceSource:l.callEvidence??l.source})),c=s.map(l=>({symbol:l.symbol,shortName:T(l.symbol),file:l.file,relationship:l.source==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:l.source==="scip-chunk"?"candidate":"exact",evidenceSource:l.source}));return{symbol:r.symbol,shortName:T(r.symbol),callers:a.map(({symbol:l,shortName:u,file:d})=>({symbol:l,shortName:u,file:d})),callees:c.map(({symbol:l,shortName:u,file:d})=>({symbol:l,shortName:u,file:d})),callerEvidence:a,calleeEvidence:c,coverage:{scope:"indexed-static-call-graph",blindSpots:["unresolved dynamic dispatch and reflection","external or unindexed callees without a resolved symbol identity","SCIP chunk co-occurrence is retained only as candidate call evidence"]}}}function $o(e,t){let n=mt(e,t);return n?_n(e,"forward",[n]).filter(i=>!e.isIgnored(i)).map(i=>({relativePath:i,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):[]}function jo(e,t){let n=mt(e,t);return n?_n(e,"reverse",[n]).filter(i=>!e.isIgnored(i)).map(i=>({relativePath:i,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):[]}function Sd(e,t,n={}){let r=nc(e,t,n);return{definitions:r.definitions,referencedBy:r.referencedBy}}function nc(e,t,n={}){let r=ne(e,t);if(!r)return{definitions:[],referencedBy:[],referenceEvidence:[],claimSupport:null};let i=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",r.symbolId),o=si(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:v0(o,i?.display_name??null,r.symbol),source:S0(e,r.relativePath,r.startLine,r.endLine)}],a=n.referenceContext??2,c=Mf(e,r,{semantic:n.semantic,semanticEvidence:re}).map(u=>{let d=_g(e,u.file,u.line,a,z(r.symbol));return{relativePath:u.file,line:u.line,enclosingSymbol:u.enclosingSymbol,enclosingShort:u.enclosingSymbol?T(u.enclosingSymbol):"(top-level)",provenance:u.provenance,sourceStartLine:d?.startLine??null,sourceEndLine:d?.endLine??null,source:d?.source??null,sourceKind:d?.kind??"unavailable"}}),l=c.map(g0);return{definitions:s,referencedBy:l,referenceEvidence:c.map(u=>({relativePath:u.relativePath,line:u.line,provenance:u.provenance,sourceKind:u.sourceKind})),claimSupport:h0(c)}}function g0(e){return{relativePath:e.relativePath,line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort,sourceStartLine:e.sourceStartLine,sourceEndLine:e.sourceEndLine,source:e.source}}function h0(e){let t="resolved source-attributed or SCIP-indexed references to this exact symbol",n=["Dynamic dispatch, reflection, generated calls, and unindexed source are outside this scope."],r=e.filter(o=>o.sourceKind!=="complete-call-expression"&&o.sourceKind!=="non-call-reference"),i="direct, statically visible call expressions among the resolved reference sites";return{referenceAbsence:{status:"eligible",scope:t,limitations:n},callsitePredicates:r.length===0?{status:"eligible",scope:i,limitations:n}:{status:"ineligible",scope:i,reason:`${r.length} reference site(s) lack one unambiguous complete call expression.`,followup:y0(r)}}}function y0(e){let t=[...new Set(e.map(n=>`${n.relativePath}:${n.line+1}`))];return t.length===0||t.length>24?null:`scip-query inspect ${t.map(n=>`--at ${b0(n)}`).join(" ")} --view behavior`}function b0(e){return`'${e.replaceAll("'","'\\''")}'`}function S0(e,t,n,r){let i=W(e,t);if(!i)return null;let s=i.split(`
|
|
71
|
-
`).slice(n,r+1).join(`
|
|
72
|
-
`).trimEnd();return s.length>0?s:null}function v0(e,t,n){let r=oi(e);if(r&&!C0(r))return r;let i=(t??"").trim();return i?Se(n)&&!i.endsWith("()")?`${i}()`:i:T(n)}function C0(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function vd(e,t,n={}){let r=$S(e,t,n);if(r.kind!=="matched")return r;let{referenceEvidence:i,claimSupport:o,...s}=r;return s}function $S(e,t,n={}){let r=Qe(e,t);if(!r.match)return{kind:"missing",query:t};if(r.total>1)return{kind:"ambiguous",query:t,total:r.total,candidates:[{symbol:r.match.symbol,shortName:T(r.match.symbol),relativePath:r.match.relativePath,startLine:r.match.startLine},...r.candidates]};let i=r.match,o=R0(n.parts),s=o.includes("definition")||o.includes("references")?nc(e,i.symbol,{semantic:n.semantic,referenceContext:n.referenceContext}):{definitions:[],referencedBy:[],referenceEvidence:[],claimSupport:null},a=o.includes("callers")||o.includes("callees")?Bo(e,i.symbol,{semantic:n.semantic}):null,c=n.relatedSourceLines??80;return{kind:"matched",query:t,symbol:i.symbol,shortName:T(i.symbol),file:i.relativePath,parts:o,definition:o.includes("definition")?jg(e,i.symbol):null,referenceWindows:o.includes("references")?x0(e,s.referencedBy):[],callers:o.includes("callers")?BS(e,a?.callers??[],c):[],callees:o.includes("callees")?BS(e,a?.callees??[],c):[],dependencies:o.includes("dependencies")?$o(e,i.relativePath):[],consumers:o.includes("consumers")?jo(e,i.relativePath):[],referenceEvidence:s.referenceEvidence,claimSupport:s.claimSupport}}function x0(e,t){let n=t.filter(i=>i.sourceStartLine!==null&&i.sourceEndLine!==null&&i.source!==null).sort((i,o)=>i.relativePath.localeCompare(o.relativePath)||i.sourceStartLine-o.sourceStartLine||i.line-o.line),r=[];for(let i of n){let o=r[r.length-1];if(o&&o.relativePath===i.relativePath&&i.sourceStartLine<=o.endLine+1){o.endLine=Math.max(o.endLine,i.sourceEndLine),o.references.push(OS(i)),o.source=V(e,o.relativePath).slice(o.startLine,o.endLine+1).join(`
|
|
73
|
-
`);continue}r.push({relativePath:i.relativePath,startLine:i.sourceStartLine,endLine:i.sourceEndLine,source:i.source,references:[OS(i)]})}return r}function OS(e){return{line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort}}function R0(e){let t=e&&e.length>0?e:["definition","references"];return[...new Set(t)]}function BS(e,t,n){let r=[],i=new Set;for(let o of t){if(i.has(o.symbol))continue;i.add(o.symbol);let s=(o.file?U(e,o.file).find(c=>c.symbol===o.symbol):void 0)??Qe(e,o.symbol).match;if(!s)continue;let a=Og(e,s.relativePath,s.startLine,s.endLine,n);a&&r.push({...a,symbol:o.symbol,shortName:o.shortName,omittedLines:Math.max(0,s.endLine-a.endLine)})}return r}var GS=6;function jS(e,t,n){return`${e}\0${t}\0${n??t}`}function zS(e,t,n,r={}){let i=r.limit??GS;if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`next-anchor limit must be a positive safe integer; received ${i}`);let o=r.sourceAllowed??(()=>!0),s=new Map(t.nodes.map(E=>[E.id,E])),a=new Set(n.steps.map(E=>E.nodeId)),c=new Set(n.steps.flatMap(E=>{let w=xd(s.get(E.nodeId));return w?[w]:[]})),l=new Set;for(let E of n.steps)for(let w of E.behavior?.supportingDeclarations??[])c.add(w.symbol),l.add(jS(w.file,w.line,w.endLine));let u=E=>E.symbol!==null&&c.has(E.symbol)||l.has(jS(E.file,E.line,E.endLine)),d=new Map(n.steps.flatMap(E=>{if(!E.location)return[];let w=xd(s.get(E.nodeId));if(!w)return[];let I=U(e,E.location.file).find(k=>k.symbol===w);return I?[[E.id,I]]:[]})),m=new H(e).calleeMap([...d.values()],{additive:!1,semantic:!0}),p=[],f=new Set,g=new Set,h=0,b=0,S=0,y=0,x=0,v=0,C=0,R=0;for(let E of n.steps){if(!E.location||!E.behavior)continue;let w=E0(E,{db:e,topology:t,nodeById:s,returnedNodeIds:a,sourceAllowed:o,alternativeAlreadyReturned:u});p.push(...w.candidates),v+=w.upstreamCandidates,R+=w.runtimeCandidates,C+=w.resultCandidates;let I=I0(E,{db:e,topology:t,nodeById:s,returnedNodeIds:a,sourceAllowed:o,alternativeAlreadyReturned:u},f);p.push(...I);let k=w0(E,{db:e,topology:t,nodeById:s,returnedNodeIds:a,sourceAllowed:o,alternativeAlreadyReturned:u},{evidencedCallsiteKeys:f,consideredCandidateKeys:g,calleeMap:m,stepDefinition:d.get(E.id)});p.push(...k.candidates),h+=k.scannedBehaviorSteps,b+=k.visibleCallsites,S+=k.identityCandidateCallsites,y+=k.ambiguousCallsites,x+=k.unresolvedCallsites}return YS(e,p,n.steps,i,{scannedBehaviorSteps:h,visibleCallsites:b,graphEvidencedCallsites:f.size,identityCandidateCallsites:S,ambiguousCallsites:y,unresolvedCallsites:x,upstreamCandidates:v,resultCandidates:C,runtimeCandidates:R},r.selectionTerms)}function E0(e,t){let n=[],r=0,i=0,o=0;if(!e.location||!e.behavior)return{candidates:n,upstreamCandidates:r,resultCandidates:i,runtimeCandidates:o};let s=t.topology.edges.filter(c=>["call","runtime-boundary"].includes(c.kind)&&(c.fromNodeId===e.nodeId||c.toNodeId===e.nodeId)&&c.disposition!=="excluded"&&c.disposition!=="unsupported");for(let c of s){let l=c.toNodeId===e.nodeId,u=l?c.fromNodeId:c.toNodeId;if(t.returnedNodeIds.has(u))continue;let d=t.nodeById.get(u);if(!d?.location||!t.sourceAllowed(d.location.file))continue;let m=c.kind==="call"?Rd(t.db,d):wd(d);if(!m||t.alternativeAlreadyReturned(m))continue;let p=Ed(c,d.location.file)??d.location,f=V(t.db,p.file)[p.line]?.trim(),g=l?"upstream":"downstream",h=c.kind==="runtime-boundary"?l?"runtime-producer":"runtime-consumer":l?"caller":"callee",b=Id(c.evidence),S=Uo(d);n.push({anchor:{id:or(e.id,p.line,d.id),status:b,source:"graph-relation",direction:g,causalRole:h,relationKind:c.kind,fromStepId:e.id,fromLabel:e.label,callsite:{file:p.file,line:p.line,endLine:p.endLine??p.line,text:f||`${d.label} \u2192 ${e.label}`,signals:["call"],calleeLeaf:S},alternatives:[m],alternativeCount:1,evidence:c.evidence}}),l&&(r+=1),c.kind==="runtime-boundary"&&(o+=1)}let a=t.topology.edges.filter(c=>c.kind==="reference"&&c.fromNodeId===e.nodeId&&c.disposition!=="excluded"&&c.disposition!=="unsupported"&&!t.returnedNodeIds.has(c.toNodeId));for(let c of a){let l=t.nodeById.get(c.toNodeId);if(!l?.location||!t.sourceAllowed(l.location.file))continue;let u=Rd(t.db,l);if(!u||t.alternativeAlreadyReturned(u))continue;let d=Uo(l),m=Ed(c,e.location.file)?.line,p=e.behavior.lines.find(h=>(m===void 0||m>=h.line&&m<=h.endLine)&&h.text.includes(d));if(!p)continue;let f=WS(p.signals),g=Id(c.evidence);n.push({anchor:{id:or(e.id,p.line,l.id),status:g,source:"graph-relation",direction:"downstream",causalRole:f,relationKind:"reference",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:p.line,endLine:p.endLine,text:p.text,signals:p.signals,calleeLeaf:d},alternatives:[u],alternativeCount:1,evidence:c.evidence}}),f==="result-callback"&&(i+=1)}return{candidates:n,upstreamCandidates:r,resultCandidates:i,runtimeCandidates:o}}function I0(e,t,n){let r=[];if(!e.location)return r;let i=Rn(t.db,e.location.file,e.location.line,e.location.endLine??e.location.line),o=V(t.db,e.location.file),s=yn(t.db,e.location.file,e.location.line,e.location.endLine??e.location.line);for(let a of i.targets){if(!t.sourceAllowed(a.definition.relativePath))continue;let c=Br(e.location.file,a.sourceLine,a.calleeLeaf);if(n.has(c))continue;n.add(c);let l=Cd(s.get(a.sourceLine)),u={symbol:a.definition.symbol,label:a.definition.leaf,file:a.definition.relativePath,line:a.definition.startLine,endLine:a.definition.endLine};t.alternativeAlreadyReturned(u)||r.push({anchor:{id:or(e.id,a.sourceLine,a.definition.symbol),status:"exact",source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:a.sourceLine,endLine:a.sourceLine,text:o[a.sourceLine]?.trim()||`${a.calleeLeaf}()`,signals:l,calleeLeaf:a.calleeLeaf},alternatives:[u],alternativeCount:1,evidence:[{method:"scip-occurrence-callsite",strength:"exact",identity:a.definition.symbol,location:{file:e.location.file,line:a.sourceLine}}]}})}return r}function w0(e,t,n){let r={candidates:[],scannedBehaviorSteps:0,visibleCallsites:0,identityCandidateCallsites:0,ambiguousCallsites:0,unresolvedCallsites:0};if(!e.location||!e.behavior)return r;let i=e.behavior.lines.filter(f=>f.signals.includes("call"));if(i.length===0)return r;let o=[],s=0,a=0,c=0,l=(K(t.db,e.location.file)?.callSites??[]).filter(f=>i.some(g=>f.line>=g.line&&f.line<=g.endLine)),u=t.topology.edges.filter(f=>f.kind==="call"&&f.fromNodeId===e.nodeId&&f.disposition!=="excluded"&&f.disposition!=="unsupported"),d=new Map;for(let f of u){let g=t.nodeById.get(f.toNodeId);if(!g)continue;let h=Uo(g);d.set(h,(d.get(h)??0)+1)}let m=P0(t.db,n.stepDefinition?n.calleeMap.get(n.stepDefinition.symbolId)??[]:[]),p=D0(m);for(let f of m){if(!t.sourceAllowed(f.alternative.file)||t.alternativeAlreadyReturned(f.alternative))continue;let g=qe(f.alternative.label),h=US(l,i,g,f.row.callsiteLine,p.get(g)===1);if(!h)continue;let b=Ho(i,h.line,g);if(!b)continue;let S=Br(e.location.file,h.line,g);if(n.evidencedCallsiteKeys.has(S))continue;n.evidencedCallsiteKeys.add(S);let y=XS(f.row.source);o.push({anchor:{id:or(e.id,h.line,f.alternative.symbol??f.alternative.file),status:y,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:b.line,endLine:b.endLine,text:b.text,signals:b.signals,calleeLeaf:g},alternatives:[f.alternative],alternativeCount:1,evidence:[{method:f.row.source,strength:y,identity:f.row.symbol,location:{file:e.location.file,line:h.line}}]}})}for(let f of u){if(t.returnedNodeIds.has(f.toNodeId))continue;let g=t.nodeById.get(f.toNodeId);if(!g?.location||!t.sourceAllowed(g.location.file))continue;let h=Uo(g),b=f.evidence.find(R=>{let E=R.location;return E!==null&&E.file===e.location?.file&&E.line>=0})?.location?.line,S=US(l,i,h,b,d.get(h)===1);if(!S)continue;let y=Ho(i,S.line,h);if(!y)continue;let x=Br(e.location.file,S.line,h);if(n.evidencedCallsiteKeys.has(x))continue;n.evidencedCallsiteKeys.add(x);let v=wd(g);if(!v||t.alternativeAlreadyReturned(v))continue;let C=Id(f.evidence);o.push({anchor:{id:or(e.id,S.line,g.id),status:C,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:y.line,endLine:y.endLine,text:y.text,signals:y.signals,calleeLeaf:h},alternatives:[v],alternativeCount:1,evidence:f.evidence}})}for(let f of l){let g=Br(e.location.file,f.line,f.calleeLeaf);if(n.evidencedCallsiteKeys.has(g))continue;let h=Ho(i,f.line,f.calleeLeaf);if(!h)continue;let b=_t(e.location.file,zt(t.db).get(f.calleeLeaf)??[]).flatMap(v=>U(t.db,v.file).filter(C=>C.symbol===v.symbol&&C.isFunctionLike)).filter(v=>t.sourceAllowed(v.relativePath)&&!t.alternativeAlreadyReturned({symbol:v.symbol,label:v.leaf,file:v.relativePath,line:v.startLine,endLine:v.endLine})),S=ic(b.map(v=>({symbol:v.symbol,label:v.leaf??f.calleeLeaf,file:v.relativePath,line:v.startLine,endLine:v.endLine})));if(S.length===0){c+=1;continue}let y=`${e.id}\0${f.line}\0${f.calleeLeaf}`;if(n.consideredCandidateKeys.has(y))continue;n.consideredCandidateKeys.add(y);let x=S.length>1;x?a+=1:s+=1,o.push({anchor:{id:or(e.id,f.line,f.calleeLeaf),status:x?"ambiguous":"candidate",source:"leaf-identity-candidate",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:h.line,endLine:h.endLine,text:h.text,signals:h.signals,calleeLeaf:f.calleeLeaf},alternatives:S.slice(0,3),alternativeCount:S.length,evidence:[]}})}return{candidates:o,scannedBehaviorSteps:1,visibleCallsites:l.length,identityCandidateCallsites:s,ambiguousCallsites:a,unresolvedCallsites:c}}function KS(e,t,n){let r=new Map(t.nodes.map(i=>[i.id,i]));for(let i of n.steps)if(!(!i.behavior||!i.location))for(let o of t.edges){if(o.kind!=="reference"||o.fromNodeId!==i.nodeId||o.disposition==="excluded"||o.disposition==="unsupported")continue;let s=r.get(o.toNodeId);if(!s?.location||!Rd(e,s))continue;let a=Uo(s),c=Ed(o,i.location.file)?.line,l=i.behavior.lines.find(u=>(c===void 0||c>=u.line&&c<=u.endLine)&&u.text.includes(a));!l||WS(l.signals)!=="result-callback"||o.semantics?.some(({family:u,subtype:d})=>u==="control"&&d==="result-callback")||(o.semantics=[...o.semantics??[],{family:"control",subtype:"result-callback",attributes:{evidenceRole:"result-producing-callable-reference"}}])}}function WS(e){return e.includes("call")&&e.some(t=>["return","mutation","shape","spread","binding"].includes(t))?"result-callback":"callable-reference"}function VS(e,t,n={}){let r=n.limit??GS;if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`next-anchor limit must be a positive safe integer; received ${r}`);let i=n.sourceAllowed??(()=>!0),o=[],s=t.map((p,f)=>({id:p.id,nodeId:p.id,order:f,role:"anchor",kind:"source-construct",label:p.label,location:{file:p.file,line:p.startLine,endLine:p.endLine},behavior:null})),a=t.map(p=>({file:p.file,startLine:p.startLine,endLine:p.endLine})),c=0,l=0,u=0,d=0,m=0;for(let p of t){let f=V(e,p.file),h=(K(e,p.file)?.callSites??[]).filter(C=>C.line>=p.startLine&&C.line<=p.endLine);c+=h.length;let b=yn(e,p.file,p.startLine,p.endLine),S=Rn(e,p.file,p.startLine,p.endLine),y=new Set;for(let C of S.targets){if(!i(C.definition.relativePath)||a.some(I=>I.file===C.definition.relativePath&&I.startLine<=C.definition.startLine&&I.endLine>=C.definition.endLine))continue;let R=Br(p.file,C.sourceLine,C.calleeLeaf);y.add(R);let E=Cd(b.get(C.sourceLine)),w={symbol:C.definition.symbol,label:C.definition.leaf,file:C.definition.relativePath,line:C.definition.startLine,endLine:C.definition.endLine};o.push({anchor:{id:or(p.id,C.sourceLine,C.definition.symbol),status:"exact",source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:p.id,fromLabel:p.label,callsite:{file:p.file,line:C.sourceLine,endLine:C.sourceLine,text:f[C.sourceLine]?.trim()||`${C.calleeLeaf}()`,signals:E,calleeLeaf:C.calleeLeaf},alternatives:[w],alternativeCount:1,evidence:[{method:"scip-occurrence-callsite",strength:"exact",identity:C.definition.symbol,location:{file:p.file,line:C.sourceLine}}]}})}l+=S.resolvedCallsites;let x=nr(e,p.file,{ranges:[{startLine:p.startLine,endLine:p.endLine}]}),v=new Map;for(let C of x.targets){let R=h.find(I=>I.line===C.line)?.calleeLeaf??C.calleeLeaf,E=Br(p.file,C.line,R),w=v.get(E)??[];w.push(C),v.set(E,w)}for(let[C,R]of v){if(y.has(C))continue;y.add(C);let E=R.filter(L=>i(L.targetFile)&&!a.some(A=>A.file===L.targetFile&&A.startLine<=L.targetStartLine&&A.endLine>=L.targetEndLine));if(E.length===0)continue;let w=E[0],I=h.find(L=>L.line===w.line)?.calleeLeaf??w.calleeLeaf,k=Cd(b.get(w.line)),D=ic(E.map(L=>({symbol:L.targetSymbol??null,label:L.calleeLeaf,file:L.targetFile,line:L.targetStartLine,endLine:L.targetEndLine}))),F=E.some(L=>(L.resolutionAlternativeCount??0)>1)?"candidate":E.every(L=>L.strength==="exact")?"exact":"derived";o.push({anchor:{id:or(p.id,w.line,D.map(L=>`${L.file}:${L.line}`).join("|")),status:D.length>1?"ambiguous":F,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:p.id,fromLabel:p.label,callsite:{file:p.file,line:w.line,endLine:w.line,text:f[w.line]?.trim()||`${w.calleeLeaf}()`,signals:k,calleeLeaf:I},alternatives:D.slice(0,3),alternativeCount:D.length,evidence:E.map(L=>({method:L.resolution==="constructed-member-receiver"?"ast-constructed-member-callsite":L.resolution==="factory-callback-member"?"ast-factory-callback-callsite":L.resolution==="imported-service-object-member"?"ast-service-member-callsite":"ast-import-member-callsite",strength:F,identity:L.targetSymbol??`${L.targetFile}:${L.targetStartLine}-${L.targetEndLine}`,location:{file:p.file,line:w.line}}))}})}l+=v.size;for(let C of h){let R=Br(p.file,C.line,C.calleeLeaf);y.has(R)||(m+=1)}}return YS(e,o,s,r,{scannedBehaviorSteps:t.length,visibleCallsites:c,graphEvidencedCallsites:l,identityCandidateCallsites:u,ambiguousCallsites:d,unresolvedCallsites:m,upstreamCandidates:0,resultCandidates:0,runtimeCandidates:0})}function YS(e,t,n,r,i,o=[]){let s=M0(t).sort(JS),a=s.filter(f=>L0(e,f)).slice(0,r),c=new Set(a.map(f=>f.anchor.id)),l=s.filter(f=>!c.has(f.anchor.id)),u=a.map(f=>f.anchor),d=l.map(f=>f.anchor),m=ic(u.flatMap(f=>f.alternativeCount===1?f.alternatives:[])),p=ic(d.flatMap(f=>f.alternativeCount===1?f.alternatives:[]));return{anchors:u,withheldAnchors:d,candidateAnchors:s.length,omittedAnchors:Math.max(0,s.length-u.length),...i,inspectCommand:m.length===0?null:`scip-query inspect ${m.map(qS).join(" ")} --view behavior`,remainingInspectCommands:k0(p,8).map(f=>`scip-query inspect ${f.map(qS).join(" ")} --view behavior`)}}function JS(e,t){let n=e.anchor.alternatives[0],r=t.anchor.alternatives[0];return rc(e.anchor.status)-rc(t.anchor.status)||(e.anchor.direction??"").localeCompare(t.anchor.direction??"")||(e.anchor.relationKind??"").localeCompare(t.anchor.relationKind??"")||(e.anchor.causalRole??"").localeCompare(t.anchor.causalRole??"")||e.anchor.fromStepId.localeCompare(t.anchor.fromStepId)||e.anchor.callsite.file.localeCompare(t.anchor.callsite.file)||e.anchor.callsite.line-t.anchor.callsite.line||(n?.file??"").localeCompare(r?.file??"")||(n?.line??0)-(r?.line??0)||e.anchor.id.localeCompare(t.anchor.id)}function L0(e,t){if(t.anchor.alternativeCount!==1)return!0;let n=t.anchor.alternatives[0],r=n.endLine??n.line;return V(e,n.file).slice(n.line,r+1).join(`
|
|
74
|
-
`).length<=2e4}function Cd(e){return e?.includes("call")?[...e]:["call",...e??[]]}function P0(e,t){let n=new Map;for(let r of t){let i=U(e,r.file).find(a=>a.symbol===r.symbol&&a.isFunctionLike);if(!i)continue;let o={symbol:i.symbol,label:i.leaf,file:i.relativePath,line:i.startLine,endLine:i.endLine},s=n.get(i.symbol);!s||HS(r.source)>HS(s.row.source)?n.set(i.symbol,{row:{...r,...r.callsiteLine===void 0&&s?.row.callsiteLine!==void 0?{callsiteLine:s.row.callsiteLine}:{}},alternative:o}):s.row.callsiteLine===void 0&&r.callsiteLine!==void 0&&n.set(i.symbol,{...s,row:{...s.row,callsiteLine:r.callsiteLine}})}return[...n.values()]}function D0(e){let t=new Map;for(let n of e){let r=qe(n.alternative.label);t.set(r,(t.get(r)??0)+1)}return t}function XS(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function HS(e){return XS(e)==="exact"?2:1}function Ho(e,t,n){return e.find(r=>t>=r.line&&t<=r.endLine&&r.text.includes(n))??e.find(r=>t>=r.line&&t<=r.endLine)??null}function US(e,t,n,r,i){if(r!==void 0)return e.find(s=>s.line===r&&s.calleeLeaf===n&&Ho(t,s.line,n)!==null)??null;let o=e.filter(s=>s.calleeLeaf===n&&Ho(t,s.line,s.calleeLeaf)!==null);return i&&o.length===1?o[0]:null}function Uo(e){let t=e.attributes.leaf;if(typeof t=="string"&&t.length>0)return qe(t);let n=e.label.slice(e.label.lastIndexOf(":")+1);return qe(n)}function xd(e){if(e?.kind!=="symbol"||!e.id.startsWith("symbol:"))return null;try{return decodeURIComponent(e.id.slice(7))}catch{return null}}function wd(e){return e.location?{symbol:xd(e),label:e.label,file:e.location.file,line:e.location.line,endLine:e.location.endLine??null}:null}function Rd(e,t){let n=wd(t);return n?.symbol&&U(e,n.file).some(i=>i.symbol===n.symbol&&i.isFunctionLike)?n:null}function Ed(e,t){return e.evidence.find(n=>n.location?.file===t)?.location??e.evidence.find(n=>n.location!==null)?.location??null}function Id(e){let t={exact:5,derived:4,mixed:3,candidate:2,unknown:1};return e.reduce((n,r)=>t[r.strength]>t[n]?r.strength:n,"unknown")}function M0(e){let t=new Map;for(let n of e){let i=n.anchor.alternatives[0]?.symbol??`${n.anchor.callsite.file}:${n.anchor.callsite.line}:${n.anchor.callsite.calleeLeaf}`,o=t.get(i);(!o||T0(n,o)<0)&&t.set(i,n)}return[...t.values()]}function T0(e,t){return rc(e.anchor.status)-rc(t.anchor.status)||e.anchor.alternativeCount-t.anchor.alternativeCount||JS(e,t)}function rc(e){return{exact:0,derived:1,mixed:2,candidate:3,unknown:4,ambiguous:5}[e]}function ic(e){let t=new Map;for(let n of e)t.set(n.symbol??`${n.file}:${n.line}`,n);return[...t.values()].sort((n,r)=>n.file.localeCompare(r.file)||n.line-r.line||n.label.localeCompare(r.label))}function qS(e){return`--at ${A0(`${e.file}:${e.line+1}`)}`}function k0(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function A0(e){return`'${e.replaceAll("'","'\\''")}'`}function Br(e,t,n){return`${e}\0${t}\0${n}`}function or(e,t,n){return["next-anchor",e,String(t),n].map(encodeURIComponent).join(":")}var ov=6,F0=12,N0=48,_0=2e4,QS=12,$r=Number.MAX_SAFE_INTEGER,O0=["definition","callers","callees"],Md={search:12,"exact-source":24,definition:24,caller:8,callee:8,"production-reference":6,"test-reference":2,dependency:6,consumer:6};function B0(e,t){if(t.cursor)throw new Error("Inspect no longer accepts semantic packet cursors. Run the original inspect selectors again.");let n=j0(t),r=q0(e,n),i=r.candidates.sort((D,F)=>Ld(D,F));n.view==="behavior"&&K0(e,i),W0(e,i),n.view==="behavior"&&G0(e,i);let o=Hb(i.map(D=>Pd(D,n.view)),n.evidenceBudgets,(D,F)=>Ld(D.candidate,F.candidate)),{selected:s,omitted:a}=qa(o.selected,n.maxUnits,n.maxCharacters,(D,F)=>Ld(D.candidate,F.candidate),n.view==="source"),c=s.map(D=>D.candidate),l=[...o.omitted,...a].map(D=>D.candidate),u=c.map(nN),d=Zs(c.map(D=>D.kind==="source"?D.bindingClosure:void 0),c.filter(D=>D.kind==="source").map(D=>({relativePath:D.relativePath,startLine:D.startLine,endLine:D.endLine}))),m=u.reduce((D,F)=>D+(F.kind==="source"?oN(F.source):0),0),p=u.reduce((D,F)=>D+(F.kind==="source"?F.source.length:0),0),f=u.reduce((D,F)=>D+cv(F,n.view),0),g=u.filter(D=>D.kind==="source"&&(D.roles.includes("search")||D.roles.includes("location"))).map(rN),h=i.filter(D=>D.kind==="source"&&(D.roles.includes("search")||D.roles.includes("location"))).length,b=u.filter(D=>D.kind==="source"&&(D.roles.includes("search")||D.roles.includes("location"))).length,S=r.searches.map(D=>J0(D,i,c)),y=X0(l),x=r.locations.every(D=>D.matched)&&r.evidence.every(D=>D.kind==="matched")&&r.searches.every(D=>Z0(D.textCoverage))&&l.every(D=>!D.roles.some(F=>F==="location"||F==="definition")),v=S.reduce((D,F)=>D+F.omittedMatches,0),C=l.length===0&&v===0,R=C?void 0:av(n,!0),E=V0(n,l),w=$0(C,x,l.length+v,E,S,R),I=i.filter(D=>n.view==="behavior"&&D.kind==="source"&&D.roles.some(F=>F==="location"||F==="definition"||F==="search")).map(D=>({id:`inspect:${D.relativePath}:${D.startLine}-${D.endLine}`,label:D.ownerShort??`${D.relativePath}:${D.startLine+1}`,file:D.relativePath,startLine:D.startLine,endLine:D.endLine})),k=I.length>0?VS(e,I):void 0;return{searches:S,evidence:r.evidence,locations:r.locations,slices:g,candidateSlices:h,omittedSlices:h-b,maxSlices:h,maxTotalLines:m,units:u,candidateUnits:i.length,omittedUnits:l.length,maxUnits:n.maxUnits,maxCharacters:n.maxCharacters,returnedLines:m,returnedCharacters:p,returnedViewCharacters:f,view:n.view,omissionGroups:E,packetCoverage:{mode:C?"complete":"bounded",candidateUnits:i.length,returnedUnits:u.length,omittedUnits:l.length,omittedByRole:y,exactSelectorsComplete:x,maxUnits:n.maxUnits,maxCharacters:n.maxCharacters,channels:Q0(i,c,n.evidenceBudgets,n.view),...R?{expansionCommand:R}:{}},stoppingSummary:w,...k&&k.candidateAnchors>0?{causalFrontier:k}:{},bindingClosure:d,continuation:null}}function $0(e,t,n,r,i,o){let s=ct([...r.map(a=>a.drillCommand),...i.flatMap(a=>a.exactFollowup?[a.exactFollowup]:[]),...o?[o]:[]]);return e&&t?{queryStatus:"selection-complete",status:"stop-ready",openEvidence:0,guidance:"All evidence requested by this inspect query was materialized.",drillCommands:[]}:t?{queryStatus:"frontier-accounted",status:"relevance-check-required",openEvidence:n,guidance:"Withheld evidence is accounted for by recoverable groups; drill the groups relevant to the current decision.",drillCommands:s}:{queryStatus:"coverage-incomplete",status:"exact-evidence-withheld",openEvidence:n,guidance:"A requested identity, exact source unit, or current-text coverage requirement is unresolved; drill before relying on it.",drillCommands:s}}function j0(e){let t=ke(e.searches),n=ke(e.symbols),r=ke(e.locations),i=t.length+n.length+r.length;if(i===0)throw new Error("inspect requires at least one --search, --symbol, or --at selector.");if(i>24)throw new RangeError(`inspect accepts at most ${24} selectors; received ${i}.`);let o=e.evidence??{};if(e.unitLines!==void 0&&sr(e.unitLines,"unitLines"),e.totalLines!==void 0&&sr(e.totalLines,"totalLines"),e.sliceLimit!==void 0&&sr(e.sliceLimit,"sliceLimit"),e.maxCharacters!==void 0&&sr(e.maxCharacters,"maxCharacters"),e.maxUnits!==void 0&&sr(e.maxUnits,"maxUnits"),e.view!==void 0&&e.view!=="source"&&e.view!=="behavior")throw new Error(`Unknown inspect view: ${String(e.view)}. Use source or behavior.`);if(e.full&&(e.searchLimit!==void 0||e.maxUnits!==void 0||e.maxCharacters!==void 0||e.evidenceBudgets!==void 0))throw new Error("full inspect cannot be combined with searchLimit, maxUnits, maxCharacters, or evidenceBudgets.");let s=e.full??!1;return{searches:t,symbols:n,locations:r,...e.scope?.trim()?{scope:e.scope.trim()}:{},context:rv(e.context??ov,"context"),searchLimit:sr(e.searchLimit??(s?$r:F0),"searchLimit"),maxUnits:sr(s?$r:e.maxUnits??N0,"maxUnits"),maxCharacters:sr(s?$r:e.maxCharacters??_0,"maxCharacters"),evidenceBudgets:s?U0():H0(e.evidenceBudgets??Md),view:e.view??"source",evidence:{...o.parts?{parts:[...o.parts]}:n.length>0?{parts:[...O0]}:{},...o.referenceContext!==void 0?{referenceContext:rv(o.referenceContext,"referenceContext")}:{},relatedSourceLines:o.relatedSourceLines??60,...o.semantic!==void 0?{semantic:o.semantic}:{}}}}function H0(e){let t={...Md};for(let[n,r]of Object.entries(e)){if(!(n in t))throw new Error(`Unknown inspect evidence channel: ${n}.`);if(!Number.isSafeInteger(r)||(r??-1)<0)throw new RangeError(`Evidence budget ${n} must be a non-negative safe integer; received ${r}.`);t[n]=r}return t}function U0(){return Object.fromEntries(Object.keys(Md).map(e=>[e,$r]))}function q0(e,t){let n=[],r=0,i=Ga(e,t.searches,{scope:t.scope,context:0,limit:t.searchLimit,ranking:"structural"}).map((l,u)=>({pattern:t.searches[u],result:l,matches:l.matches})),o=Math.max(0,...i.map(l=>l.matches.length));for(let l=0;l<o;l+=1)for(let u of i){let d=u.matches[l];if(!d)continue;let m=Kn(e,d.relativePath,d.focusLine,$r,t.context);m&&Mi(e,n,m,"search",`search:${u.pattern}`,d.ownerSymbol,d.ownerShort,1,r++)}let s=i.map(({pattern:l,result:u})=>{let d=u.omittedMatches>0?sv(l,t.scope):void 0,m=u.fileCoverage??[],p=eN(l,m,t.scope);return{pattern:l,matchingLines:u.matchingLines,returnedMatches:u.matches.length,omittedMatches:u.omittedMatches,matchingFiles:m.length,returnedFiles:m.filter(f=>f.returnedMatches>0).length,omittedFiles:m.filter(f=>f.returnedMatches===0).length,candidateUnits:0,selectedUnits:0,omittedUnits:0,scopeHints:p.slice(0,QS),omittedScopeHints:Math.max(0,p.length-QS),textCoverage:u.textCoverage,...d?{exactFollowup:d}:{}}}),a=t.locations.map(l=>{let u=iN(l),d=u?ng(e,u.path):null,m=d?Kn(e,d,u.line-1,$r,t.context):null;return m&&Mi(e,n,m,"location",`at:${l}`,null,null,0,r++),{target:l,matched:m!==null}}),c=t.symbols.map(l=>vd(e,l,t.evidence));for(let l of c)if(l.kind==="matched"){if(l.definition){let u=Kn(e,l.definition.relativePath,l.definition.startLine,$r,t.context);u&&Mi(e,n,u,"definition",`definition:${l.shortName}`,l.symbol,l.shortName,0,r++)}for(let u of l.referenceWindows){let d=u.references[0];Mi(e,n,{...u,focusLine:d?.line??u.startLine,unitType:null,unitStartLine:u.startLine,unitEndLine:u.endLine,omittedLines:0},"reference",`reference:${l.shortName}`,d?.enclosingSymbol??null,d?.enclosingShort??null,q(u.relativePath)==="test"?5:4,r++,u.references.map(m=>m.line),l.symbol)}for(let u of l.callers)ZS(e,n,u,"caller",l,2,r++);for(let u of l.callees)ZS(e,n,u,"callee",l,3,r++);for(let u of l.dependencies)ev(e,n,"dependency",l.file,u.relativePath,l.symbol,t.context,6,r++);for(let u of l.consumers)ev(e,n,"consumer",u.relativePath,l.file,l.symbol,t.context,7,r++)}return{searches:s,evidence:c,locations:a,candidates:n}}function Ld(e,t){return e.priority-t.priority||t.roles.length-e.roles.length||t.reasons.length-e.reasons.length||xe(q(e.relativePath))-xe(q(t.relativePath))||e.sequence-t.sequence}function Pd(e,t){return{candidate:e,priority:e.priority,sequence:e.sequence,relativePath:e.relativePath,fileKind:q(e.relativePath),evidenceCharacters:cv(e,t),roles:e.roles,reasons:e.reasons,symbols:e.symbols,behaviorSignals:e.kind==="source"?e.behavior?.signals??[]:[],channel:Dd(e)}}function Dd(e){let t=e.roles;return t.includes("location")?"exact-source":t.includes("definition")?"definition":t.includes("caller")?"caller":t.includes("callee")?"callee":t.includes("reference")?q(e.relativePath)==="test"?"test-reference":"production-reference":t.includes("dependency")?"dependency":t.includes("consumer")?"consumer":"search"}function G0(e,t){let n=t.filter(i=>i.kind==="source"),r=no(e,{files:ct(n.map(i=>i.relativePath))});for(let i of n){i.behavior=mi(e,i.relativePath,i.startLine,i.endLine,i.focusLines)??void 0;let o=r.filter(a=>a.source.file===i.relativePath&&a.source.startLine<=i.endLine&&a.source.endLine>=i.startLine),s=o.filter(a=>!z0(a,o)).map(a=>({observationId:a.id,protocol:a.protocol,action:a.action,role:a.role,strength:a.strength,resolution:a.resolution,line:a.source.startLine,endLine:a.source.endLine,keyParts:a.keyParts.map(c=>({name:c.name,value:c.value,evidence:c.evidence})),derivation:{kind:a.derivation.kind,rule:a.derivation.rule,sourceSpans:a.derivation.sourceSpans.length}}));i.runtimeFacts=s.length>0?s:void 0}}function z0(e,t){if(e.strength!=="candidate"||e.protocol!=="http")return!1;let n=e.keyParts.find(i=>i.name==="path")?.value,r=e.keyParts.find(i=>i.name==="method")?.value;return n?t.some(i=>{if(i===e||i.action!==e.action||i.role!==e.role||i.source.startLine!==e.source.startLine||i.derivation.rule!=="http.mount-prefix")return!1;let o=i.keyParts.find(a=>a.name==="path")?.value,s=i.keyParts.find(a=>a.name==="method")?.value;return!!(o&&o!==n&&o.endsWith(n)&&(!r||r===s))}):!1}function K0(e,t){for(let n of t){if(n.kind!=="source")continue;let r=ot(e,n.relativePath,n.startLine,n.endLine,n.focusLines);r.startLine===n.startLine&&r.endLine===n.endLine||(n.startLine=r.startLine,n.endLine=r.endLine,n.source=V(e,n.relativePath).slice(r.startLine,r.endLine+1).join(`
|
|
75
|
-
`),n.unitStartLine=r.startLine,n.unitEndLine=r.endLine,n.omittedLines=0)}}function W0(e,t){for(let n of t)n.kind==="source"&&(n.bindingClosure=di(e,n.relativePath,n.startLine,n.endLine))}function V0(e,t){let n=new Map;for(let r of t){let i=oc(r.relativePath),o=Dd(r),s=[...r.roles].sort().join(","),a=r.kind==="path"?r.relationship:"",c=`${i}|${o}|${s}|${a}`,l=n.get(c)??[];l.push(r),n.set(c,l)}return[...n.entries()].map(([r,i])=>{let o=i[0],s=ct(i.flatMap(c=>[...c.roles])).sort(),a=ct(i.flatMap(c=>c.kind==="source"?c.behavior?.signals??[]:[])).sort();return{id:`g-${iv("sha256").update(r).digest("hex").slice(0,8)}`,scope:oc(o.relativePath),channel:Dd(o),roles:s,behaviorSignals:a,candidateUnits:i.length,sourceCharacters:i.reduce((c,l)=>c+(l.kind==="source"?l.source.length:0),0),anchors:i.map(c=>({relativePath:c.relativePath,line:c.kind==="source"?c.focusLine:0,ownerShort:c.kind==="source"?c.ownerShort:null,roles:[...c.roles],behaviorSignals:c.kind==="source"?[...c.behavior?.signals??[]]:[]})),drillCommand:Y0(e,i)}}).sort((r,i)=>i.candidateUnits-r.candidateUnits||i.sourceCharacters-r.sourceCharacters||r.scope.localeCompare(i.scope)||r.id.localeCompare(i.id))}function Y0(e,t){let n=ct(t.flatMap(o=>o.reasons.filter(s=>s.startsWith("search:")).map(s=>s.slice(7)))),r=oc(t[0].relativePath);if(n.length>0&&t.every(o=>o.kind==="source"&&o.roles.includes("search"))){let o=["scip-query inspect"];for(let s of n)o.push(`--search ${Tt(s)}`);return o.push(`--scope ${Tt(r)}`,"--full"),e.view==="behavior"&&o.push("--view behavior"),o.join(" ")}let i=t.filter(o=>o.kind==="source");if(i.length>0&&i.length<=24){let o=["scip-query inspect"];for(let s of i)o.push(`--at ${Tt(`${s.relativePath}:${s.focusLine+1}`)}`);return e.view==="behavior"&&o.push("--view behavior"),o.join(" ")}return t.length===1&&t[0].kind==="path"?t[0].exactFollowup:av(e,!0)}function J0(e,t,n){let r=`search:${e.pattern}`,i=t.filter(a=>a.reasons.includes(r)).length,o=new Set(n),s=t.filter(a=>a.reasons.includes(r)&&o.has(a)).length;return{...e,candidateUnits:i,selectedUnits:s,omittedUnits:i-s}}function X0(e){let t={};for(let n of e)for(let r of n.roles)t[r]=(t[r]??0)+1;return t}function Q0(e,t,n,r){let i=e.map(s=>Pd(s,r).channel),o=t.map(s=>Pd(s,r).channel);return Object.fromEntries(Object.keys(n).map(s=>{let a=i.filter(l=>l===s).length,c=o.filter(l=>l===s).length;return[s,{candidateUnits:a,returnedUnits:c,omittedUnits:a-c,maxUnits:n[s]}]}))}function Z0(e){return!!(e&&e.skippedUnreadablePaths.length===0&&e.skippedOversizedPaths.length===0)}function eN(e,t,n){let r=new Map;for(let i of t){let o=oc(i.relativePath),s=r.get(o)??{matchingLines:0,returnedMatches:0};s.matchingLines+=i.matchingLines,s.returnedMatches+=i.returnedMatches,r.set(o,s)}return[...r.entries()].map(([i,o])=>({scope:i,...o,exactFollowup:sv(e,i||n)})).sort((i,o)=>o.matchingLines-i.matchingLines||o.returnedMatches-i.returnedMatches||i.scope.localeCompare(o.scope))}function oc(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function sv(e,t){return`scip-query inspect --search ${Tt(e)}${t?` --scope ${Tt(t)}`:""} --full`}function av(e,t){let n=["scip-query inspect"];for(let r of e.searches)n.push(`--search ${Tt(r)}`);for(let r of e.symbols)n.push(`--symbol ${Tt(r)}`);for(let r of e.locations)n.push(`--at ${Tt(r)}`);return e.scope&&n.push(`--scope ${Tt(e.scope)}`),e.context!==ov&&n.push(`--context ${e.context}`),e.evidence.parts&&n.push(`--include ${Tt(e.evidence.parts.join(","))}`),t&&n.push("--full"),e.view==="behavior"&&n.push("--view behavior"),n.join(" ")}function ZS(e,t,n,r,i,o,s){Mi(e,t,{...n,unitType:null,unitStartLine:n.startLine,unitEndLine:n.endLine+n.omittedLines},r,`${r}:${i.shortName}`,n.symbol,n.shortName,o,s,[n.focusLine],i.symbol)}function ev(e,t,n,r,i,o,s,a,c){let l=`${r} -> ${i}`,u=ae(e,r).filter(h=>h.sourcePath===i),d=V(e,r),m=tN(d,u,i),p=m===null?null:la(e,r,m,Math.min(s,4));if(p){Mi(e,t,{...p,unitType:null,unitStartLine:p.startLine,unitEndLine:p.endLine,omittedLines:0},n,`${n}:${l}`,null,null,a,c,[p.focusLine],o);return}let f=`scip-query inspect --search ${Tt(lv(i))} --scope ${Tt(r)}`,g=t.find(h=>h.kind==="path"&&h.relativePath===r&&h.relationship===l);if(g){g.roles=ct([...g.roles,n]),g.reasons=ct([...g.reasons,`${n}:${l}`]),g.symbols=ct([...g.symbols,o]),g.priority=Math.min(g.priority,a);return}t.push({kind:"path",roles:[n],relativePath:r,relationship:l,reasons:[`${n}:${l}`],symbols:[o],exactFollowup:f,priority:a,sequence:c})}function tN(e,t,n){let r=ct(t.flatMap(c=>[c.importedName,c.localName??""]).filter(c=>c.length>1)),i=lv(n).replace(/\.[^.]+$/u,""),o=ct([...r,i]).filter(Boolean),s=/\b(?:from|import|include|require|use)\b/u,a=e.findIndex(c=>s.test(c)&&o.some(l=>c.includes(l)));return a>=0?a:null}function Mi(e,t,n,r,i,o,s,a,c,l=[n.focusLine],u){let d=t.find(m=>m.kind==="source"&&m.relativePath===n.relativePath&&m.startLine<=n.endLine&&n.startLine<=m.endLine);if(d){let m=Math.min(d.startLine,n.startLine),p=Math.max(d.endLine,n.endLine);d.startLine=m,d.endLine=p,d.source=V(e,n.relativePath).slice(m,p+1).join(`
|
|
76
|
-
`),d.focusLine=Math.min(d.focusLine,n.focusLine),d.focusLines=nv([...d.focusLines,...l]),d.unitStartLine=Math.min(d.unitStartLine,n.unitStartLine),d.unitEndLine=Math.max(d.unitEndLine,n.unitEndLine),d.omittedLines=Math.max(d.omittedLines,n.omittedLines),d.reasons=ct([...d.reasons,i]),d.roles=ct([...d.roles,r]),d.symbols=ct([...d.symbols,...u?[u]:[]]),!d.ownerSymbol&&o&&(d.ownerSymbol=o),!d.ownerShort&&s&&(d.ownerShort=s),d.priority=Math.min(d.priority,a);return}t.push({kind:"source",...n,reasons:[i],focusLines:nv(l),ownerSymbol:o,ownerShort:s,roles:[r],symbols:u?[u]:[],priority:a,sequence:c})}function nN(e){if(e.kind==="path"){let{priority:o,sequence:s,...a}=e;return{...a,id:tv(a)}}let{priority:t,sequence:n,bindingClosure:r,...i}=e;return{...i,id:tv(i),omittedCharacters:0}}function rN(e){let{kind:t,id:n,roles:r,symbols:i,omittedCharacters:o,behavior:s,runtimeFacts:a,...c}=e;return c}function tv(e){return iv("sha256").update(JSON.stringify(e)).digest("hex").slice(0,16)}function iN(e){let t=e.match(/^(.+\.\w+):(\d+)$/u);if(!t)return null;let n=Number(t[2]);return Number.isSafeInteger(n)&&n>0?{path:t[1],line:n}:null}function ct(e){return[...new Set(e)]}function nv(e){return ct(e).sort((t,n)=>t-n)}function oN(e){return e.length===0?0:e.split(`
|
|
77
|
-
`).length}function cv(e,t){if(e.kind==="path")return e.relationship.length+e.exactFollowup.length;let n="bindingClosure"in e?yg(e.bindingClosure):0,r=(e.runtimeFacts??[]).reduce((i,o)=>i+o.action.length+o.derivation.rule.length+o.keyParts.reduce((s,a)=>s+a.name.length+a.value.length+4,0)+24,0);return t!=="behavior"?e.source.length+n:e.behavior?e.behavior.lines.reduce((i,o)=>i+o.text.length+o.signals.join(",").length+12,0)+e.behavior.testCases.reduce((i,o)=>i+o.length+2,0)+r+n:e.source.length+n+r}function lv(e){return e.split("/").at(-1)??e}function Tt(e){return`'${e.replaceAll("'","'\\''")}'`}function sr(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new RangeError(`${t} must be a positive safe integer; received ${e}`);return e}function rv(e,t){if(!Number.isSafeInteger(e)||e<0)throw new RangeError(`${t} must be a non-negative safe integer; received ${e}`);return e}import{basename as sN}from"path";function aN(e,t){let n=t.className,r=Qe(e,n);return r.match?r.total>1?{kind:"ambiguous",query:n,total:r.total,candidates:[uv(r.match),...r.candidates]}:{kind:"matched",query:n,owner:lN(r.match),methods:cN(e,r.match)}:{kind:"missing",query:n,suggestions:js(e,n,5)}}function cN(e,t){let n=z(t.symbol),i=new H(e).definitionsForFile(t.relativePath).filter(c=>Xe(c.symbol)),o=i.filter(c=>c.parentTypeName===n||c.symbol.includes(n)),a=(o.length>0?o:uN(sN(t.relativePath))===n?i.filter(c=>c.symbol.includes("<invalid-global-code>")):[]).map(c=>({startLine:c.startLine,endLine:c.endLine,name:z(c.symbol)}));return se(t.relativePath)!=="clojure"?a:mN(a,dN(e,t))}function uv(e){return{symbol:e.symbol,shortName:T(e.symbol),relativePath:e.relativePath,startLine:e.startLine}}function lN(e){return{...uv(e),endLine:e.endLine}}function uN(e){return e.replace(/\.[^.]+$/,"")}function dN(e,t){let n=z(t.symbol);return n?(K(e,t.relativePath)?.clojureMembers??[]).filter(r=>r.ownerName===n).map(r=>({startLine:r.startLine,endLine:r.endLine,name:r.memberName})):[]}function mN(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.name}:${r.startLine}:${r.endLine}`,r);return[...n.values()].sort((r,i)=>r.startLine-i.startLine||r.endLine-i.endLine)}import{createHash as LB}from"crypto";var pne={exact:"Direct compiler or source evidence establishes this relationship within the provider's reported coverage.",derived:"A deterministic analysis computed this relationship from reported input facts; it was not directly observed.",candidate:"Ambiguous or heuristic evidence identifies a lead that requires exact graph or source confirmation.",mixed:"The relationship combines evidence of different strengths; its constituent methods and strengths remain disclosed.",unknown:"The relationship has no calibrated evidence strength and cannot support a stronger claim than its raw observation."},pN=[{id:"general-interprocedural-value-flow",families:["dataflow"],capability:"Whole-program definition-use flow through arbitrary calls and returns is unavailable.",consequence:"Missing dataflow edges cannot establish that a value never crosses an unmodeled call.",recoverWith:["value-flow","dependence-slice","inspect","code"]},{id:"heap-aliasing",families:["dataflow","state"],capability:"Heap points-to and cross-instance alias analysis are unavailable.",consequence:"Missing field or state edges cannot establish that two references never reach the same object.",recoverWith:["value-flow","dependence-slice","inspect","code"]},{id:"exceptional-flow",families:["execution","dataflow","temporal"],capability:"Interprocedural exception propagation and finally completion flow are unavailable.",consequence:"Normal-path reachability and ordering do not establish behavior after a throw or rejection.",recoverWith:["dependence-slice","inspect","code"]},{id:"reflection",families:["execution","runtime","identity","dependencies"],capability:"Reflective lookup, dynamic loading, and name-computed invocation are unavailable without exact evidence.",consequence:"Missing static edges cannot establish that a construct is unreachable through reflection.",recoverWith:["search","inspect","code"]},{id:"generated-dispatch",families:["execution","runtime","identity"],capability:"Dispatch tables or names created only by generated or unavailable source are unavailable.",consequence:"Missing dispatch edges cannot establish that no generated consumer exists.",recoverWith:["search","inspect","code"]},{id:"unsupported-framework-adapters",families:["runtime","dataflow","state","temporal"],capability:"Framework runtime crossings without a registered source adapter are unavailable.",consequence:"Missing boundary edges cannot establish that no producer, consumer, state effect, or ordering exists.",recoverWith:["search","inspect","code"]}];function fN(e){let t=new Set(e);return pN.filter(n=>n.families.some(r=>t.has(r)))}function dv(e){return fN(e).map(t=>`[${t.id}] ${t.capability} ${t.consequence} Recover selected paths with: ${t.recoverWith.map(n=>`scip-query ${n}`).join(", ")}.`)}var gN=["incoming","outgoing","both"];function fe(e,t,n,r={}){return{family:e,subtype:t,...r.match?{match:r.match}:{},directions:gN,evidenceStrengths:r.strengths??["exact","derived","mixed"],supportCeiling:r.supportCeiling??"partial",establishes:n,nonClaims:r.nonClaims??[],recoverWith:r.recoverWith??["inspect","code"]}}var hN=["predicate-consequence","predicate-alternative","predicate-fallthrough","predicate-case","predicate-default","predicate-return","predicate-throw","loop-iteration","loop-exit","exception-handler","finally-cleanup","handler-return","handler-throw"],yN=["captured-value-to-state","constant-to-state","expression-to-state","property-to-state","return-to-state","value-to-state"],bN=["await-completion-before","awaits-completion","inside-lock-scope","lexical-successor"],SN=[{id:"indexed-program-identity",label:"SCIP/compiler identity and source ownership",requirements:["indexed-graph"],relations:[fe("execution","call","The source construct may call the resolved target.",{strengths:["exact","derived","candidate","mixed"],nonClaims:["Static may-call reachability does not prove that an invocation occurred at runtime."],recoverWith:["call-graph","inspect","code"]}),fe("execution","result-callback","The referenced callable can produce the result consumed by this path.",{nonClaims:["A callback relationship does not prove invocation order or runtime selection."],recoverWith:["call-graph","inspect","code"]}),fe("contract","uses-contract-symbol","The source construct refers to the identified contract symbol.",{supportCeiling:"exact",nonClaims:["Contract identity does not prove runtime invocation or behavioral conformance."],recoverWith:["hierarchy","inspect","code"]}),fe("identity","references","The occurrence resolves to the identified compiler-owned symbol.",{supportCeiling:"exact",nonClaims:["A reference does not establish execution or value transfer."],recoverWith:["refs","trace","inspect"]}),fe("ownership","contains","The owner contains the identified program construct.",{supportCeiling:"exact",nonClaims:["Structural containment does not establish runtime lifetime or sharing scope."],recoverWith:["outline","inspect"]}),fe("ownership","contains-","The owner contains the identified program construct.",{match:"prefix",supportCeiling:"exact",nonClaims:["Structural containment does not establish runtime lifetime or sharing scope."],recoverWith:["outline","inspect"]}),fe("ownership","owns-","The owner owns the identified source or runtime observation.",{match:"prefix",supportCeiling:"exact",nonClaims:["Observation ownership does not establish singleton lifetime or exclusive ownership."],recoverWith:["inspect","code"]}),fe("dependencies","imports","The source file or module statically imports the indexed target.",{nonClaims:["An import does not establish that imported code executes."],recoverWith:["imports","deps","code"]}),fe("dependencies","imports-external","The source region statically imports an external package.",{nonClaims:["An external import does not establish which package behavior executes."],recoverWith:["imports","code"]})]},{id:"runtime-boundary-join",label:"source-grounded runtime-boundary joins",requirements:["indexed-graph","source-facts"],relations:[fe("runtime","runtime-handoff","A producer and consumer share a source-grounded runtime rendezvous.",{strengths:["exact","derived","candidate","mixed"],nonClaims:["A candidate or unresolved join does not prove a runtime handoff."],recoverWith:["evidence","inspect","code"]}),fe("runtime","discriminator-dispatch","A serialized discriminator selects the reported consumer.",{strengths:["exact","derived","mixed"],nonClaims:["The dispatch edge does not prove delivery, retry, or successful handling."],recoverWith:["evidence","inspect","code"]}),fe("dataflow","serialized-discriminator-transfer","The producer serializes the discriminator consumed by dispatch.",{strengths:["exact","derived","mixed"],nonClaims:["This edge does not establish the flow of every payload field."],recoverWith:["value-flow","inspect","code"]}),fe("temporal","enqueue-before-consume","The reported enqueue precedes a possible consume through the queue.",{strengths:["exact","derived","mixed"],nonClaims:["Queue order does not establish delivery time, uniqueness, retry count, or durability."],recoverWith:["evidence","inspect","code"]})]},{id:"parser-control-dependence",label:"parser-proved intraprocedural control dependence",requirements:["indexed-graph","source-facts"],relations:[...hN.map(e=>fe("execution",e,"The outcome is control-dependent on the reported predicate or handler.",{strengths:["exact"],nonClaims:["Local control dependence does not establish that the containing function executes."],recoverWith:["dependence-slice","inspect","code"]})),fe("execution","returns","The selected construct contains the reported return terminal.",{strengths:["exact"],nonClaims:["A local return terminal does not establish that the containing callable executes."],recoverWith:["inspect","code"]}),fe("execution","throws","The selected construct contains the reported throw terminal.",{strengths:["exact"],nonClaims:["A local throw terminal does not establish propagation, handling, or callable execution."],recoverWith:["inspect","code"]})]},{id:"bounded-static-value-flow",label:"compiler callsites and bounded static value evaluation",requirements:["indexed-graph","source-facts"],relations:["argument-to-parameter","constant-to-parameter","property-to-parameter","return-to-parameter","return-to-call-result"].map(e=>fe("dataflow",e,"The reported value may reach the target through the evidenced callsite transfer.",{strengths:["exact","derived","mixed"],nonClaims:["This provider does not establish general local definition-use, alias, field, or heap flow."],recoverWith:["value-flow","dependence-slice","inspect","code"]}))},{id:"typescript-local-dependence",label:"TypeScript compiler identities, control-flow graph, and reaching definitions",requirements:["typescript-semantic"],relations:[fe("dataflow","definition-to-use","The definition reaches the reported read on a feasible local control-flow path.",{strengths:["exact"],nonClaims:["Local reaching definitions do not establish heap aliasing, exceptional flow, or the runtime order of closure invocation."],recoverWith:["value-flow","dependence-slice","inspect","code"]}),fe("dataflow","value-to-definition","The reported right-hand-side read supplies the assigned local definition.",{strengths:["exact"],nonClaims:["A local assignment edge does not establish field or heap points-to flow."],recoverWith:["value-flow","dependence-slice","inspect","code"]}),fe("dataflow","closure-capture","The nested callable reads the reported binding from an enclosing callable.",{strengths:["candidate"],supportCeiling:"candidate",nonClaims:["Closure capture does not establish whether or when the nested callable executes."],recoverWith:["call-graph","inspect","code"]}),fe("dataflow","field-definition-to-use","The reported same-owner field definition can reach the field read.",{strengths:["exact","candidate"],nonClaims:["Field-name identity does not establish whole-program heap aliasing or cross-instance flow."],recoverWith:["value-flow","dependence-slice","inspect","code"]}),fe("execution","control-dependence","Execution of the reported statement depends on the outcome of the predicate.",{strengths:["exact"],nonClaims:["Intraprocedural control dependence does not establish that the containing callable executes."],recoverWith:["dependence-slice","inspect","code"]})]},{id:"parser-state-temporal",label:"parser-proved local state and temporal facts",requirements:["indexed-graph","source-facts"],relations:[...yN.map(e=>fe("dataflow",e,"The reported source value is assigned into the identified state resource.",{strengths:["exact"],nonClaims:["The edge does not establish alias, heap, or later read flow."],recoverWith:["value-flow","inspect","code"]})),...["writes-resource","deletes-resource","reads-resource","enqueues-resource","consumes-resource"].map(e=>fe("state",e,"The reported construct performs the named operation on the identified resource.",{strengths:["exact"],nonClaims:["A state operation does not establish transactionality, durability, or exclusive ownership."],recoverWith:["evidence","inspect","code"]})),...bN.map(e=>fe("temporal",e,"The reported source constructs have the named local ordering relationship.",{strengths:["exact"],nonClaims:["Local source order does not establish cross-process happens-before or durable completion."],recoverWith:["evidence","inspect","code"]}))]}];function sc(e,t){let n=SN.flatMap(r=>r.relations.filter(i=>i.family===e&&(i.match==="prefix"?t.startsWith(i.subtype):t===i.subtype)).map(i=>({provider:r,relation:i})));if(n.length>1)throw new Error(`Ambiguous graph relation provider for ${e}/${t}: ${n.map(r=>r.provider.id).join(", ")}`);return n[0]??null}var Bt=["execution","runtime","dataflow","state","temporal","contract","identity","ownership","dependencies"];function _e(e,t){let n=new Map;for(let r of e){let i=t(r),o=n.get(i)??[];o.push(r),n.set(i,o)}return n}function Ti(e){return e.includes("symbol-anchor")?0:e.includes("literal-owner")?1:e.some(t=>t.startsWith("boundary-import:"))?2:e.includes("reference-owner")?3:4}function mv(e,t){return Ti(e.origins)-Ti(t.origins)||e.depth-t.depth||e.startLine-t.startLine||e.shortName.localeCompare(t.shortName)}var pv=["call","contract-symbol","import","reference","runtime-boundary"],vN={call:[{family:"control",subtype:"call"}],"contract-symbol":[{family:"contract",subtype:"uses-contract-symbol"}],import:[{family:"identity",subtype:"imports"}],reference:[{family:"identity",subtype:"references"}]},CN={"structural-membership":[{family:"identity",subtype:"contains"}],"boundary-observation":[{family:"identity",subtype:"owns-runtime-observation"}],"external-import":[{family:"identity",subtype:"imports-external"}]};function fv(e){if(e.kind!=="runtime-boundary")return gv(vN[e.kind]);let t=e.fromBoundaryParticipant?.protocol??e.toBoundaryParticipant?.protocol,n={crossesRuntimeBoundary:!0,...t?{protocol:t}:{},...e.runtimeBoundaryKey?{runtimeKey:e.runtimeBoundaryKey}:{}},r=[{family:"control",subtype:"runtime-handoff",context:n}];return e.evidence==="runtime-boundary:carrier.discriminator"&&(r.push({family:"control",subtype:"discriminator-dispatch",context:{...n},attributes:{joinRule:"carrier.discriminator",...e.fromBoundaryParticipant?.action?{producerAction:e.fromBoundaryParticipant.action}:{},...e.toBoundaryParticipant?.action?{consumerAction:e.toBoundaryParticipant.action}:{}}}),r.push({family:"data",subtype:"serialized-discriminator-transfer",context:{...n},attributes:{joinRule:"carrier.discriminator"}})),e.evidence==="runtime-boundary:queue.address"&&e.fromBoundaryParticipant?.action==="queue.send"&&e.toBoundaryParticipant?.action==="queue.consume"&&r.push({family:"temporal",subtype:"enqueue-before-consume",context:{...n},attributes:{producerAction:e.fromBoundaryParticipant.action,consumerAction:e.toBoundaryParticipant.action,retryPolicy:"unknown"}}),r}function ac(e){return gv(CN[e])}function gv(e){return e.map(t=>({...t,...t.context?{context:{...t.context}}:{},...t.attributes?{attributes:{...t.attributes}}:{}}))}import{join as WN}from"path";import{createRequire as xN}from"module";import{resolve as Go}from"path";var RN=xN(import.meta.url),qo;function yv(e,t,n){let r=EN();if(!r)return Td("The TypeScript compiler runtime is unavailable.");let i=IN(r,e,t),o=i.getSourceFile(Go(t))??i.getSourceFile(t);if(!o)return Td(`The TypeScript compiler did not materialize ${t}.`);let s={ts:r,sourceFile:o,checker:i.getTypeChecker(),points:new Map,edges:new Map,unsupported:new Set,nextCfgId:0},a=LN(r,o,n);if(a.length===0)return Td("No function-like construct intersects the selected source range.");let c=new Map(a.map(d=>[d,PN(o,d)])),l=a.map(d=>MN(s,d,DN(r,d,c),c.get(d)));for(let d of l)TN(s,d),NN(s,d),BN(s,d);jN(s,l);let u=[...s.unsupported].sort();return{points:[...s.points.values()].map(({node:d,...m})=>m).sort(KN),edges:[...s.edges.values()].sort((d,m)=>d.id.localeCompare(m.id)),coverage:{status:u.length===0?"complete":"partial",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:u}}}function EN(){if(qo!==void 0)return qo;try{qo=RN("typescript")}catch{qo=Ws()?.ts??null}return qo}function IN(e,t,n){let r=Go(n),i={target:e.ScriptTarget.ESNext,module:e.ModuleKind.NodeNext,moduleResolution:e.ModuleResolutionKind.NodeNext,skipLibCheck:!0,noResolve:!0},o=e.createSourceFile(r,t,i.target,!0,wN(e,r)),s=e.createCompilerHost(i,!0),a=s.getSourceFile.bind(s),c=s.readFile.bind(s),l=s.fileExists.bind(s);return s.getSourceFile=(u,d,m,p)=>Go(u)===r?o:a(u,d,m,p),s.readFile=u=>Go(u)===r?t:c(u),s.fileExists=u=>Go(u)===r||l(u),e.createProgram([r],i,s)}function wN(e,t){return/\.tsx$/iu.test(t)?e.ScriptKind.TSX:/\.[cm]?js$/iu.test(t)?e.ScriptKind.JS:/\.jsx$/iu.test(t)?e.ScriptKind.JSX:e.ScriptKind.TS}function LN(e,t,n){let r=[],i=o=>{if(bv(e,o)){let s=t.getLineAndCharacterOfPosition(o.getStart(t)).line,a=t.getLineAndCharacterOfPosition(o.getEnd()).line;(!n||s<=n.endLine&&a>=n.startLine)&&r.push(o)}o.forEachChild(i)};return t.forEachChild(i),r.sort((o,s)=>o.getStart(t)-s.getStart(t))}function bv(e,t){return e.isFunctionLike(t)&&"body"in t&&t.body!==void 0}function PN(e,t){return`callable:${encodeURIComponent(e.fileName)}:${t.getStart(e)}:${t.getEnd()}`}function DN(e,t,n){for(let r=t.parent;r;r=r.parent)if(bv(e,r)&&n.has(r))return n.get(r);return null}function MN(e,t,n,r){let i=new Map,o=ze(e,i,"exit",null),s=t.body,a=o.id;if(s&&e.ts.isBlock(s))a=kd(e,i,[...s.statements],o.id,{breakTarget:null,continueTarget:null});else if(s){let l=ze(e,i,"statement",s);ve(i,l.id,o.id),a=l.id}let c=ze(e,i,"entry",t);return ve(i,c.id,a),{id:r,node:t,parentId:n,cfg:i,entryId:c.id,exitId:o.id}}function kd(e,t,n,r,i){let o=r;for(let s=n.length-1;s>=0;s-=1)o=jr(e,t,n[s],o,i);return o}function jr(e,t,n,r,i){let o=e.ts;if(o.isBlock(n))return kd(e,t,[...n.statements],r,i);if(o.isIfStatement(n)){let a=ze(e,t,"predicate",n.expression),c=jr(e,t,n.thenStatement,r,i),l=n.elseStatement?jr(e,t,n.elseStatement,r,i):r;return ve(t,a.id,c),ve(t,a.id,l),a.id}if(o.isWhileStatement(n)){let a=ze(e,t,"predicate",n.expression),c=jr(e,t,n.statement,a.id,{breakTarget:r,continueTarget:a.id});return ve(t,a.id,c),ve(t,a.id,r),a.id}if(o.isDoStatement(n)){let a=ze(e,t,"predicate",n.expression),c=jr(e,t,n.statement,a.id,{breakTarget:r,continueTarget:a.id});return ve(t,a.id,c),ve(t,a.id,r),c}if(o.isForStatement(n)){let a=ze(e,t,"predicate",n.condition??n),c=n.incrementor?ze(e,t,"statement",n.incrementor):null;c&&ve(t,c.id,a.id);let l=c?.id??a.id,u=jr(e,t,n.statement,l,{breakTarget:r,continueTarget:l});if(ve(t,a.id,u),n.condition&&ve(t,a.id,r),!n.initializer)return a.id;let d=ze(e,t,"statement",n.initializer);return ve(t,d.id,a.id),d.id}if(o.isForInStatement(n)||o.isForOfStatement(n)){e.unsupported.add("for-in/for-of iterator assignment is conservatively represented without iterable element flow.");let a=ze(e,t,"predicate",n.expression),c=ze(e,t,"statement",n.initializer),l=jr(e,t,n.statement,a.id,{breakTarget:r,continueTarget:a.id});return ve(t,a.id,c.id),ve(t,a.id,r),ve(t,c.id,l),a.id}if(o.isSwitchStatement(n)){e.unsupported.add("switch fallthrough is represented conservatively; discriminant-to-case value refinement is unsupported.");let a=ze(e,t,"predicate",n.expression),c=r,l=[];for(let u=n.caseBlock.clauses.length-1;u>=0;u-=1){let d=n.caseBlock.clauses[u];c=kd(e,t,[...d.statements],c,{...i,breakTarget:r}),l.push(c)}for(let u of l)ve(t,a.id,u);return ve(t,a.id,r),a.id}if(o.isReturnStatement(n)||o.isThrowStatement(n)){let a=ze(e,t,"statement",n),c=[...t.values()].find(l=>l.kind==="exit");return ve(t,a.id,c.id),a.id}if(o.isBreakStatement(n)){let a=ze(e,t,"statement",n);return i.breakTarget||e.unsupported.add("A break statement could not be attached to a structured target."),ve(t,a.id,i.breakTarget??r),a.id}if(o.isContinueStatement(n)){let a=ze(e,t,"statement",n);return i.continueTarget||e.unsupported.add("A continue statement could not be attached to a structured target."),ve(t,a.id,i.continueTarget??r),a.id}if(o.isTryStatement(n)){e.unsupported.add("Exceptional control-flow and finally completion are not included in the local compiler CFG.");let a=ze(e,t,"statement",n);return a.invalidatesAllDefinitions=!0,ve(t,a.id,r),a.id}let s=ze(e,t,"statement",n);return ve(t,s.id,r),s.id}function ze(e,t,n,r){let i={id:`cfg:${e.nextCfgId++}`,kind:n,ast:r,successors:new Set,predecessors:new Set,definitions:[],uses:[],displayPoint:null,invalidatesAllDefinitions:!1};return t.set(i.id,i),i}function ve(e,t,n){e.get(t).successors.add(n),e.get(n).predecessors.add(t)}function TN(e,t){let n=t.cfg.get(t.entryId);for(let r of t.node.parameters){let i=Hr(e,r.name);if(!i){e.unsupported.add("Destructured parameter definition-use is not implemented.");continue}n.definitions.push({point:Ur(e,i.node,"parameter-definition",i.symbolKey,i.name,t.id),rhsUseIds:[]})}for(let r of t.cfg.values())!r.ast||r.kind==="entry"||r.kind==="exit"||(r.kind==="predicate"&&(r.displayPoint=Ur(e,r.ast,"predicate",null,"predicate",t.id)),kN(e,t,r,r.ast),!r.displayPoint&&r.definitions.length===0&&r.uses.length===0&&(r.displayPoint=Ur(e,r.ast,"statement",null,UN(e,r.ast),t.id)))}function kN(e,t,n,r){let i=e.ts;if(i.isTryStatement(r))return;let o=s=>{if(!(s!==r&&i.isFunctionLike(s))){if(i.isVariableDeclaration(s)){let a=s.initializer?cc(e,t.id,s.initializer,n):[];n.uses.push(...a);let c=Hr(e,s.name);c?n.definitions.push({point:Ur(e,c.node,"definition",c.symbolKey,c.name,t.id),rhsUseIds:a.map(l=>l.point.id)}):(n.invalidatesAllDefinitions=!0,e.unsupported.add("Destructured variable reaching definitions are not implemented."));return}if(i.isBinaryExpression(s)&&Cv(i,s.operatorToken.kind)){let a=cc(e,t.id,s.right,n);s.operatorToken.kind!==i.SyntaxKind.EqualsToken&&a.push(...cc(e,t.id,s.left,n)),n.uses.push(...a);let c=Hr(e,s.left);c?n.definitions.push({point:Ur(e,c.node,"definition",c.symbolKey,c.name,t.id),rhsUseIds:a.map(l=>l.point.id)}):(n.invalidatesAllDefinitions=!0,e.unsupported.add("Dynamic or destructured assignment targets are not included in reaching definitions."));return}if((i.isPrefixUnaryExpression(s)||i.isPostfixUnaryExpression(s))&&(s.operator===i.SyntaxKind.PlusPlusToken||s.operator===i.SyntaxKind.MinusMinusToken)){let a=cc(e,t.id,s.operand,n);n.uses.push(...a);let c=Hr(e,s.operand);c&&n.definitions.push({point:Ur(e,c.node,"definition",c.symbolKey,c.name,t.id),rhsUseIds:a.map(l=>l.point.id)});return}if(!(i.isFunctionDeclaration(s)||i.isClassDeclaration(s)||i.isInterfaceDeclaration(s))){if(Sv(e,s)){let a=vv(e,t.id,s);a&&n.uses.push(a),i.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}}};o(r),n.uses=xv(n.uses)}function cc(e,t,n,r){let i=[],o=s=>{if(!e.ts.isFunctionLike(s)){if(e.ts.isBinaryExpression(s)&&Cv(e.ts,s.operatorToken.kind)){r.invalidatesAllDefinitions=!0,e.unsupported.add("Nested assignment expressions are not included in ordered local definition-use flow."),s.operatorToken.kind!==e.ts.SyntaxKind.EqualsToken&&o(s.left),o(s.right);return}if(Sv(e,s)){let a=vv(e,t,s);a&&i.push(a),e.ts.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}};return o(n),xv(i)}function Sv(e,t){if(e.ts.isPropertyAccessExpression(t))return!0;if(!e.ts.isIdentifier(t))return!1;let n=t.parent;return!(e.ts.isPropertyAccessExpression(n)&&n.name===t||"name"in n&&n.name===t&&AN(e.ts,n)||e.ts.isPropertyAssignment(n)&&n.name===t||e.ts.isBindingElement(n)&&n.propertyName===t||e.ts.isLabeledStatement(n)||e.ts.isBreakOrContinueStatement(n)||FN(e.ts,t))}function AN(e,t){return e.isVariableDeclaration(t)||e.isParameter(t)||e.isFunctionDeclaration(t)||e.isFunctionExpression(t)||e.isClassDeclaration(t)||e.isMethodDeclaration(t)||e.isPropertyDeclaration(t)||e.isInterfaceDeclaration(t)||e.isTypeAliasDeclaration(t)||e.isImportSpecifier(t)||e.isImportClause(t)||e.isNamespaceImport(t)}function FN(e,t){for(let n=t.parent;n;n=n.parent){if(e.isExpression(n)||e.isStatement(n)||e.isSourceFile(n))return!1;if(e.isTypeNode(n))return!0}return!1}function vv(e,t,n){let r=Hr(e,n);return r?{point:Ur(e,r.node,"use",r.symbolKey,r.name,t),property:e.ts.isPropertyAccessExpression(n)}:null}function Hr(e,t){let n=e.ts;if(n.isIdentifier(t)){let r=hv(e,t);return r?{node:t,symbolKey:r,name:t.text}:null}if(n.isPropertyAccessExpression(t)){let r=hv(e,t.name);return r?{node:t,symbolKey:r,name:t.getText(e.sourceFile)}:null}return n.isParenthesizedExpression(t)||n.isAsExpression(t)||n.isTypeAssertionExpression(t)||n.isNonNullExpression(t)?Hr(e,t.expression):((n.isArrayLiteralExpression(t)||n.isObjectLiteralExpression(t))&&e.unsupported.add("Heap aggregate identity and destructured assignment are not included in local points-to flow."),null)}function hv(e,t){let n=e.checker.getSymbolAtLocation(t);if(!n)return null;if((n.flags&e.ts.SymbolFlags.Alias)!==0)try{n=e.checker.getAliasedSymbol(n)}catch{}let r=n.valueDeclaration??n.declarations?.[0];return r?`symbol:${encodeURIComponent(r.getSourceFile().fileName)}:${r.getStart()}:${n.getName()}`:`symbol:${n.getName()}`}function Ur(e,t,n,r,i,o){let s=t.getStart(e.sourceFile),a=t.getEnd(),c=e.sourceFile.getLineAndCharacterOfPosition(s),l=`flow-point:${encodeURIComponent(e.sourceFile.fileName)}:${s}:${a}:${n}:${encodeURIComponent(r??i)}`,u=e.points.get(l);if(u)return u;let d={id:l,kind:n,name:i,symbolKey:r,callableId:o,start:s,end:a,line:c.line,column:c.character,node:t};return e.points.set(l,d),d}function NN(e,t){let n=[...t.cfg.values()].flatMap(c=>c.definitions),r=new Map(n.map(c=>[c.point.id,c])),i=_N(n),o=new Map,s=new Map;for(let c of t.cfg.values())o.set(c.id,new Set),s.set(c.id,new Set);let a=!0;for(;a;){a=!1;for(let c of t.cfg.values()){let l=GN([...c.predecessors].map(m=>s.get(m))),u=new Set(l);c.invalidatesAllDefinitions&&u.clear();let d=ON(c.definitions);for(let m of d){for(let p of i.get(m.point.symbolKey)??[])u.delete(p.point.id);u.add(m.point.id)}Ad(o.get(c.id),l)||(o.set(c.id,l),a=!0),Ad(s.get(c.id),u)||(s.set(c.id,u),a=!0)}}for(let c of t.cfg.values()){let l=o.get(c.id);for(let u of c.uses){let d=c.definitions.filter(p=>p.point.symbolKey===u.point.symbolKey&&p.point.start<u.point.start&&!p.rhsUseIds.includes(u.point.id)).sort((p,f)=>f.point.start-p.point.start)[0],m=d?[d.point.id]:l;for(let p of m){let f=r.get(p);f.point.symbolKey===u.point.symbolKey&&zo(e,"reaching-definition",f.point.id,u.point.id,"exact","A CFG path reaches this use without an intervening definition.")}}for(let u of c.definitions)for(let d of u.rhsUseIds)zo(e,"value-source",d,u.point.id,"exact","This right-hand-side use supplies the new definition.")}}function _N(e){let t=new Map;for(let n of e){if(!n.point.symbolKey)continue;let r=t.get(n.point.symbolKey)??[];r.push(n),t.set(n.point.symbolKey,r)}return t}function ON(e){let t=new Map;for(let n of e)n.point.symbolKey&&t.set(n.point.symbolKey,n);return[...t.values()]}function BN(e,t){let n=$N(t);for(let r of t.cfg.values()){if(r.successors.size<2||!r.displayPoint)continue;let i=n.get(r.id);for(let o of r.successors)for(let s of n.get(o)??[]){if(i.has(s)||s===t.exitId)continue;let a=t.cfg.get(s),c=[...a.definitions.map(l=>l.point),...a.uses.map(l=>l.point),...a.displayPoint?[a.displayPoint]:[]];for(let l of qN(c))zo(e,"control-dependence",r.displayPoint.id,l.id,"exact","The target postdominates a branch successor but does not postdominate the predicate.")}}}function $N(e){let t=[...e.cfg.keys()],n=new Set(t),r=new Map;for(let o of t)r.set(o,o===e.exitId?new Set([o]):new Set(n));let i=!0;for(;i;){i=!1;for(let o of e.cfg.values()){if(o.id===e.exitId)continue;let s=[...o.successors].map(c=>r.get(c)),a=new Set([o.id,...zN(s)]);Ad(r.get(o.id),a)||(r.set(o.id,a),i=!0)}}return r}function jN(e,t){let n=new Map(t.map(s=>[s.id,s.parentId])),r=t.flatMap(s=>[...s.cfg.values()].flatMap(a=>a.definitions.map(c=>c.point))),i=new Map;for(let s of r){if(!s.symbolKey)continue;let a=i.get(s.symbolKey)??[];a.push(s),i.set(s.symbolKey,a)}let o=new Set([...e.edges.values()].filter(s=>s.kind==="reaching-definition").map(s=>s.toPointId));for(let s of t)for(let a of[...s.cfg.values()].flatMap(c=>c.uses)){if(!a.point.symbolKey||o.has(a.point.id))continue;let c=i.get(a.point.symbolKey)??[];for(let l of c)HN(l.callableId,a.point.callableId,n)?zo(e,"closure-capture",l.id,a.point.id,"candidate","Compiler identity proves the captured binding, but invocation order can select among outer definitions."):a.property&&zo(e,"field-definition-to-use",l.id,a.point.id,"candidate","Compiler identity matches the field; cross-callable receiver and execution order remain unresolved.")}[...e.edges.values()].some(s=>s.kind==="closure-capture")&&e.unsupported.add("Closure capture identity is known, but invocation order and intervening writes remain candidate flow."),[...e.edges.values()].some(s=>s.kind==="field-definition-to-use")&&e.unsupported.add("Cross-callable field flow lacks receiver points-to and invocation-order analysis.")}function HN(e,t,n){for(let r=n.get(t)??null;r;r=n.get(r)??null)if(r===e)return!0;return!1}function zo(e,t,n,r,i,o){let s=`local-flow-edge:${t}:${encodeURIComponent(n)}:${encodeURIComponent(r)}`;e.edges.set(s,{id:s,kind:t,fromPointId:n,toPointId:r,strength:i,reason:o})}function Cv(e,t){return t>=e.SyntaxKind.FirstAssignment&&t<=e.SyntaxKind.LastAssignment}function UN(e,t){let n=t.getText(e.sourceFile).replace(/\s+/gu," ").trim();return n.length>80?`${n.slice(0,77)}...`:n||e.ts.SyntaxKind[t.kind]||"statement"}function xv(e){return[...new Map(e.map(t=>[t.point.id,t])).values()]}function qN(e){return[...new Map(e.map(t=>[t.id,t])).values()]}function GN(e){return new Set(e.flatMap(t=>[...t]))}function zN(e){return e.length===0?new Set:new Set([...e[0]].filter(t=>e.slice(1).every(n=>n.has(t))))}function Ad(e,t){return e.size===t.size&&[...e].every(n=>t.has(n))}function KN(e,t){return e.start-t.start||e.kind.localeCompare(t.kind)||e.id.localeCompare(t.id)}function Td(e){return{points:[],edges:[],coverage:{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:[e]}}}var VN=An("typescript-local-flow",{clearGroups:["whole-project","source-file","semantic-provider"]});function Fd(e,t,n,r){if(!Un(t))return null;let i=`${t}\0${n}\0${r}`;return VN.get(e,i,()=>{let o=W(e,t);return o?yv(o,WN(e.config.projectRoot,t),{startLine:n,endLine:r}):{points:[],edges:[],coverage:{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:[`Current source is unavailable for ${t}.`]}}})}function YN(e,t=new Map){let n=new Map,r=new Map,i=[];for(let o of e.transfers){if(!e.caller)continue;let s=lc(e.caller,o.callerPosition),a=lc(e.callee,o.calleePosition);Ko(n,s),Ko(n,a),_d(r,e.caller,s),_d(r,e.callee,a);let c=nt("edge","data-transfer",o.proof.file,String(o.proof.startLine),String(o.callerPosition),String(o.calleePosition));r.set(c,{id:c,kind:"data-transfer",fromNodeId:s.id,toNodeId:a.id,directed:!0,disposition:"folded",semantics:[{family:"data",subtype:"argument-to-parameter",attributes:{argumentText:o.argumentText,callerPosition:o.callerPosition,calleePosition:o.calleePosition}}],evidence:[{method:"compiler-callsite-direct-parameter-transfer",strength:"exact",identity:`${e.caller.symbol}:${o.callerPosition} -> ${e.callee.symbol}:${o.calleePosition}`,location:{file:o.proof.file,line:o.proof.startLine,endLine:o.proof.endLine}}]})}return e.unknown.forEach((o,s)=>{let a=lc(e.callee,o.calleePosition);Ko(n,a),_d(r,e.callee,a);let c=t.get(o.calleePosition);if(c&&s_(c)){o_(r,n,e,o.calleePosition,o.argumentText,c);return}let l=r_(e,o.calleePosition,o.argumentText);Ko(n,l);let u=nt("edge","data-transfer-unsupported",o.proof.file,String(o.proof.startLine),String(o.calleePosition),String(s));r.set(u,{id:u,kind:"data-transfer",fromNodeId:l.id,toNodeId:a.id,directed:!0,disposition:"unsupported",semantics:[{family:"data",subtype:"argument-to-parameter",attributes:{argumentText:o.argumentText,calleePosition:o.calleePosition}}],evidence:[{method:"compiler-callsite-argument-expression",strength:"exact",identity:o.argumentText,location:{file:o.proof.file,line:o.proof.startLine,endLine:o.proof.endLine}}]}),i.push({id:nt("frontier","data-transfer",u),kind:"data-transfer",direction:"unresolved",fromNodeIds:[l.id],edgeIds:[u],memberNodeIds:[a.id],memberCount:1,disposition:"unsupported",reason:c?.derivation.rule??o.reason,expansion:null})}),{nodes:[...n.values()],edges:[...r.values()],frontiers:i,blindSpots:[]}}function Ev(e,t,n=[]){let r=Iv(),i=new Map,o=new Set;for(let s of t){if(s.kind!=="call"||!s.fromSymbol||!s.toSymbol||s.line===null)continue;let a=n_(i,e,s.toFile,s.toSymbol);if(!a)continue;let c=Hf(e,a),l=c.sites.filter(g=>g.file===s.fromFile&&g.startLine<=s.line&&g.endLine>=s.line&&g.caller?.symbol===s.fromSymbol);if(l.length!==1){let g=c.unresolved.find(h=>h.file===s.fromFile&&h.line===s.line);g&&r.blindSpots.push(`Parameter flow unresolved at ${s.fromFile}:${s.line+1}: ${g.reason}.`);continue}let u=l[0],d=`${u.file}\0${u.callNode.startIndex}\0${u.callNode.endIndex}\0${a.symbol}`;if(o.has(d))continue;o.add(d);let m=Uf(e,u),p=J(e,u.file)?.rootNode,f=new Map;if(p)for(let g of m.unknown){let h=jf({db:e,file:u.file,root:p},u.arguments[g.calleePosition]);h&&f.set(g.calleePosition,h)}Rv(r,YN(m,f)),m.caller&&e_(u.callNode)&&t_(r,m,u.callNode)}for(let s of n){if(!s.location||!["source-construct","symbol"].includes(s.kind))continue;let a=s.location.endLine??s.location.line,c=Fd(e,s.location.file,s.location.line,a);if(c){Rv(r,JN(s,c.points,c.edges));for(let l of c.coverage.unsupported)r.blindSpots.push(`TypeScript local flow is partial for ${s.location.file}:${s.location.line+1}-${a+1}: ${l} Recover with: scip-query inspect --at '${s.location.file}:${s.location.line+1}-${a+1}' --view behavior.`)}}return r.blindSpots=[...new Set(r.blindSpots)].sort(),r}function JN(e,t,n){let r=Iv(),i=new Map,o=new Map,s=new Map,a=e.location.file;for(let c of t){let l=XN(e,a,c);s.set(c.id,l.id),i.set(l.id,l),QN(o,e,l)}for(let c of n){let l=s.get(c.fromPointId),u=s.get(c.toPointId);if(!l||!u)continue;let d=ZN(c),m=nt("edge","typescript-local-flow",a,c.id);o.set(m,{id:m,kind:c.kind==="control-dependence"?"control-dependence":"data-transfer",fromNodeId:l,toNodeId:u,directed:!0,disposition:"folded",semantics:[d],evidence:[{method:"typescript-compiler-cfg-reaching-definitions",strength:c.strength,identity:c.reason,location:i.get(l)?.location??e.location}]})}return r.nodes=[...i.values()],r.edges=[...o.values()],r}function XN(e,t,n){return{id:nt("local-flow-point",t,String(n.start),String(n.end),n.kind,n.symbolKey??n.name),kind:n.kind==="parameter-definition"||n.kind==="definition"?"local-definition":n.kind==="use"?"local-use":n.kind==="predicate"?"control-predicate":"local-statement",label:n.name,disposition:"folded",location:{file:t,line:n.line,endLine:n.line},anchorIds:[],attributes:{ownerNodeId:e.id,pointKind:n.kind,callableId:n.callableId,symbolKey:n.symbolKey,column:n.column}}}function QN(e,t,n){let r=nt("edge","local-flow-owner",t.id,n.id);e.has(r)||e.set(r,{id:r,kind:"local-flow-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains"}],evidence:[{method:"typescript-compiler-local-flow-owner",strength:"exact",identity:t.id,location:n.location}]})}function ZN(e){switch(e.kind){case"reaching-definition":return{family:"data",subtype:"definition-to-use"};case"value-source":return{family:"data",subtype:"value-to-definition"};case"closure-capture":return{family:"data",subtype:"closure-capture"};case"field-definition-to-use":return{family:"data",subtype:"field-definition-to-use"};case"control-dependence":return{family:"control",subtype:"control-dependence"}}}function e_(e){let t=e;for(;t.parent&&["await_expression","yield_expression","parenthesized_expression","as_expression","type_assertion"].includes(t.parent.type);)t=t.parent;return t.parent!==null&&t.parent.type!=="expression_statement"}function t_(e,t,n){if(!t.caller)return;let r={id:nt("call-result",t.call.file,String(n.startIndex),String(n.endIndex),t.callee.symbol),kind:"call-result",label:`result of ${t.callee.leaf}`,disposition:"folded",location:{file:t.call.file,line:t.call.startLine,endLine:t.call.endLine},anchorIds:[],attributes:{calleeSymbol:t.callee.symbol,callerSymbol:t.caller.symbol}},i=nt("edge","return-to-call-result",t.callee.symbol,r.id),o=nt("edge","call-result-owner",t.caller.symbol,r.id);e.nodes.push(r),e.edges.push({id:i,kind:"data-transfer",fromNodeId:Od(t.callee.symbol),toNodeId:r.id,directed:!0,disposition:"folded",semantics:[{family:"data",subtype:"return-to-call-result"}],evidence:[{method:"compiler-callsite-used-result",strength:"exact",identity:`${t.callee.symbol} -> ${t.caller.symbol}`,location:r.location}]},{id:o,kind:"call-result-owner",fromNodeId:Od(t.caller.symbol),toNodeId:r.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains-call-result"}],evidence:[{method:"compiler-call-result-owner",strength:"exact",identity:t.caller.symbol,location:r.location}]})}function Iv(){return{nodes:[],edges:[],frontiers:[],blindSpots:[]}}function Rv(e,t){Nd(e.nodes,t.nodes),Nd(e.edges,t.edges),Nd(e.frontiers,t.frontiers),e.blindSpots.push(...t.blindSpots)}function Nd(e,t){let n=new Set(e.map(r=>r.id));for(let r of t)n.has(r.id)||(n.add(r.id),e.push(r))}function n_(e,t,n,r){let i=`${n}\0${r}`,o=e.get(i);if(o!==void 0)return o;let s=U(t,n).find(a=>a.symbol===r)??null;return e.set(i,s),s}function lc(e,t){return{id:l_(e.symbol,t),kind:"parameter",label:`${e.leaf} parameter ${t}`,disposition:"folded",location:{file:e.relativePath,line:e.startLine,endLine:e.endLine},anchorIds:[],attributes:{ownerSymbol:e.symbol,position:t}}}function r_(e,t,n){return{id:nt("argument-expression",e.call.file,String(e.call.startLine),String(e.call.endLine),String(t)),kind:"argument-expression",label:n,disposition:"unsupported",location:{file:e.call.file,line:e.call.startLine,endLine:e.call.endLine},anchorIds:[],attributes:{calleeSymbol:e.callee.symbol,position:t}}}function i_(e,t,n){return{id:nt("static-value",e.call.file,String(e.call.startLine),String(e.call.endLine),String(t)),kind:"static-value",label:n.value,disposition:"folded",location:{file:e.call.file,line:e.call.startLine,endLine:e.call.endLine},anchorIds:[],attributes:{value:n.value,precision:n.precision,evidence:n.evidence,termKind:n.term.kind,derivationRule:n.derivation.rule}}}function o_(e,t,n,r,i,o){let s=i_(n,r,o),a=lc(n.callee,r);Ko(t,s);let c=nt("edge","static-value-transfer",n.call.file,String(n.call.startLine),String(r));e.set(c,{id:c,kind:"data-transfer",fromNodeId:s.id,toNodeId:a.id,directed:!0,disposition:"folded",semantics:[{family:"data",subtype:a_(o),attributes:{argumentText:i,calleePosition:r,value:o.value,precision:o.precision,derivationRule:o.derivation.rule}}],evidence:c_(o,n)})}function s_(e){return e.derivation.kind!=="heuristic"&&e.precision!=="symbolic"&&e.precision!=="unknown"}function a_(e){return e.derivation.rule==="bounded-call-return"?"return-to-parameter":e.derivation.rule==="member-constant"||e.term.kind==="property"?"property-to-parameter":"constant-to-parameter"}function c_(e,t){return(e.derivation.sourceSpans.length>0?e.derivation.sourceSpans:[t.call]).map(r=>({method:`static-value:${e.derivation.rule}`,strength:e.derivation.kind==="direct"?"exact":"derived",identity:e.derivation.inputFactIds.join(",")||e.value,location:{file:r.file,line:r.startLine,endLine:r.endLine}}))}function Ko(e,t){e.has(t.id)||e.set(t.id,t)}function _d(e,t,n){let r=nt("edge","parameter-owner",t.symbol,n.id);e.has(r)||e.set(r,{id:r,kind:"parameter-owner",fromNodeId:Od(t.symbol),toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains"}],evidence:[{method:"compiler-parameter-owner",strength:"exact",identity:t.symbol,location:{file:t.relativePath,line:t.startLine,endLine:t.endLine}}]})}function l_(e,t){return nt("parameter",e,String(t))}function Od(e){return nt("symbol",e)}function nt(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function wv(e,t){let n=new Map,r=new Map,i=new Map,o=new Set;for(let s of t){if(!s.location||!["source-construct","symbol"].includes(s.kind))continue;let a=s.location.endLine??s.location.line,c=Eg(e,s.location.file,s.location.line,a);if(!c){o.add(`Control dependence unavailable for ${s.location.file}:${s.location.line+1}-${a+1}: no supported syntax tree or covering construct.`);continue}for(let l of c.facts){let u=Bd(s,l.controller),d=Bd(s,l.outcome);n.set(u.id,u),n.set(d.id,d),u_(r,s,u);let m=qr("edge","control-dependence",u.id,d.id,l.subtype);r.set(m,{id:m,kind:"control-dependence",fromNodeId:u.id,toNodeId:d.id,directed:!0,disposition:"folded",semantics:[{family:"control",subtype:l.subtype,attributes:{...l.attributes}}],evidence:[{method:"parser-control-dependence",strength:"exact",identity:`${s.location.file}:${l.controller.startLine+1}-${l.outcome.startLine+1}`,location:{file:s.location.file,line:l.controller.startLine,endLine:l.controller.endLine}}]})}for(let l of c.terminals){let u=Bd(s,l);n.set(u.id,u);let d=l.label.startsWith("throw")||l.label.startsWith("raise")?"throw":"return",m=qr("edge","control-terminal",s.id,u.id,d);r.set(m,{id:m,kind:"control-terminal",fromNodeId:s.id,toNodeId:u.id,directed:!0,disposition:"folded",semantics:[{family:"control",subtype:d==="throw"?"throws":"returns"}],evidence:[{method:"parser-terminal-statement",strength:"exact",identity:l.label,location:{file:s.location.file,line:l.startLine,endLine:l.endLine}}]})}for(let l of c.unsupported){let u=qr("control-unsupported",s.location.file,String(l.startLine),String(l.endLine),l.reason);n.set(u,{id:u,kind:"control-unsupported",label:l.reason,disposition:"unsupported",location:{file:s.location.file,line:l.startLine,endLine:l.endLine},anchorIds:[],attributes:{ownerNodeId:s.id}});let d=qr("edge","control-unsupported",s.id,u);r.set(d,{id:d,kind:"control-dependence",fromNodeId:s.id,toNodeId:u,directed:!0,disposition:"unsupported",semantics:[{family:"control",subtype:"unresolved-control-construct"}],evidence:[{method:"parser-control-construct",strength:"exact",identity:l.reason,location:{file:s.location.file,line:l.startLine,endLine:l.endLine}}]});let m=qr("frontier","control-dependence",u);i.set(m,{id:m,kind:"control-dependence",direction:"unresolved",fromNodeIds:[s.id],edgeIds:[d],memberNodeIds:[u],memberCount:1,disposition:"unsupported",reason:l.reason,expansion:null})}}return{nodes:[...n.values()],edges:[...r.values()],frontiers:[...i.values()],blindSpots:[...o].sort()}}function Bd(e,t){let n=e.location.file;return{id:qr(`control-${t.kind}`,n,String(t.startLine),String(t.endLine),t.label),kind:`control-${t.kind}`,label:t.label,disposition:"folded",location:{file:n,line:t.startLine,endLine:t.endLine},anchorIds:[],attributes:{ownerNodeId:e.id,constructKind:t.kind,implicit:t.implicit}}}function u_(e,t,n){let r=qr("edge","control-owner",t.id,n.id);e.has(r)||e.set(r,{id:r,kind:"control-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains-control"}],evidence:[{method:"parser-control-owner",strength:"exact",identity:t.id,location:t.location}]})}function qr(...e){return e.map(t=>encodeURIComponent(t)).join(":")}var uc=new Set(["arrow_function","constructor_declaration","function_declaration","function_definition","function_expression","generator_function","generator_function_declaration","function_item","lambda","lambda_expression","method","method_declaration","method_definition"]),Vo=new Set(["block","body","compound_statement","declaration_list","statement_block"]),d_=new Set(["assignment","assignment_expression","augmented_assignment_expression"]),jd=new Set(["update_expression"]),Mv=new Set(["array_access","element_access_expression","subscript_expression"]),Tv=new Set(["attribute","field_access","field_expression","member_access_expression","member_expression","selector_expression"]),m_=new Set(["false","null","null_literal","number","number_literal","string","string_literal","template_string","true"]),p_=new Set(["call_expression","method_invocation","object_creation_expression"]),f_=new Set(["comment","else_clause","formal_parameters","parameters","type_parameters"]);function kv(e,t,n,r){let i=J(e,t);if(!i)return null;let o=x_(i.rootNode,n,r);if(!o)return null;let s=[],a=[],c=[];return Gr(o,l=>{if(d_.has(l.type)||jd.has(l.type)||Fv(l)){let u=g_(l);u?s.push(u):c.push({family:"state",startLine:l.startPosition.row,endLine:l.endPosition.row,reason:`Mutation target ${tn(l.text)} could not be resolved to an exact source resource.`})}}),Gr(o,l=>{if(!Vo.has(l.type))return;let u=v_(l);for(let d=0;d<u.length-1;d+=1)a.push({from:Wo(u[d]),to:Wo(u[d+1]),subtype:"lexical-successor",synchronizationScope:null,attributes:{sameScope:!0,executionConditional:!0}});for(let d=0;d<u.length;d+=1){let m=u[d],p=E_(m).filter(f=>f.type==="await_expression");for(let f of p){let g=Yo("event",`await ${tn(f.text.replace(/^await\s+/u,""))}`,f);a.push({from:Wo(m),to:g,subtype:"awaits-completion",synchronizationScope:null,attributes:{completionRequired:!0}});let h=u[d+1];h&&a.push({from:g,to:Wo(h),subtype:"await-completion-before",synchronizationScope:null,attributes:{continuationOnly:!0}})}}}),Gr(o,l=>{if(l.type!=="synchronized_statement")return;let u=l.childForFieldName("object")??l.childForFieldName("condition")??l.namedChildren.find(g=>!Vo.has(g.type)),d=l.childForFieldName("body")??l.namedChildren.find(g=>Vo.has(g.type));if(!u||!d){c.push({family:"temporal",startLine:l.startPosition.row,endLine:l.endPosition.row,reason:"Synchronized scope has no structurally resolved monitor or body."});return}let m=tn(u.text).replace(/^\(|\)$/gu,""),p=Yo("lock",m,u),f=R_(d).filter(g=>g.parent!==null&&Nv(g));for(let g of C_(f))a.push({from:p,to:Wo(g),subtype:"inside-lock-scope",synchronizationScope:m,attributes:{syntaxNative:!0}})}),{mutations:s,temporal:a,unsupported:c}}function g_(e){let t=Fv(e),n=e.childForFieldName("left")??e.childForFieldName("argument")??(t?e.namedChildren.at(-1)??null:e.namedChildren[0]??null);if(!n)return null;let r=h_(n);if(!r)return null;let i=t?"delete":jd.has(e.type)||!S_(e,n).startsWith("=")?"update":"assign",o=t||jd.has(e.type)?null:e.childForFieldName("right");return{event:Yo("event",tn(e.text),e),resource:{kind:"resource",label:r.name,startLine:n.startPosition.row,endLine:n.endPosition.row},operation:i,durabilityClass:"in-memory",recordIdentity:r.recordIdentity,value:o?Yo("value",tn(o.text),o):null,dataSubtype:o?y_(o,e):null}}function h_(e){if(Mv.has(e.type)){let t=e.childForFieldName("object")??e.childForFieldName("array")??e.namedChildren[0]??null,n=e.childForFieldName("index")??e.childForFieldName("subscript")??e.namedChildren[1]??null;return!t||!n?null:{name:`${tn(t.text)}[]`,recordIdentity:tn(n.text)}}return Tv.has(e.type)?{name:tn(e.text),recordIdentity:null}:/^(?:identifier|property_identifier|field_identifier)$/u.test(e.type)?{name:tn(e.text),recordIdentity:null}:null}function y_(e,t){return m_.has(e.type)||/(?:integer|float|decimal|boolean|character)_literal$/u.test(e.type)?"constant-to-state":p_.has(e.type)?"return-to-state":Tv.has(e.type)||Mv.has(e.type)?"property-to-state":/identifier$/u.test(e.type)?b_(e.text,t)?"captured-value-to-state":"value-to-state":"expression-to-state"}function b_(e,t){let n=$d(t.parent);if(!n||Lv(n,e))return!1;let r=$d(n.parent);for(;r;){if(Lv(r,e))return!0;r=$d(r.parent)}return!1}function $d(e){let t=e;for(;t;){if(uc.has(t.type))return t;t=t.parent}return null}function Lv(e,t){let n=e.childForFieldName("parameters")??e.namedChildren.find(o=>["formal_parameters","parameters"].includes(o.type));if(n&&Pv(n,t))return!0;let r=e.childForFieldName("body")??e.namedChildren.find(o=>Vo.has(o.type));if(!r)return!1;let i=!1;return Av(r,e,o=>{if(i||!/(?:declarator|declaration|parameter)$/u.test(o.type))return;let s=o.childForFieldName("name")??o.childForFieldName("pattern")??o.namedChildren[0];s&&Pv(s,t)&&(i=!0)}),i}function Pv(e,t){let n=!1;return Gr(e,r=>{/identifier$/u.test(r.type)&&r.text===t&&(n=!0)}),n}function Av(e,t,n){n(e);for(let r of e.namedChildren)r!==t&&uc.has(r.type)||Av(r,t,n)}function S_(e,t){let n=e.childForFieldName("right"),r=Math.max(0,t.endIndex-e.startIndex),i=n?Math.max(r,n.startIndex-e.startIndex):e.text.length;return e.text.slice(r,i).trim()}function Fv(e){return(e.type==="delete_expression"||e.type==="unary_expression")&&/^delete\b/u.test(e.text.trim())}function v_(e){return e.namedChildren.filter(t=>Nv(t))}function Nv(e){return f_.has(e.type)||Vo.has(e.type)?!1:/(?:statement|declaration)$/u.test(e.type)||e.type==="expression_statement"||e.type==="local_variable_declaration"}function C_(e){let t=new Set(e);return e.filter(n=>{let r=n.parent;for(;r;){if(t.has(r))return!1;r=r.parent}return!0})}function Wo(e){return Yo("event",tn(e.text),e)}function Yo(e,t,n){return{kind:e,label:t,startLine:n.startPosition.row,endLine:n.endPosition.row}}function x_(e,t,n){let r=[];return Gr(e,o=>{o.startPosition.row<=t&&o.endPosition.row>=n&&r.push(o)}),r.filter(o=>uc.has(o.type)).sort(Dv)[0]??r.sort(Dv)[0]??null}function Dv(e,t){return e.endIndex-e.startIndex-(t.endIndex-t.startIndex)||e.startIndex-t.startIndex}function R_(e){let t=[];return Gr(e,n=>t.push(n)),t}function E_(e){let t=[],n=r=>{t.push(r);for(let i of r.namedChildren)i!==e&&uc.has(i.type)||n(i)};return n(e),t}function Gr(e,t){t(e);for(let n of e.namedChildren)Gr(n,t)}function tn(e){return e.trim().replace(/\s+/gu," ")}function Bv(e,t,n=[]){let r=new Map,i=new Map,o=new Map,s=new Set;for(let a of t){if(!a.location||!["source-construct","symbol"].includes(a.kind))continue;let c=a.location.endLine??a.location.line,l=kv(e,a.location.file,a.location.line,c);if(!l){s.add(`State and temporal analysis unavailable for ${a.location.file}:${a.location.line+1}-${c+1}: no supported syntax tree or covering construct.`);continue}for(let u of l.mutations){let d=mc(a,u.event),m=M_(a,u.resource,u.durabilityClass);if(r.set(d.id,d),r.set(m.id,m),pc(i,a,d,"contains-state-effect"),fc(i,{kind:"state-resource",from:d,to:m,semantics:[{family:"state",subtype:u.operation==="delete"?"deletes-resource":"writes-resource",attributes:{operation:u.operation,durabilityClass:u.durabilityClass,resource:u.resource.label,recordIdentity:u.recordIdentity,transactionMembership:"unknown"}}],method:"parser-state-mutation",identity:u.event.label}),u.value&&u.dataSubtype){let p=mc(a,u.value);r.set(p.id,p),fc(i,{kind:"data-to-state",from:p,to:m,semantics:[{family:"data",subtype:u.dataSubtype,attributes:{operation:u.operation,resource:u.resource.label,recordIdentity:u.recordIdentity,value:u.value.label}}],method:"parser-assignment-value",identity:`${u.value.label} -> ${u.resource.label}`})}}for(let u of l.temporal){let d=mc(a,u.from),m=mc(a,u.to);r.set(d.id,d),r.set(m.id,m),pc(i,a,d,u.from.kind==="lock"?"contains-lock-scope":"contains-event"),pc(i,a,m,"contains-event"),fc(i,{kind:"temporal-order",from:d,to:m,semantics:[{family:"temporal",subtype:u.subtype,context:u.synchronizationScope?{synchronizationScope:u.synchronizationScope}:void 0,attributes:{...u.attributes}}],method:u.subtype==="inside-lock-scope"?"parser-synchronized-scope":"parser-program-order",identity:`${u.from.label} -> ${u.to.label}`})}for(let u of l.unsupported){let d=wn(`${u.family}-unsupported`,a.location.file,String(u.startLine),String(u.endLine),u.reason);r.set(d,{id:d,kind:`${u.family}-unsupported`,label:u.reason,disposition:"unsupported",location:{file:a.location.file,line:u.startLine,endLine:u.endLine},anchorIds:[],attributes:{ownerNodeId:a.id}});let m=wn("edge",`${u.family}-unsupported`,a.id,d);i.set(m,{id:m,kind:`${u.family}-unsupported`,fromNodeId:a.id,toNodeId:d,directed:!0,disposition:"unsupported",semantics:[{family:u.family,subtype:`unresolved-${u.family}-construct`}],evidence:[{method:`parser-${u.family}-construct`,strength:"exact",identity:u.reason,location:{file:a.location.file,line:u.startLine,endLine:u.endLine}}]});let p=wn("frontier",u.family,d);o.set(p,{id:p,kind:u.family,direction:"unresolved",fromNodeIds:[a.id],edgeIds:[m],memberNodeIds:[d],memberCount:1,disposition:"unsupported",reason:u.reason,expansion:null})}}for(let a of t.filter(c=>c.kind==="runtime-boundary-participant")){let c=dc(a,"protocol"),l=dc(a,"action"),u=dc(a,"address")??a.label;!c||!l||!Ov(c,l)||_v(r,i,a,{observationId:a.id,action:l,strength:"exact",file:a.location?.file??"",line:a.location?.line??0,address:u,protocol:c,role:dc(a,"role")??void 0,resolution:"locally-linked"})}for(let a of n){if(!a.protocol||!Ov(a.protocol,a.action))continue;let c=P_(t,a.file,a.line,a.ownerShortName??null);if(!c){s.add(`State observation ${a.observationId} at ${a.file}:${a.line+1} has no materialized owner node.`);continue}_v(r,i,c,a)}return{nodes:[...r.values()],edges:[...i.values()],frontiers:[...o.values()],blindSpots:[...s].sort()}}function _v(e,t,n,r){let i=w_(r),s={id:wn("runtime-state-event",r.observationId),kind:"runtime-state-event",label:`${r.action} ${i}`,disposition:"folded",location:{file:r.file,line:r.line},anchorIds:[],attributes:{action:r.action,protocol:r.protocol??null,modality:r.modality??null,resolution:r.resolution??null}},a=r.protocol==="database"?"external-durable-intent":"external",c={id:wn("runtime-state-resource",r.protocol??"unknown",i),kind:"runtime-state-resource",label:i,disposition:"folded",location:{file:r.file,line:r.line},anchorIds:[],attributes:{protocol:r.protocol??null,durabilityClass:a}};e.set(s.id,s),e.set(c.id,c),pc(t,n,s,"contains-runtime-state-effect");let l=I_(r.action);fc(t,{kind:"runtime-state-resource",from:s,to:c,semantics:[{family:"state",subtype:l,context:{crossesRuntimeBoundary:!0,protocol:r.protocol},attributes:{operation:r.action,durabilityClass:a,resource:i,recordIdentity:L_(r),modality:r.modality??null,resolution:r.resolution??null,transactionMembership:"unknown",commitState:r.protocol==="database"?"unknown":null}}],method:`runtime-boundary-${r.strength}`,identity:r.observationId})}function I_(e){return e==="database.read"?"reads-resource":e==="queue.send"?"enqueues-resource":e==="queue.consume"?"consumes-resource":"writes-resource"}function w_(e){return(e.keyParts?.find(n=>["address","resource"].includes(n.name))?.value??e.address)||e.observationId}function L_(e){return e.keyParts?.find(n=>/^(?:id|key|record)$/u.test(n.name))?.value??null}function Ov(e,t){return e==="database"&&["database.read","database.write"].includes(t)||e==="queue"&&["queue.consume","queue.send"].includes(t)}function dc(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function P_(e,t,n,r){let i=e.filter(s=>s.location?.file===t&&["source-construct","symbol"].includes(s.kind)),o=i.filter(s=>s.location.line<=n&&(s.location.endLine??s.location.line)>=n).sort(D_)[0];if(o)return o;if(r){let s=i.find(a=>a.label===r||a.label.endsWith(`.${r}`)||a.label.includes(r));if(s)return s}return i.length===1?i[0]:null}function D_(e,t){let n=(e.location?.endLine??e.location?.line??0)-(e.location?.line??0),r=(t.location?.endLine??t.location?.line??0)-(t.location?.line??0);return n-r}function mc(e,t){let n=e.location.file;return{id:wn(`program-${t.kind}`,n,String(t.startLine),String(t.endLine),t.label),kind:`program-${t.kind}`,label:t.label,disposition:"folded",location:{file:n,line:t.startLine,endLine:t.endLine},anchorIds:[],attributes:{ownerNodeId:e.id,constructKind:t.kind}}}function M_(e,t,n){let r=e.location.file;return{id:wn("program-resource",r,e.id,t.label,n),kind:"program-resource",label:t.label,disposition:"folded",location:{file:r,line:t.startLine,endLine:t.endLine},anchorIds:[],attributes:{ownerNodeId:e.id,durabilityClass:n}}}function pc(e,t,n,r){let i=wn("edge","program-owner",t.id,n.id,r);e.has(i)||e.set(i,{id:i,kind:"program-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:r}],evidence:[{method:"parser-program-owner",strength:"exact",identity:t.id,location:n.location}]})}function fc(e,t){let n=wn("edge",t.kind,t.from.id,t.to.id,t.semantics[0].subtype);e.set(n,{id:n,kind:t.kind,fromNodeId:t.from.id,toNodeId:t.to.id,directed:!0,disposition:"folded",semantics:t.semantics,evidence:[{method:t.method,strength:"exact",identity:t.identity,location:t.from.location}]})}function wn(...e){return e.map(t=>encodeURIComponent(t)).join(":")}var T_=new Set(["control","data","state","temporal"]),gc=new Set(["contains-control","contains-event","contains-lock-scope","contains-state-effect","contains-runtime-state-effect","contains","owns-parameter","owns-runtime-observation"]),Uv=new Set(["discriminator-dispatch","result-callback","returns","runtime-handoff","throws"]);function qv(e,t={}){let n=new Map(e.nodes.map(E=>[E.id,E])),r=B_(e.nodes,t.focusLocations),i=$_(e.edges,t.focusLocations),o=j_(e.edges,i),s=new Set(e.paths.flatMap(E=>E.edgeIds)),a=Ln(e.anchors.filter(E=>E.status==="matched").flatMap(E=>E.nodeIds)),l=e.edges.filter(Hv).filter(E=>k_(E,r,i,s)),u=l.filter(E=>__(E,r,i,o,n,s)),d=$v(a,u,"forward"),m=N_(d,u),p=$v(m,u,"backward"),f=new Set([...d].filter(E=>p.has(E)));for(let E of a)f.add(E);let g=new Set(u.filter(E=>f.has(E.fromNodeId)&&f.has(E.toNodeId)).map(E=>E.id)),h=new Set(f),b=new Set(g);A_(l,h,b,r,i);let S=e.frontiers.filter(E=>U_(E,h)),y=Ln(S.filter(E=>E.disposition==="unsupported").map(E=>E.id)),x=Ln(e.edges.filter(E=>!Hv(E)&&zv(E)&&H_(E,h)).map(E=>E.id)),v=Ln(S.map(E=>E.id)),C=[];a.length===0&&C.push("No matched anchor node starts the corridor."),m.length===0&&C.push("No proved mechanical outcome is reachable from a matched anchor."),y.length>0&&C.push(`${y.length} unsupported frontier(s) touch the protected corridor.`),x.length>0&&C.push(`${x.length} candidate or unknown edge(s) touch the protected corridor.`);let R=C.length===0?"complete":"incomplete";return{schemaVersion:1,status:R,startNodeIds:a,outcomeNodeIds:m,baseNodeIds:Ln([...f]),baseEdgeIds:Ln([...g]),nodeIds:Ln([...h]),edgeIds:Ln([...b]),accountedFrontierIds:v,unresolvedFrontierIds:y,unresolvedEdgeIds:x,coverage:{protectedNodes:h.size,protectedEdges:b.size,baseNodes:f.size,baseEdges:g.size,accountedFrontiers:v.length,unresolvedFrontiers:y.length,unresolvedEdges:x.length},explanation:R==="complete"?"Every proved anchor-to-outcome path is closed over its material causal facts within reported coverage.":C.join(" ")}}function k_(e,t,n,r){return t===null||e.disposition==="emitted"||r.has(e.id)||n?.has(e.id)===!0?!0:(e.semantics??[]).some(i=>{if(i.family==="identity"&&gc.has(i.subtype))return t.has(e.toNodeId);if(i.family==="contract")return t.has(e.fromNodeId)&&t.has(e.toNodeId);if(i.family==="state")return t.has(e.fromNodeId);if(i.family==="data"||i.family==="temporal")return t.has(e.fromNodeId)||t.has(e.toNodeId);if(i.family==="control"){if(Kv(i))return t.has(e.fromNodeId);if(["returns","throws"].includes(i.subtype))return t.has(e.toNodeId);if(i.subtype==="completion-callback")return t.has(e.fromNodeId)||t.has(e.toNodeId)}return!1})}function A_(e,t,n,r,i){let o=!0;for(;o;){o=!1;for(let s of e)F_(s,t,r,i)&&(n.has(s.id)||(n.add(s.id),o=!0),t.has(s.fromNodeId)||(t.add(s.fromNodeId),o=!0),t.has(s.toNodeId)||(t.add(s.toNodeId),o=!0))}}function F_(e,t,n,r){let i=t.has(e.fromNodeId),o=t.has(e.toNodeId);return!i&&!o?!1:(e.semantics??[]).some(s=>s.family==="identity"?gc.has(s.subtype)&&(o||n===null||n.has(e.toNodeId)):s.family==="contract"?!0:s.family==="state"?i&&(n===null||n.has(e.fromNodeId)):s.family==="temporal"?s.subtype==="lexical-successor"?i&&o:!0:s.family==="data"?o&&(i||n===null||n.has(e.fromNodeId)||r?.has(e.id)===!0):s.family==="control"?Gv(s)||["returns","throws"].includes(s.subtype)&&!o&&n!==null&&!n.has(e.toNodeId)?!1:Uv.has(s.subtype)||Kv(s)||s.subtype==="completion-callback":!1)}function N_(e,t){let n=new Set,r=new Map,i=new Map;for(let o of t)!e.has(o.fromNodeId)||!e.has(o.toNodeId)||(r.set(o.fromNodeId,(r.get(o.fromNodeId)??0)+1),i.set(o.toNodeId,(i.get(o.toNodeId)??0)+1),(o.semantics??[]).some(s=>s.family==="state"||s.family==="control"&&Uv.has(s.subtype))&&n.add(o.toNodeId));for(let o of e)(i.get(o)??0)>0&&(r.get(o)??0)===0&&n.add(o);return Ln([...n])}function $v(e,t,n){let r=new Map;for(let s of t){let a=n==="forward"?s.fromNodeId:s.toNodeId,c=n==="forward"?s.toNodeId:s.fromNodeId,l=r.get(a)??[];l.push(c),r.set(a,l)}let i=new Set(e),o=[...e];for(;o.length>0;){let s=o.shift();for(let a of r.get(s)??[])i.has(a)||(i.add(a),o.push(a))}return i}function __(e,t,n,r,i,o){return(e.semantics??[]).some(s=>e.disposition==="emitted"||o.has(e.id)?!0:s.family==="identity"&&gc.has(s.subtype)?t===null||t.has(e.toNodeId)||r?.has(e.toNodeId)===!0:!T_.has(s.family)||Gv(s)?!1:s.family==="control"&&["returns","throws"].includes(s.subtype)&&t!==null?t.has(e.toNodeId):t===null?!0:s.family==="state"?t.has(e.fromNodeId):s.family==="data"?t.has(e.fromNodeId)||t.has(e.toNodeId)||n?.has(e.id)===!0:s.family==="temporal"?s.subtype==="lexical-successor"?t.has(e.fromNodeId)&&t.has(e.toNodeId):t.has(e.fromNodeId)||t.has(e.toNodeId):s.family==="control"?O_(e,i)&&(t.has(e.fromNodeId)||t.has(e.toNodeId)):!1)}function Gv(e){return e.family==="control"&&["call","discriminator-dispatch","result-callback","runtime-handoff"].includes(e.subtype)}function O_(e,t){let n=t.get(e.fromNodeId),r=t.get(e.toNodeId);if(!n||!r)return!1;let i=jv(n,"ownerNodeId")??(n.kind==="symbol"?n.id:null),o=jv(r,"ownerNodeId")??(r.kind==="symbol"?r.id:null);return i!==null&&i===o}function B_(e,t){if(!t)return null;let n=new Map;for(let r of t){let i=n.get(r.file)??[];i.push(r.line),n.set(r.file,i)}return new Set(e.filter(r=>{if(!r.location||r.kind==="parameter")return!1;let i=n.get(r.location.file)??[],o=r.location.endLine??r.location.line;return i.some(s=>s>=r.location.line&&s<=o)}).map(r=>r.id))}function $_(e,t){if(!t)return null;let n=new Map;for(let r of t){let i=n.get(r.file)??[];i.push(r.line),n.set(r.file,i)}return new Set(e.filter(r=>r.evidence.some(i=>{if(!i.location)return!1;let o=n.get(i.location.file)??[],s=i.location.endLine??i.location.line;return o.some(a=>a>=i.location.line&&a<=s)})).map(r=>r.id))}function j_(e,t){return t===null?null:new Set(e.filter(n=>t.has(n.id)).flatMap(n=>[n.fromNodeId,n.toNodeId]))}function jv(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function Hv(e){return e.disposition==="excluded"||e.disposition==="unsupported"||!zv(e)?!1:e.evidence.some(t=>t.strength==="exact"||t.strength==="derived")}function zv(e){return(e.semantics??[]).some(t=>t.family!=="identity"||gc.has(t.subtype))}function Kv(e){return e.subtype.startsWith("predicate-")||e.subtype.startsWith("loop-")||e.subtype.startsWith("exception-")||e.subtype.startsWith("finally-")||e.subtype.startsWith("handler-")}function H_(e,t){return t.has(e.fromNodeId)||t.has(e.toNodeId)}function U_(e,t){return[...e.fromNodeIds,...e.memberNodeIds].some(n=>t.has(n))}function Ln(e){return[...new Set(e)].sort()}import{createHash as q_}from"crypto";var hc=["identity","contract","control","data","state","temporal"],G_=new Set(hc);function bc(e){let t=Ai(e.anchors,"anchor"),n=Ai(e.nodes,"node"),r=Ai(e.edges,"edge"),i=Ai(e.paths??[],"path"),o=Ai(e.frontiers??[],"frontier"),s=new Set(t.map(p=>p.id)),a=new Set(n.map(p=>p.id)),c=new Set(r.map(p=>p.id)),l=e.routeCatalog?{...e.routeCatalog,routes:Ai(e.routeCatalog.routes,"route"),selectedRouteIds:lt(e.routeCatalog.selectedRouteIds)}:void 0;for(let p of t)gt(`anchor ${p.id}`,[...p.nodeIds,...p.candidateNodeIds],a,"node");for(let p of n)gt(`node ${p.id}`,p.anchorIds,s,"anchor");for(let p of r){if(gt(`edge ${p.id}`,[p.fromNodeId,p.toNodeId],a,"node"),p.evidence.length===0)throw new Error(`Exploration edge ${p.id} has no evidence source.`);W_(p)}for(let p of i)gt(`path ${p.id}`,[p.fromAnchorId,p.toAnchorId],s,"anchor"),gt(`path ${p.id}`,p.nodeIds,a,"node"),gt(`path ${p.id}`,p.edgeIds,c,"edge");for(let p of o)if(gt(`frontier ${p.id}`,p.fromNodeIds,a,"node"),gt(`frontier ${p.id}`,p.edgeIds,c,"edge"),gt(`frontier ${p.id}`,p.memberNodeIds,a,"node"),p.memberCount!==p.memberNodeIds.length)throw new Error(`Exploration frontier ${p.id} reports ${p.memberCount} member(s) but identifies ${p.memberNodeIds.length}.`);for(let p of l?.routes??[])gt(`route ${p.id}`,p.nodeIds,a,"node"),gt(`route ${p.id}`,p.edgeIds,c,"edge"),gt(`route ${p.id}`,[p.anchorNodeId,p.endpointNodeId],a,"node");l&>("route catalog selection",l.selectedRouteIds,new Set(l.routes.map(p=>p.id)),"route");let u=lt(e.incompleteReasons??[]),d=u.length===0?"accounted":"incomplete",m=t.reduce((p,f)=>p+f.omittedCandidates,0);return{schemaVersion:1,anchors:t,nodes:n,edges:r,paths:i,frontiers:o,coverage:{status:d,scope:e.scope,nodes:tC(n),edges:tC(r),matchedAnchors:t.filter(p=>p.status==="matched").length,ambiguousAnchors:t.filter(p=>p.status==="ambiguous").length,missingAnchors:t.filter(p=>p.status==="missing").length,omittedCandidates:m,frontierGroups:o.length,programEdges:K_(r),blindSpots:lt(e.blindSpots??[]),explanation:d==="accounted"?"Every node and edge discovered within the declared query scope is emitted, folded with recoverable identity, explicitly excluded, or reported unsupported.":`The declared query scope is not fully accounted for: ${u.join("; ")}`},completion:J_(d,i,e.scope),...l?{routeCatalog:l}:{}}}function z_(e){return e.flatMap(t=>V_(t.semantics??[]).map(n=>({id:Y_(t.id,n),sourceEdgeId:t.id,sourceKind:t.kind,fromNodeId:t.fromNodeId,toNodeId:t.toNodeId,directed:!0,disposition:t.disposition,evidence:[...t.evidence],family:n.family,subtype:n.subtype,...n.context?{context:{...n.context}}:{},...n.attributes?{attributes:{...n.attributes}}:{}}))).sort((t,n)=>t.id.localeCompare(n.id))}function K_(e){let t=z_(e),n=new Set(t.map(s=>s.sourceEdgeId)),r=new Map(hc.map(s=>[s,new Set])),i=new Map(hc.map(s=>[s,new Set])),o=new Map(hc.map(s=>[s,0]));for(let s of t)r.get(s.family).add(s.sourceEdgeId),i.get(s.family).add(s.subtype),o.set(s.family,o.get(s.family)+1);return{sourceEdges:e.length,mappedSourceEdges:n.size,projectedEdges:t.length,unmappedSourceEdges:e.length-n.size,unsupportedSourceEdges:e.filter(s=>s.disposition==="unsupported").length,unmappedKinds:lt(e.filter(s=>!n.has(s.id)).map(s=>s.kind)),families:{identity:ki("identity",r,o,i),contract:ki("contract",r,o,i),control:ki("control",r,o,i),data:ki("data",r,o,i),state:ki("state",r,o,i),temporal:ki("temporal",r,o,i)}}}function ki(e,t,n,r){return{sourceEdges:t.get(e)?.size??0,projectedEdges:n.get(e)??0,subtypes:[...r.get(e)??[]].sort()}}function W_(e){let t=new Set;for(let n of e.semantics??[]){if(!G_.has(n.family))throw new Error(`Exploration edge ${e.id} has unknown program edge family: ${n.family}.`);if(n.subtype.trim().length===0)throw new Error(`Exploration edge ${e.id} has an empty program edge subtype.`);let r=Hd(n);if(t.has(r))throw new Error(`Exploration edge ${e.id} repeats program edge semantic ${r}.`);t.add(r)}}function V_(e){return[...e].sort((t,n)=>Hd(t).localeCompare(Hd(n)))}function Hd(e){return`${e.family}:${e.subtype}`}function Y_(e,t){return`program:${encodeURIComponent(e)}:${t.family}:${encodeURIComponent(t.subtype)}`}function J_(e,t,n){return e==="incomplete"||t.some(r=>r.status!=="connected")?{status:"coverage-incomplete",scope:n,explanation:"The declared graph query has an ambiguous, missing, candidate-only, or disconnected anchor relationship."}:t.length>0?{status:"connector-complete",scope:n,explanation:"Every requested anchor pair has a selected path supported by proved repository relationships."}:{status:"frontier-accounted",scope:n,explanation:"Every discovered direction in the declared graph query is emitted or represented by an exact frontier."}}function nC(e,t={}){let n=t.maxSelectedNodes??24;if(!Number.isSafeInteger(n)||n<=0)throw new RangeError(`maxSelectedNodes must be a positive safe integer; received ${n}`);let r=new Set(e.anchors.flatMap(I=>[...I.nodeIds,...I.candidateNodeIds])),i=[],o=e.anchors.filter(I=>I.status!=="missing"&&I.nodeIds.length+I.candidateNodeIds.length>0);for(let I=0;I<o.length;I+=1)for(let k=I+1;k<o.length;k+=1){let D=o[I],F=o[k],L=Xv(e,D,F,!1),P=L??Xv(e,D,F,!0);P?(P.nodeIds.forEach(j=>r.add(j)),i.push({id:yc("path",D.id,F.id),fromAnchorId:D.id,toAnchorId:F.id,status:!L||D.status==="ambiguous"||F.status==="ambiguous"?"candidate":"connected",nodeIds:P.nodeIds,edgeIds:P.edgeIds})):i.push({id:yc("path",D.id,F.id),fromAnchorId:D.id,toAnchorId:F.id,status:"partial",nodeIds:[],edgeIds:[]})}let s=lt(t.routeIds??[]),a=X_(e,s),c=new Set(a.routes.map(I=>I.id)),l=s.filter(I=>!c.has(I));if(l.length>0)throw new Error(`Unknown exploration route id(s): ${l.join(", ")}`);let d=a.routes.filter(I=>s.includes(I.id)).map(I=>({anchorNodeId:I.anchorNodeId,endpointNodeId:I.endpointNodeId,endpointKind:I.endpointKind,endpointPriority:2,nodeIds:[...I.nodeIds].reverse(),edgeIds:[...I.edgeIds].reverse()}));for(let I of d)I.nodeIds.forEach(k=>r.add(k));let m=i.length===0||i.some(I=>I.edgeIds.length>0);m&&Zv(e,r,n);let p=eC(e,r),f=new Set(t.expandedFrontierIds??[]),g=new Set(p.map(I=>I.id)),h=[...f].filter(I=>!g.has(I)).sort();if(h.length>0)throw new Error(`Unknown exploration frontier id(s): ${h.join(", ")}`);for(let I of p)f.has(I.id)&&I.memberNodeIds.forEach(k=>r.add(k));m&&Zv(e,r,n);let b=new Map(d.map(I=>[I.endpointNodeId,I.endpointKind])),S=new Set(d.flatMap(I=>I.nodeIds)),y=new Map;for(let I of d)for(let k=0;k<I.nodeIds.length;k+=1){let D=I.nodeIds[k],F=k;y.set(D,Math.max(y.get(D)??0,F))}let x=e.nodes.map(I=>{let k=b.get(I.id),D=S.has(I.id)?{upstreamCausalPath:!0,upstreamCausalDistance:y.get(I.id)??0,...k?{upstreamCausalEndpoint:k}:{}}:{};return{...I,attributes:{...I.attributes,...D},disposition:I.disposition==="excluded"||I.disposition==="unsupported"?I.disposition:r.has(I.id)?"emitted":"folded"}}),v=new Set([...i.flatMap(I=>I.edgeIds),...d.flatMap(I=>I.edgeIds)]),C=e.edges.map(I=>({...I,disposition:I.disposition==="excluded"||I.disposition==="unsupported"?I.disposition:v.has(I.id)||r.has(I.fromNodeId)&&r.has(I.toNodeId)?"emitted":"folded"})),R=bc({anchors:e.anchors,nodes:x,edges:C,paths:i,frontiers:[...e.frontiers.filter(I=>I.disposition!=="folded"),...eC({...e,nodes:x,edges:C},r)],scope:e.coverage.scope,blindSpots:e.coverage.blindSpots,incompleteReasons:e.coverage.status==="incomplete"?[e.coverage.explanation]:[],routeCatalog:a}),E=new Set(R.frontiers.flatMap(I=>I.edgeIds)),w=R.edges.filter(I=>I.disposition==="folded"&&!E.has(I.id)).map(I=>I.id);if(w.length>0)throw new Error(`Folded exploration edge(s) are not frontier-accounted: ${w.sort().join(", ")}`);return R}var Wv=10;function X_(e,t=[]){let n=new Map(e.nodes.map(h=>[h.id,h])),r=new Map(e.edges.map(h=>[h.id,h])),i=new Map;for(let h of e.edges){if(!Q_(h))continue;let b=i.get(h.toNodeId)??[];b.push(h),i.set(h.toNodeId,b)}for(let h of i.values())h.sort((b,S)=>Number(Jo(S))-Number(Jo(b))||Jv(S)-Jv(b)||b.fromNodeId.localeCompare(S.fromNodeId)||b.id.localeCompare(S.id));let o=lt(e.anchors.filter(h=>h.status==="matched").flatMap(h=>h.nodeIds)),s=new Map,a=new Set,c=(h,b,S)=>{let y=b.nodeIds[b.nodeIds.length-1],x=n.get(y),v=n.get(h);if(!x?.location||!v)return;let C=[...b.nodeIds].reverse(),R=[...b.edgeIds].reverse(),E=new Set(C),w=R.flatMap(L=>{let A=r.get(L);return A?[A]:[]}),I=e.edges.filter(L=>L.disposition!=="excluded"&&L.disposition!=="unsupported"&&(E.has(L.fromNodeId)||E.has(L.toNodeId))),k={id:yc("route",h,y,S,...R),status:"proved",anchorNodeId:h,anchorLabel:v.label,endpointNodeId:y,endpointLabel:x.label,endpointLocation:{...x.location},endpointKind:S,nodeIds:C,edgeIds:R,evidenceStrengths:lt(w.flatMap(L=>L.evidence.map(A=>A.strength))),spineEdgeFamilies:Vv(w,!0),relatedEdgeFamilies:Vv(I,!1),crossesRuntimeBoundary:w.some(Jo)},D=`${h}\0${y}\0${S}`,F=s.get(D);(!F||Yv(k,F)<0)&&s.set(D,k)};for(let h of o){n.get(h)?.attributes.publicEntry===!0&&c(h,{nodeIds:[h],edgeIds:[]},"public-entry");let b=[{nodeIds:[h],edgeIds:[]}],S=new Map([[h,0]]);for(let y=0;y<b.length;y+=1){let x=b[y],v=x.nodeIds[x.nodeIds.length-1];x.edgeIds.length>0&&n.get(v)?.location&&n.get(v)?.attributes.publicEntry===!0&&c(h,x,"public-entry");let C=i.get(v)??[];if(x.edgeIds.length>=Wv){C.some(R=>!x.nodeIds.includes(R.fromNodeId))&&a.add(h);continue}for(let R of C){if(x.nodeIds.includes(R.fromNodeId))continue;let E=x.edgeIds.length+1,w=S.get(R.fromNodeId);if(w!==void 0&&w<=E)continue;let I={nodeIds:[...x.nodeIds,R.fromNodeId],edgeIds:[...x.edgeIds,R.id]};if(S.set(R.fromNodeId,E),Jo(R)&&n.get(R.fromNodeId)?.location){c(h,I,"runtime-boundary");continue}b.push(I)}}}let l=[...s.values()].sort(Yv),u=new Set(l.map(h=>h.id)),d=lt(t.filter(h=>u.has(h))),m=lt(l.map(h=>h.anchorNodeId)),p=o.filter(h=>!m.includes(h)),f=[...a].sort(),g=e.coverage.status==="accounted"&&f.length===0?"accounted":"incomplete";return{schemaVersion:1,routes:l,selectedRouteIds:d,coverage:{status:g,scope:"Distinct proved public-entry and runtime-boundary endpoints reachable upstream in the supplied topology.",enumeration:"one-shortest-proved-path-per-endpoint",maximumDepth:Wv,anchorNodeIds:o,anchorsWithRoutes:m,anchorsWithoutRoutes:p,depthLimitedAnchorNodeIds:f,routeCount:l.length,explanation:g==="accounted"?"Every distinct proved upstream public/runtime endpoint in the supplied topology has one stable shortest route.":"Route enumeration is incomplete because the supplied topology has incomplete coverage or a traversal reached the route-depth bound."}}}function Vv(e,t){let n=e.flatMap(r=>r.semantics?.map(i=>i.family)??[]);return t&&e.length>0&&n.length===0&&n.push("control"),lt(n)}function Yv(e,t){return e.anchorNodeId.localeCompare(t.anchorNodeId)||e.edgeIds.length-t.edgeIds.length||e.endpointKind.localeCompare(t.endpointKind)||e.endpointNodeId.localeCompare(t.endpointNodeId)||e.id.localeCompare(t.id)}function Q_(e){return e.disposition!=="excluded"&&e.disposition!=="unsupported"&&Z_(e)&&e.evidence.some(t=>["exact","derived","mixed"].includes(t.strength))}function Z_(e){return Jo(e)||e.kind==="boundary-observation"||e.kind==="call"||e.kind==="compiler:call"}function Jo(e){return e.kind==="runtime-boundary"||e.kind.startsWith("runtime:")}function Jv(e){let t={exact:5,derived:4,mixed:3,candidate:1,unknown:0};return Math.max(0,...e.evidence.map(n=>t[n.strength]))}function Xv(e,t,n,r){return Qv(e,t,n,r)??Qv(e,n,t,r)}function Qv(e,t,n,r){let i=[...t.nodeIds,...t.candidateNodeIds].sort(),o=new Set([...n.nodeIds,...n.candidateNodeIds]);if(i.some(u=>o.has(u)))return{nodeIds:[i.find(d=>o.has(d))],edgeIds:[]};let s=new Set(e.nodes.filter(u=>u.kind==="structural-region").map(u=>u.id)),a=new Map;for(let u of e.edges)u.disposition==="excluded"||u.disposition==="unsupported"||u.kind==="structural-membership"||s.has(u.fromNodeId)||s.has(u.toNodeId)||u.evidence.every(m=>["candidate","unknown"].includes(m.strength))&&!r||eO(a,u.fromNodeId,u.toNodeId,u.id);for(let u of a.values())u.sort((d,m)=>d.nodeId.localeCompare(m.nodeId)||d.edgeId.localeCompare(m.edgeId));let c=i.map(u=>({nodeId:u,nodeIds:[u],edgeIds:[]})),l=new Set(i);for(let u=0;u<c.length;u+=1){let d=c[u];for(let m of a.get(d.nodeId)??[]){if(l.has(m.nodeId))continue;let p={nodeId:m.nodeId,nodeIds:[...d.nodeIds,m.nodeId],edgeIds:[...d.edgeIds,m.edgeId]};if(o.has(m.nodeId))return p;l.add(m.nodeId),c.push(p)}}return null}function eO(e,t,n,r){let i=e.get(t)??[];i.push({nodeId:n,edgeId:r}),e.set(t,i)}function tO(e,t,n){let r=new Map;for(let a of e.edges){let c=r.get(a.fromNodeId)??{incoming:0,outgoing:0},l=r.get(a.toNodeId)??{incoming:0,outgoing:0};c.outgoing+=1,l.incoming+=1,r.set(a.fromNodeId,c),r.set(a.toNodeId,l)}let i=new Set,o=new Map;for(let a of e.edges){let c=t.has(a.fromNodeId),l=t.has(a.toNodeId);if(c===l)continue;let u=c?a.toNodeId:a.fromNodeId,d=c?a.fromNodeId:a.toNodeId,m=e.nodes.find(g=>g.id===u);if(m?.kind==="structural-region")continue;let p=o.get(u)??new Set;p.add(d),o.set(u,p),(/(?:runtime-boundary|external)/u.test(a.kind)||m&&/(?:frontier|external)/u.test(m.kind))&&i.add(u)}let s=[...o].filter(([a,c])=>{if(i.has(a))return!0;let l=r.get(a)??{incoming:0,outgoing:0};return(l.incoming>1||l.outgoing>1)&&c.size>1}).sort(([a,c],[l,u])=>Number(i.has(l))-Number(i.has(a))||u.size-c.size||a.localeCompare(l)).map(([a])=>a);for(let a of s){if(t.size>=n)break;t.add(a)}}function Zv(e,t,n){let r=-1;for(;t.size!==r&&t.size<n;)r=t.size,tO(e,t,n)}function eC(e,t){let n=new Set(e.nodes.filter(s=>!t.has(s.id)&&s.disposition!=="excluded"&&s.disposition!=="unsupported").map(s=>s.id)),r=new Map;for(let s of e.edges){if(!n.has(s.fromNodeId)||!n.has(s.toNodeId))continue;let a=r.get(s.fromNodeId)??new Set,c=r.get(s.toNodeId)??new Set;a.add(s.toNodeId),c.add(s.fromNodeId),r.set(s.fromNodeId,a),r.set(s.toNodeId,c)}let i=[],o=new Set;for(let s of[...n].sort()){if(o.has(s))continue;let a=[],c=[s];o.add(s);for(let l=0;l<c.length;l+=1){let u=c[l];a.push(u);for(let d of[...r.get(u)??[]].sort())o.has(d)||(o.add(d),c.push(d))}i.push(a.sort())}return i.map(s=>{let a=new Set(s),c=e.edges.filter(f=>a.has(f.fromNodeId)||a.has(f.toNodeId)),l=c.filter(f=>a.has(f.fromNodeId)!==a.has(f.toNodeId)),u=lt(l.map(f=>a.has(f.fromNodeId)?f.toNodeId:f.fromNodeId)),d=new Set(l.map(f=>a.has(f.toNodeId)?"outgoing":"incoming")),m=lt(c.map(f=>f.id)),p=lt(l.map(f=>f.kind));return{id:yc("frontier",...s,...m),kind:p.join("+")||"disconnected",direction:d.size===1?[...d][0]:"undirected",fromNodeIds:u,edgeIds:m,memberNodeIds:s,memberCount:s.length,disposition:"folded",reason:l.length>0?"Connected evidence is folded beyond the first edge leaving the selected connector graph.":"Discovered evidence is disconnected from every selected anchor connector under the declared relation scope.",expansion:null}})}function yc(e,...t){let n=q_("sha256").update(t.join("\0")).digest("hex").slice(0,16);return`${e}:${n}`}function Ai(e,t){let n=[...e].sort((r,i)=>r.id.localeCompare(i.id));for(let r=1;r<n.length;r+=1)if(n[r-1].id===n[r].id)throw new Error(`Duplicate exploration ${t} id: ${n[r].id}`);return n}function gt(e,t,n,r){let i=lt(t.filter(o=>!n.has(o)));if(i.length>0)throw new Error(`Exploration ${e} references missing ${r}(s): ${i.join(", ")}`)}function tC(e){return{total:e.length,emitted:e.filter(t=>t.disposition==="emitted").length,folded:e.filter(t=>t.disposition==="folded").length,excluded:e.filter(t=>t.disposition==="excluded").length,unsupported:e.filter(t=>t.disposition==="unsupported").length}}function lt(e){return[...new Set(e)].sort()}var nO=5,rO=12,iO=8,oO=3,rC=8,sO=6,aO=12,iC=12,cO=12,lO=2,uO=new Set(["branch","loop","call","await","return","throw","mutation","catch","finally"]),dO=9e3,oC=pv,sC=new WeakMap;function mO(e,t){return yC(e,t,"full")}function hC(e,t){return yC(e,t,"topology")}function pO(e,t,n,r,i,o=!1){let s=e.get(t);if(s)return s.depth=Math.min(s.depth,n),s.primary||=i,s.promoteBoundaryImports||=o,s.origins.add(r),s;let a={file:t,depth:n,primary:i,promoteBoundaryImports:o,origins:new Set([r]),processed:!1};return e.set(t,a),a}function fO(e,t,n,r,i,o,s="none",a=!1){let c=e.get(n.symbol);if(c)return c.depth=Math.min(c.depth,r),c.origins.add(i),o&&c.anchorQueries.add(o),c.referenceScope=mB(c.referenceScope,s),t(n.relativePath,r,i,!0,a),c;let l={definition:n,depth:r,origins:new Set([i]),anchorQueries:new Set(o?[o]:[]),referenceScope:s,processed:!1};return e.set(n.symbol,l),t(n.relativePath,r,i,!0,a),l}function gO(e,t,n,r,i,o,s=!1,a=!0){let c=nn(n),l=e.get(c);if(l)return l.depth=Math.min(l.depth,r),l.origins.add(i),o&&l.anchorQueries.add(o),l.reverseCallExpansion||=s,l.traversalEligible||=a,t(n.file,r,i,l.traversalEligible,!0),l;let u={...n,depth:r,origins:new Set([i]),anchorQueries:new Set(o?[o]:[]),reverseCallExpansion:s,traversalEligible:a};return e.set(c,u),t(n.file,r,i,a,!0),u}function hO(e){let{db:t,index:n,pendingRelations:r,addFile:i,addSymbol:o,addSourceConstruct:s,observation:a,depth:c,origin:l}=e;i(a.source.file,c,l,!0,!0),a.owner.file!==a.source.file&&i(a.owner.file,c,`${l}:owner`,!0,!0);let u=U(t,a.owner.file),d=a.owner.symbol?cr(t,n,a.owner.symbol).matches.find(f=>f.relativePath===a.owner.file):null,m=(d&&!me(d.symbol)?d:null)??Ne(u,a.source.startLine);if(m&&!me(m.symbol))return o(m,c,l,void 0,"none",!0),m.symbol;a.owner.name&&s({file:a.owner.file,name:a.owner.name,startLine:a.owner.startLine,endLine:a.owner.endLine},c,`${l}:source-owner`,void 0,!0);let p=e.index.definitionsForFile(a.source.file).filter(f=>!!f.leaf&&fn(t,a.source.file,f.leaf).some(g=>g>=a.source.startLine&&g<=a.source.endLine));if(p.length===1){let f=p[0];o(f,c,`${l}:handler-identifier`,void 0,"none",!0),bt(r,{kind:"runtime-boundary",evidence:"runtime-boundary:handler-identifier",fromFile:a.source.file,fromSymbol:null,toFile:f.relativePath,toSymbol:f.symbol,fromBoundaryParticipant:Ni(a),line:a.source.startLine,strength:"derived"})}return null}function yO(e){let t=0,n=0,r=0;for(let i of e.searches){let o=YO(e.db,e.index,i,e.boundaryObservationLocations),s=o.filter(u=>eB(u,e.sourceAllowed)),a=!e.opts.fullLiteralTraversal&&(o.length>rO||s.length>iO),c=a?[]:o,l=new Set((a?[]:e.opts.fullLiteralTraversal?s:[...s].sort(JO).slice(0,oO)).map(dC));a&&(n+=1,r+=o.length);for(let u of c){let d=l.has(dC(u)),m=d&&!u.ownerSymbol&&u.ownerStartLine!==null&&u.ownerEndLine!==null;if(e.addFile(u.relativePath,0,`${d?"literal-anchor":"literal-match"}:${i}`,m,m),m&&e.addSourceConstruct({file:u.relativePath,name:u.ownerShortName??`${u.relativePath}:${u.ownerStartLine+1}`,startLine:u.ownerStartLine,endLine:u.ownerEndLine},0,`literal-source-owner:${i}`,i,!0),d&&u.ownerSymbol){let p=cr(e.db,e.index,u.ownerSymbol).matches[0];p&&!me(p.symbol)&&e.addSymbol(p,0,"literal-owner",i,"all",!0)}e.literalHits.push({query:i,file:u.relativePath,line:u.line,ownerSymbol:u.ownerSymbol,ownerShortName:u.ownerShortName,ownerStartLine:u.ownerStartLine,ownerEndLine:u.ownerEndLine,sourceLine:u.sourceLine.trim(),matchKind:u.matchKind,traversalSeed:d})}e.anchors.push({kind:"literal",query:i,status:o.length>0?"matched":"missing",matchedRegionIds:[],matchingLines:o.length,seedMatchingLines:a?0:l.size,matchOnlyLines:o.length-l.size,eligibleSeedMatchingLines:s.length,materializedMatchingLines:c.length,withheldMatchingLines:a?o.length:0,literalTraversal:a?"withheld-broad":"materialized",representativeMatches:a?tB(i,o):void 0,narrowingCommands:a?rB(i,o):void 0,exhaustiveTraversalCommand:a||l.size<s.length?`scip-query system-map --search ${ye(i)} --full-literal-traversal`:void 0,seedRegionIds:[],matchOnlyRegionIds:[]})}for(let i of e.symbolQueries){let o=cr(e.db,e.index,i);t+=o.omitted;let s=XO(e.db,i),a=o.matches.filter(m=>!me(m.symbol)),c=s!==null&&a.length===0;c&&e.addSourceConstruct(s,0,"source-construct-anchor",i,!0);let l=c?a:o.matches;for(let m of l)e.addSymbol(m,0,"symbol-anchor",i,"all",!0);let u=c?QO(s):null,d=c?1:o.total;e.anchors.push({kind:"symbol",query:i,status:d===0?"missing":d===1?"matched":"ambiguous",matchedRegionIds:[],symbolCandidates:[...u?[u]:[],...l.map(cB)],totalSymbolCandidates:d,omittedSymbolCandidates:o.omitted})}return{omittedSymbolCandidates:t,broadLiteralAnchors:n,withheldLiteralMatches:r}}function bO(e){let{db:t,opts:n,mode:r,searches:i,symbolQueries:o,maxDepth:s,maxTopologyCharacters:a,requestedRelationKinds:c,evidenceFloor:l,includedSourceScopes:u,workspaces:d,runtimeBoundaries:m,boundaryObservations:p,representedBoundaryLinkIds:f,files:g,symbols:h,sourceConstructs:b,literalHits:S,pendingRelations:y,externalImports:x,anchors:v,omittedSymbolCandidates:C,broadLiteralAnchors:R,withheldLiteralMatches:E,filteredUnverifiedCallEdges:w,memberCallCandidateEdges:I,unresolvedMemberCallsites:k,sourceAllowed:D}=e,F=new Set(c),L=new Map;for(let _ of g.keys())L.set(_,Xo(_,d));let A=[...y.values()].filter(_=>L.has(_.fromFile)&&L.has(_.toFile)).map(_=>({..._,fromRegionId:L.get(_.fromFile).id,toRegionId:L.get(_.toFile).id})).sort(CC),P=CB(A),j=new Set(n.expand??[]),B=yB(g,h,S,A,P,L,j),X=new Set([...g.values()].filter(_=>[..._.origins].some(ce=>ce.startsWith("literal-anchor:")||ce==="literal-owner"||ce==="symbol-anchor")).map(_=>L.get(_.file).id)),G=KO(B),O=new Set(B.map(_=>_.id)),te=[...j].filter(_=>!O.has(_)).sort();for(let _ of v)if(_.matchedRegionIds=RB(_,S,h,L),_.kind==="literal"){let ce=S.filter(Be=>Be.query===_.query);_.seedRegionIds=pe(ce.filter(Be=>Be.traversalSeed).map(Be=>L.get(Be.file).id)),_.matchOnlyRegionIds=pe(ce.filter(Be=>!Be.traversalSeed).map(Be=>L.get(Be.file).id))}let ie=[...h.values()].filter(_=>!_.processed).length,we=[...g.values()].filter(_=>_.primary&&!_.processed).length,De=[...g.values()].filter(_=>!_.primary&&!_.processed).length,Ft=[...h.values()].filter(_=>_.processed),tt=(m?.frontiers??[]).flatMap(_=>{let ce=p.get(_.observationId);return!ce&&_.source&&_.action&&_.strength?!F.has("runtime-boundary")||!D(_.source.file)||l==="exact"||!g.has(_.source.file)?[]:[{observationId:_.observationId,action:_.action,strength:_.strength,file:_.source.file,line:_.source.startLine,ownerShortName:_.ownerShortName??null,address:_.address??_.missingKeyParts.join(", "),reason:_.reason}]:!F.has("runtime-boundary")||!ce||!D(ce.source.file)||l==="exact"&&ce.strength!=="exact"||!g.has(ce.source.file)?[]:[{observationId:ce.id,action:ce.action,strength:ce.strength,file:ce.source.file,line:ce.source.startLine,ownerShortName:ce.owner.name,address:vC(ce),reason:_.reason,protocol:ce.protocol,role:ce.role,modality:ce.modality,resolution:ce.resolution,sourceScope:ce.sourceScope,keyParts:ce.keyParts.map(Be=>({name:Be.name,value:Be.value,evidence:Be.evidence}))}]}).sort((_,ce)=>_.file.localeCompare(ce.file)||_.line-ce.line),M=(m?.links??[]).filter(_=>{if(!F.has("runtime-boundary")||l==="exact"&&_.strength!=="exact")return!1;let ce=p.get(_.from),Be=p.get(_.to);return!!(ce&&Be&&D(ce.source.file)&&D(Be.source.file)&&(g.has(ce.source.file)||g.has(Be.source.file)))}),$=M.filter(_=>_.strength==="exact").length,Y=M.filter(_=>_.strength==="derived").length,oe=M.filter(_=>_.strength==="candidate").length,Ae=m?.links.filter(_=>_.strength==="exact").length??0,Ut=m?.links.filter(_=>_.strength==="derived").length??0,Jr=m?.links.filter(_=>_.strength==="candidate").length??0,gr=xB(x,L),ll=C===0?"accounted":"incomplete",Tp=[...R>0?[`${R} broad literal anchor(s) withheld ${E} exact match(es) before graph traversal; representative identities and scoped search commands preserve recovery without treating every textual occurrence as relevant.`]:[],`Literal matches outside the included source scopes (${u.join(", ")}) remain visible as match-only evidence and do not seed traversal.`,m?"Built-in runtime-boundary extractors traverse direct and replayably derived links; heuristic candidates, unsupported frameworks, reflection, generated names, and dependency wiring not recoverable from compiler occurrences or constructor assignments remain disclosed frontiers.":"Runtime-boundary evidence is unavailable for this index; run scip-query reindex with this build to extract supported HTTP, event, registry, and persistence observations.","Reverse references do not recursively expand from discovered callers or callees.","Member calls use compiler occurrences, exact constructor-assigned fields, bounded unique service providers, direct factory-return members, and compiler-resolved object-literal callbacks when available. Ambiguous providers remain candidate frontiers; callback values routed through mutation, reflection, or unsupported dependency containers remain unrepresented.","Literal traversal is bounded to the smallest parser-delimited source construct; parser gaps may reduce an owner to one source line and leave its continuation untraversed.","Schema consumers stay within forward-flow regions; cross-workspace contracts may discover consumers in other workspaces. Add an explicit symbol anchor to widen either scope.",`Traversal stops after depth ${s}; nonzero frontier counts identify evidence that was discovered but not traversed.`,"Region labels are structural path groupings, not inferred runtime or architectural boundaries."],St=NO({db:t,anchors:v,regions:B,symbolStates:h,sourceConstructStates:b,literalHits:S,relations:A,externalBoundaries:gr,boundaryFrontiers:tt,regionForFile:L,closureStatus:ll,omittedSymbolCandidates:C,maxDepth:s,requestedRelationKinds:c,evidenceFloor:l,includedSourceScopes:u,blindSpots:Tp,topologyFrontiers:n.topologyFrontiers??[],routeIds:n.routeIds??[],expandedRegionIds:[...j],maxTopologyCharacters:a,fullLiteralTraversal:n.fullLiteralTraversal??!1});if(r==="topology")return St;let kp=(n.behaviorFocusLocations?.length??0)>0?new Set([...St.anchors.flatMap(_=>_.nodeIds),...St.paths.flatMap(_=>_.nodeIds)]).size:void 0,Is=fS(t,St,{focusLocations:n.behaviorFocusLocations,...kp?{maxSteps:kp}:{}});KS(t,St,Is);let QI=RO(t,St,Is,n.behaviorFocusLocations??[]);St.corridor=qv(St,{focusLocations:QI});let Ap=zS(t,St,Is,{sourceAllowed:D,selectionTerms:n.selectionTerms}),Fp=jO(St),ZI=GO(i,o,s,c,l,u,n.fullLiteralTraversal??!1,a,B,P,X,j,Fp),ew=qO(i,o,s,B.filter(_=>Fp.has(_.id)),X,c,l,u,n.fullLiteralTraversal??!1,a);return{anchors:v,regions:B,regionRelations:P,externalBoundaries:gr,boundaryFrontiers:tt,unmatchedExpansions:te,expansion:ew,drilldown:G,presentation:ZI,topology:St,behavior:Is,nextAnchors:Ap,closure:{status:ll,emitted:{regions:B.length,relations:A.length,runtimeLinks:f.size},withheld:{symbols:ie,files:we+De,regions:St.nodes.filter(_=>_.kind==="structural-region"&&_.disposition==="folded").length,drillAnchors:(G?.omittedAnchors??0)+Ap.omittedAnchors,literalMatches:E},ambiguous:{anchors:v.filter(_=>_.status==="ambiguous").length,omittedSymbolCandidates:C},external:gr.length,unresolved:tt.length,explanation:ll==="accounted"?"Every fact reached under the declared anchors, relations, depth, evidence floor, source scopes, and installed analyzers is accounted for as emitted, withheld, ambiguous, external, or unresolved.":"Some ambiguous symbol candidates were not identified, so the declared query is not fully accounted for."},coverage:{explicitAnchorCount:v.length,requestedRelationKinds:c,evidenceFloor:l,includedSourceScopes:u,matchedAnchorCount:v.filter(_=>_.status!=="missing").length,literalSearchesComplete:!0,broadLiteralAnchors:R,withheldLiteralMatches:E,symbolCandidateSetsComplete:C===0,omittedSymbolCandidates:C,maxTraversalDepth:s,frontierSymbols:ie,frontierFiles:we,supportFilesNotTraversed:De,filteredUnverifiedCallEdges:w,memberCallCandidateEdges:I,unresolvedMemberCallsites:k,runtimeBoundaryEvidenceAvailable:m!==null,runtimeBoundaryObservations:m?.observations.length??0,runtimeBoundaryExactLinks:$,runtimeBoundaryDerivedLinks:Y,runtimeBoundaryCandidateLinks:oe,repositoryRuntimeBoundaryExactLinks:Ae,repositoryRuntimeBoundaryDerivedLinks:Ut,repositoryRuntimeBoundaryCandidateLinks:Jr,runtimeBoundaryTraversedLinks:f.size,runtimeBoundaryFrontiers:tt.length,referenceExpansionEligibleSymbols:Ft.filter(_=>_.referenceScope!=="none").length,referenceExpansionSkippedSymbols:Ft.filter(_=>_.referenceScope==="none").length,dynamicDispatchRepresented:m?.links.some(_=>_.joinRule==="carrier.discriminator"&&f.has(_.id))??!1,runtimeGeneratedLinksRepresented:m!==null,regionBoundariesAreStructural:!0,relationFamilies:{"literal-anchor":{evidence:"exact-source",scope:"all indexed documents for each explicit literal",completeWithinScope:!0},reference:{evidence:"compiler-graph",scope:"all cross-file indexed/source-attributed sites for explicit anchors and promoted non-module boundary symbols",completeWithinScope:!0},call:{evidence:"mixed",scope:"static callees plus exact SCIP call occurrences in traversed source ranges, exact constructor-assigned member receivers, and uniquely attributed direct-import member candidates",completeWithinScope:!0},"contract-symbol":{evidence:"compiler-graph",scope:"compiler-resolved symbol identities referenced across inferred workspace boundaries",completeWithinScope:!0},import:{evidence:"compiler-graph",scope:"all indexed or source-resolved imports of traversed primary files",completeWithinScope:!0},"runtime-boundary":{evidence:"exact-source",scope:"direct and mechanically derived links produced by grounded runtime adapters and factorized relation groups",completeWithinScope:!0}},blindSpots:Tp}}}function SO(e,t){let{db:n,relationPolicy:r,sourceConstructs:i,reverseExpandedSourceConstructs:o,pendingRelations:s,reverseFileGraph:a,serviceCallerFilesBySourceConstruct:c,sourceAllowed:l,memberCallTargetsForWholeFile:u,addSymbol:d,addSourceConstruct:m}=e;if(r.has("call")){let p=[...i.values()].filter(f=>f.traversalEligible&&f.reverseCallExpansion&&f.depth<=t&&!o.has(nn(f)));for(let f of p){o.add(nn(f));let g=K(n,f.file);if((g?.callables??[]).filter(S=>S.name===f.name&&S.startLine<=f.endLine&&S.endLine>=f.startLine).length===1){let S=(g?.callSites??[]).filter(y=>y.calleeLeaf===f.name&&!y.memberAccess);for(let y of S){let x=t+1,v=Ne(U(n,f.file),y.line),C=null,R=null;if(v&&!me(v.symbol)){if(v.relativePath===f.file&&v.startLine<=f.endLine&&v.endLine>=f.startLine)continue;d(v,x,"reverse-local-call-owner",void 0,"forward-regions",!0),C=v.symbol}else{let E=Ud(n,f.file,y.line);E&&nn(E)!==nn(f)&&(R=m(E,x,"reverse-local-call-source-owner",void 0,!0))}!C&&!R||bt(s,{kind:"call",evidence:"ast-callsite",fromFile:f.file,fromSymbol:C,toFile:f.file,toSymbol:null,fromSourceConstruct:R?ut(R):void 0,toSourceConstruct:ut(f),line:y.line,strength:"derived"})}}let b=new Set([...a.get(f.file)??[],...c.get(nn(f))??[],...eS(n,f.file).flatMap(S=>[...a.get(S)??[]])]);for(let S of b){if(!l(S))continue;let x=u(S).targets.filter(v=>v.targetFile===f.file&&v.targetStartLine<=f.endLine&&v.targetEndLine>=f.startLine);for(let v of x){let C=t+1,R=Ne(U(n,S),v.line),E=null,w=null;if(R&&!me(R.symbol))d(R,C,"reverse-member-call-owner",void 0,"cross-workspace-or-forward",!0),E=R.symbol;else{let I=Ud(n,S,v.line);I&&(w=m(I,C,"reverse-member-call-source-owner",void 0,!0))}!E&&!w||bt(s,{kind:"call",evidence:"ast-service-member-callsite",fromFile:S,fromSymbol:E,toFile:f.file,toSymbol:null,fromSourceConstruct:w?ut(w):void 0,toSourceConstruct:ut(f),line:v.line,strength:v.strength==="exact"?"exact":"derived"})}}}}}function vO(e,t){let{db:n,index:r,relationPolicy:i,symbols:o,sourceAllowed:s,files:a,workspaces:c,addFile:l,addSymbol:u,addSourceConstruct:d,pendingRelations:m,fileGraph:p,traversalMetrics:f}=e,g=[...o.values()].filter(b=>!b.processed&&b.depth<=t),h=i.has("call")?r.calleeMap(g.map(b=>b.definition),{additive:!1,semantic:!1}):new Map;for(let b of g){b.processed=!0;let S=b.definition;if(b.referenceScope!=="none"&&(i.has("call")||i.has("reference")||i.has("contract-symbol"))){let y=oB(n,r,S).filter(v=>s(v.file)&&dB(b,v.file,a,c)),x=new Set(y.flatMap(v=>{if(!(i.has("call")&&K(n,v.file)?.callSites.some(E=>E.line===v.line&&aC(n,v.file,E,S))===!0)||!v.enclosingSymbol)return[];let R=cr(n,r,v.enclosingSymbol).matches[0];return R&&!me(R.symbol)?[{owner:R,site:v}]:[]}).sort((v,C)=>{let R=ht(S.relativePath,c).relativeDir,E=ht(v.owner.relativePath,c).relativeDir===R,w=ht(C.owner.relativePath,c).relativeDir===R,I=cC(n,v.owner),k=cC(n,C.owner),D=v.owner.endLine-v.owner.startLine,F=C.owner.endLine-C.owner.startLine;return Number(w)-Number(E)||k-I||D-F||v.owner.symbol.localeCompare(C.owner.symbol)}).filter((v,C,R)=>R.findIndex(E=>E.owner.symbol===v.owner.symbol)===C).reduce((v,C)=>{if(v.length>=lO)return v;let R=ht(C.owner.relativePath,c).relativeDir;return v.some(E=>E.workspace===R)||v.push({symbol:C.owner.symbol,workspace:R}),v},[]).map(v=>v.symbol));for(let v of y){let C=t+1;l(v.file,C,`reference:${T(S.symbol)}`,!0);let R=i.has("call")&&K(n,v.file)?.callSites.some(I=>I.line===v.line&&aC(n,v.file,I,S))===!0,E=null,w=null;if(v.enclosingSymbol){let I=cr(n,r,v.enclosingSymbol).matches[0];I&&!me(I.symbol)&&(u(I,C,"reference-owner",void 0,R&&x.has(I.symbol)?b.referenceScope:"none"),E=I.symbol)}if(!E&&v.line!==null){let I=Ud(n,v.file,v.line);I&&(w=d(I,C,"reference-source-owner",void 0,R))}i.has("reference")&&bt(m,{kind:"reference",evidence:"indexed-or-source-reference",fromFile:v.file,fromSymbol:E,toFile:S.relativePath,toSymbol:S.symbol,fromSourceConstruct:w?ut(w):void 0,line:v.line,strength:"mixed"}),R&&bt(m,{kind:"call",evidence:"ast-callsite",fromFile:v.file,fromSymbol:E,toFile:S.relativePath,toSymbol:S.symbol,fromSourceConstruct:w?ut(w):void 0,line:v.line,strength:"derived"}),i.has("contract-symbol")&&ht(v.file,c).relativeDir!==ht(S.relativePath,c).relativeDir&&bt(m,{kind:"contract-symbol",evidence:"compiler-cross-workspace-symbol",fromFile:v.file,fromSymbol:E,toFile:S.relativePath,toSymbol:S.symbol,fromSourceConstruct:w?ut(w):void 0,line:v.line,strength:"exact"})}}for(let y of h.get(S.symbolId)??[]){let x=cr(n,r,y.symbol).matches.find(C=>C.relativePath===y.file);if(!x||!s(x.relativePath))continue;if(!(x.relativePath===S.relativePath||(p.get(S.relativePath)??new Set).has(x.relativePath))){f.filteredUnverifiedCallEdges+=1;continue}u(x,t+1,`call:${T(S.symbol)}`,void 0,"none",!0),bt(m,{kind:"call",evidence:y.source,fromFile:S.relativePath,fromSymbol:S.symbol,toFile:x.relativePath,toSymbol:x.symbol,line:null,strength:UO(y.source)})}}}function CO(e,t){let{db:n,index:r,relationPolicy:i,files:o,sourceConstructs:s,symbols:a,boundaryObservations:c,boundaryObservationDepths:l,sourceAllowed:u,addSymbol:d,pendingRelations:m,traversalMetrics:p,addSourceConstruct:f,serviceCallerFilesBySourceConstruct:g,reverseFileGraph:h,externalImports:b,addFile:S,workspaces:y}=e,x=[...o.values()].filter(v=>!v.processed&&v.primary&&v.depth<=t);for(let v of x){v.processed=!0;let C=[...s.values()].filter(P=>P.traversalEligible&&P.file===v.file&&P.depth<=t),R=[...a.values()].filter(P=>P.definition.relativePath===v.file&&P.depth<=t).map(P=>{let j=fi(n,v.file,P.definition.startLine);return{startLine:j?.startLine??P.definition.startLine,endLine:j?.endLine??P.definition.endLine}}),E=P=>[...a.values()].filter(j=>j.definition.relativePath===v.file&&j.definition.startLine<=P&&j.definition.endLine>=P).sort((j,B)=>j.definition.endLine-j.definition.startLine-(B.definition.endLine-B.definition.startLine)||j.definition.startLine-B.definition.startLine)[0],w=[...c.values()].filter(P=>P.source.file===v.file&&l.has(P.id)),I=[...C.map(P=>({startLine:P.startLine,endLine:P.endLine})),...w.map(P=>({...Sc(n,P)}))],k=[...R,...I],D=(K(n,v.file)?.callSites??[]).filter(P=>k.some(j=>P.line>=j.startLine&&P.line<=j.endLine)),F=new Set;if(i.has("call"))for(let P of k){let j=Rn(n,v.file,P.startLine,P.endLine);for(let B of j.targets){if(!u(B.definition.relativePath))continue;let X=E(B.sourceLine),G=C.find(te=>te.startLine<=B.sourceLine&&te.endLine>=B.sourceLine),O=w.find(te=>{let ie=Sc(n,te);return ie.startLine<=B.sourceLine&&ie.endLine>=B.sourceLine});d(B.definition,t+1,`scip-occurrence-call:${v.file}:${B.sourceLine+1}`,void 0,"none",!0),bt(m,{kind:"call",evidence:"scip-occurrence-callsite",fromFile:v.file,fromSymbol:X?.definition.symbol??null,toFile:B.definition.relativePath,toSymbol:B.definition.symbol,fromBoundaryParticipant:O?Ni(O):void 0,fromSourceConstruct:G?ut(G):void 0,line:B.sourceLine,strength:"exact"}),F.add(`${B.sourceLine}\0${B.calleeLeaf}`)}}if(i.has("reference"))for(let P of k){let j=aS(n,v.file,P.startLine,P.endLine);for(let B of j.targets){if(!u(B.definition.relativePath)||F.has(`${B.sourceLine}\0${B.calleeLeaf}`))continue;let X=E(B.sourceLine);if(X?.definition.symbol===B.definition.symbol)continue;let G=C.find(te=>te.startLine<=B.sourceLine&&te.endLine>=B.sourceLine),O=w.find(te=>{let ie=Sc(n,te);return ie.startLine<=B.sourceLine&&ie.endLine>=B.sourceLine});d(B.definition,t+1,`scip-occurrence-reference:${v.file}:${B.sourceLine+1}`,void 0,"none",!0),bt(m,{kind:"reference",evidence:"scip-occurrence-reference",fromFile:v.file,fromSymbol:X?.definition.symbol??null,toFile:B.definition.relativePath,toSymbol:B.definition.symbol,fromBoundaryParticipant:O?Ni(O):void 0,fromSourceConstruct:G?ut(G):void 0,line:B.sourceLine,strength:"exact"})}}let L=i.has("call")?nr(n,v.file,{ranges:k,excludeIndexedTargets:!1}):{targets:[],unresolvedCallsites:0};p.unresolvedMemberCallsites+=L.unresolvedCallsites;let A=L.targets.filter(P=>!F.has(`${P.line}\0${P.calleeLeaf}`));p.memberCallCandidateEdges+=A.filter(P=>P.strength!=="exact"&&(P.resolution!=="imported-service-object-member"||(P.resolutionAlternativeCount??0)>1)).length;for(let P of A){let j=(P.resolutionAlternativeCount??1)===1,B=P.targetSymbol?U(n,P.targetFile).find(ie=>ie.symbol===P.targetSymbol):void 0,X=B?null:f({file:P.targetFile,name:P.calleeLeaf,startLine:P.targetStartLine,endLine:P.targetEndLine},t+1,`member-call:${v.file}`,void 0,P.resolution==="imported-service-object-member"&&j,j);if(X&&P.serviceFile){let ie=nn(X),we=g.get(ie)??new Set;for(let De of h.get(P.serviceFile)??[])we.add(De);g.set(ie,we)}B&&d(B,t+1,`member-call:${v.file}`,void 0,"none",!0);let G=C.find(ie=>ie.startLine<=P.line&&ie.endLine>=P.line),O=E(P.line),te=w.find(ie=>{let we=Sc(n,ie);return we.startLine<=P.line&&we.endLine>=P.line});bt(m,{kind:"call",evidence:P.resolution==="constructed-member-receiver"?"ast-constructed-member-callsite":P.resolution==="factory-callback-member"?"ast-factory-callback-callsite":P.resolution==="imported-service-object-member"?"ast-service-member-callsite":"ast-member-import-candidate",fromFile:v.file,fromSymbol:O?.definition.symbol??null,toFile:P.targetFile,toSymbol:B?.symbol??null,fromBoundaryParticipant:te?Ni(te):void 0,fromSourceConstruct:G?ut(G):void 0,toSourceConstruct:X?ut(X):void 0,line:P.line,strength:P.resolution==="imported-service-object-member"?(P.resolutionAlternativeCount??0)===1?"derived":"candidate":P.strength??"candidate"})}for(let P of i.has("import")||i.has("call")?sB(n,v.file):[]){if(!P.fromFile){if(i.has("import")){let B=b.get(P.shortName)??{name:P.shortName,fromFiles:new Set};B.fromFiles.add(v.file),b.set(P.shortName,B)}continue}if(!u(P.fromFile))continue;if(i.has("import")&&(S(P.fromFile,t+1,`import:${v.file}`,!1),bt(m,{kind:"import",evidence:"indexed-or-source-import",fromFile:v.file,fromSymbol:null,toFile:P.fromFile,toSymbol:P.symbol,line:null,strength:"mixed"})),i.has("call")&&D.length>0){let B=(P.source==="compiler"?cr(n,r,P.symbol).matches:qn(n,P.fromFile,P.importedName)).filter(X=>!me(X.symbol));for(let X of B){let G=D.filter(O=>O.calleeLeaf===P.localName).map(O=>O.line);if(G.length!==0){d(X,t+1,`source-call:${v.file}`,void 0,"none",!0);for(let O of G)bt(m,{kind:"call",evidence:"ast-callsite",fromFile:v.file,fromSymbol:null,toFile:X.relativePath,toSymbol:X.symbol,line:O,strength:"derived"})}}}if(!v.promoteBoundaryImports||!lB(v.file,P.fromFile,y))continue;let j=cr(n,r,P.symbol);for(let B of j.matches)if(uB(B.relativePath,P.fromFile,y)&&!me(B.symbol)){let X=ht(v.file,y).relativeDir!==ht(B.relativePath,y).relativeDir;d(B,t+1,`boundary-import:${v.file}`,void 0,X?"cross-workspace-or-forward":"forward-regions")}}}}function xO(e,t){let{relationPolicy:n,runtimeBoundaries:r,evidenceFloor:i,representedBoundaryLinkIds:o,boundaryObservations:s,sourceAllowed:a,boundaryObservationDepths:c,symbols:l,sourceConstructs:u,addBoundaryObservation:d,pendingRelations:m}=e;for(let p of n.has("runtime-boundary")?r?.links??[]:[]){if(p.strength==="candidate"||i==="exact"&&p.strength!=="exact"||o.has(p.id))continue;let f=s.get(p.from),g=s.get(p.to);if(!f||!g||!a(f.source.file)||!a(g.source.file))continue;let h=fC(f,t,c,l,u),b=fC(g,t,c,l,u);if(h===null&&b===null)continue;let S=t+1,y=d(f,h??S,`runtime-boundary:${p.joinRule}`),x=d(g,b??S,`runtime-boundary:${p.joinRule}`),v=y?null:pC(u,f),C=x?null:pC(u,g);c.set(f.id,h??S),c.set(g.id,b??S),bt(m,{kind:"runtime-boundary",evidence:`runtime-boundary:${p.joinRule}`,fromFile:f.source.file,fromSymbol:y,toFile:g.source.file,toSymbol:x,fromBoundaryParticipant:Ni(f),toBoundaryParticipant:Ni(g),fromSourceConstruct:v?ut(v):void 0,toSourceConstruct:C?ut(C):void 0,runtimeBoundaryKey:p.matchedKeyParts.map(R=>`${R.name}=${R.value}`).join(" "),line:f.source.startLine,strength:p.strength}),o.add(p.id)}}function yC(e,t,n){let r=ke(t.searches??[]),i=ke(t.symbols??[]),o=ke(t.relations&&t.relations.length>0?t.relations:oC),s=o.filter($=>!oC.includes($));if(s.length>0)throw new Error(`Unsupported system-map relation kind(s): ${s.join(", ")}`);let a=new Set(o),c=t.evidenceFloor??"derived";if(c!=="exact"&&c!=="derived")throw new Error(`Unsupported system-map evidence floor: ${c}`);let l=ke(t.sourceScopes&&t.sourceScopes.length>0?t.sourceScopes:["production"]),u=["production","test","fixture","example","generated","script","unknown"],d=l.filter($=>!u.includes($));if(d.length>0)throw new Error(`Unsupported system-map source scope(s): ${d.join(", ")}`);let m=new Set(l),p=$=>m.has(Il($));if(r.length===0&&i.length===0)throw new Error("system-map requires at least one --search or --symbol anchor.");let f=t.maxDepth??nO;if(!Number.isSafeInteger(f)||f<0)throw new RangeError(`maxDepth must be a non-negative safe integer; received ${f}`);let g=t.maxTopologyCharacters??dO;if(!Number.isSafeInteger(g)||g<=0)throw new RangeError(`maxTopologyCharacters must be a positive safe integer; received ${g}`);let h=new H(e),{fileGraph:b,reverseFileGraph:S,workspaces:y,runtimeBoundaries:x}=pB(e,h),v=new Map((x?.observations??[]).map($=>[$.id,$])),C=new Set((x?.observations??[]).map($=>`${$.source.file}\0${$.source.startLine}`)),R=new Set,E=new Map,w=new Map,I=new Map,k=new Map,D=[],F=new Map,L=new Map,A=[],P={filteredUnverifiedCallEdges:0,memberCallCandidateEdges:0,unresolvedMemberCallsites:0},j=new Set,B=new Map,X=new Map,G=$=>{let Y=X.get($);if(Y)return Y;let oe=nr(e,$,{excludeIndexedTargets:!1});return X.set($,oe),oe},O=($,Y,oe,Ae,Ut=!1)=>pO(w,$,Y,oe,Ae,Ut),te=($,Y,oe,Ae,Ut="none",Jr=!1)=>fO(I,O,$,Y,oe,Ae,Ut,Jr),ie=($,Y,oe,Ae,Ut=!1,Jr=!0)=>gO(k,O,$,Y,oe,Ae,Ut,Jr),we=($,Y,oe)=>hO({db:e,index:h,pendingRelations:F,addFile:O,addSymbol:te,addSourceConstruct:ie,observation:$,depth:Y,origin:oe}),{omittedSymbolCandidates:De,broadLiteralAnchors:Ft,withheldLiteralMatches:tt}=yO({db:e,index:h,searches:r,symbolQueries:i,opts:t,boundaryObservationLocations:C,sourceAllowed:p,addFile:O,addSymbol:te,addSourceConstruct:ie,literalHits:D,anchors:A}),M={db:e,index:h,relationPolicy:a,evidenceFloor:c,sourceAllowed:p,fileGraph:b,reverseFileGraph:S,workspaces:y,runtimeBoundaries:x,boundaryObservations:v,boundaryObservationDepths:E,representedBoundaryLinkIds:R,files:w,symbols:I,sourceConstructs:k,pendingRelations:F,externalImports:L,reverseExpandedSourceConstructs:j,serviceCallerFilesBySourceConstruct:B,traversalMetrics:P,memberCallTargetsForWholeFile:G,addFile:O,addSymbol:te,addSourceConstruct:ie,addBoundaryObservation:we};for(let $=0;$<f;$+=1)SO(M,$),vO(M,$),CO(M,$),xO(M,$);return bO({db:e,opts:t,mode:n,searches:r,symbolQueries:i,maxDepth:f,maxTopologyCharacters:g,requestedRelationKinds:o,evidenceFloor:c,includedSourceScopes:l,workspaces:y,runtimeBoundaries:x,boundaryObservations:v,representedBoundaryLinkIds:R,files:w,symbols:I,sourceConstructs:k,literalHits:D,pendingRelations:F,externalImports:L,anchors:A,omittedSymbolCandidates:De,broadLiteralAnchors:Ft,withheldLiteralMatches:tt,filteredUnverifiedCallEdges:P.filteredUnverifiedCallEdges,memberCallCandidateEdges:P.memberCallCandidateEdges,unresolvedMemberCallsites:P.unresolvedMemberCallsites,sourceAllowed:p})}function RO(e,t,n,r){let i=new Map,o=c=>{i.set(`${c.file}\0${c.line}`,c)};for(let c of r)o(c);let s=new Set(t.anchors.filter(c=>c.status==="matched").flatMap(c=>c.nodeIds));for(let c of n.steps)if(!(!c.location||!s.has(c.nodeId)||(c.behavior?.rawCharacters??1/0)>3e3))for(let l of c.behavior?.lines??[])l.signals.some(u=>uO.has(u))&&o({file:c.location.file,line:l.line,endLine:l.endLine});let a=t.edges.filter(c=>c.disposition==="emitted").flatMap(c=>c.evidence.flatMap(l=>l.location?[l.location]:[]));for(let c of a){o(c);let l=t.nodes.filter(d=>d.location?.file===c.file&&["symbol","source-construct","runtime-boundary-participant"].includes(d.kind)&&d.location.line<=c.line&&(d.location.endLine??d.location.line)>=c.line).sort((d,m)=>(d.location.endLine??d.location.line)-d.location.line-((m.location.endLine??m.location.line)-m.location.line)||d.id.localeCompare(m.id))[0];if(!l?.location)continue;let u=sa(e,c.file,l.location.line,l.location.endLine??l.location.line,[c.line]);for(let d of u)o({file:c.file,line:d.line,endLine:d.endLine})}return[...i.values()].sort((c,l)=>c.file.localeCompare(l.file)||c.line-l.line)}function EO(e){if(e.ownerStartLine===null||e.ownerStartLine===void 0)throw new Error(`Literal hit ${e.file}:${e.line+1} has no source-owner start line.`);if(e.ownerEndLine===null||e.ownerEndLine===void 0)throw new Error(`Literal hit ${e.file}:${e.line+1} has no source-owner end line.`);return{file:e.file,name:e.ownerShortName??`${e.file}:${e.ownerStartLine+1}`,startLine:e.ownerStartLine,endLine:e.ownerEndLine}}function nn(e){return`${e.file}\0${e.startLine}\0${e.endLine}\0${e.name}`}function ut(e){return{file:e.file,name:e.name,startLine:e.startLine,endLine:e.endLine}}function aC(e,t,n,r){if(n.calleeLeaf===r.leaf)return!0;let i=ri(e,t,n.calleeLeaf);return i!==null&&i.importedName===r.leaf&&i.sourcePath!==null&&Fe(i.sourcePath,r.relativePath)}function vc(e,t){let n=Nn(K(e,t.file)?.callables??[],t.startLine);if(n&&n.endLine>=t.endLine)return{file:t.file,name:/^source@\d+$/u.test(n.name)&&!/^source@\d+$/u.test(t.name)?t.name:n.name,startLine:n.startLine,endLine:n.endLine};let r=SC(e,t.file,t.startLine);return r&&r.endLine>=t.endLine?{file:t.file,name:r.name,startLine:r.startLine,endLine:r.endLine}:ut(t)}function Fi(e){return yt("source-construct",e.file,String(e.startLine),String(e.endLine),e.name)}function Cc(e,t){let n=Ii(e,t.symbol,t.relativePath),r=new Set(["package-surface-file","transitive-package-surface"]),i=n.filter(s=>!r.has(s)||pt(e,t)),o=i.some(s=>!r.has(s));return{evidence:i,priority:o||Ib(e,t.symbol,t.relativePath)?2:1}}function cC(e,t){let n=Cc(e,t);return n.evidence.length>0?n.priority:0}function IO(e,t){let n=U(e,t.file),r=n.filter(i=>i.startLine<=t.startLine&&i.endLine>=t.startLine).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine)||i.startLine-o.startLine);for(let i of r){let o=Cc(e,i);if(o.evidence.length>0)return o}for(let i of wO(e,t.file,t.startLine)){let o=n.filter(s=>s.leaf===i.name).sort((s,a)=>Math.abs(s.startLine-i.startLine)-Math.abs(a.startLine-i.startLine)||s.symbol.localeCompare(a.symbol));for(let s of o){let a=Cc(e,s);if(a.evidence.length>0)return a}return{evidence:[],priority:0}}return{evidence:[],priority:0}}function wO(e,t,n){let r=J(e,t)?.rootNode;if(!r||r.startPosition.row>n||r.endPosition.row<n)return[];let i=[],o=zd(r,n);for(;o;){if(o.type==="variable_declarator"||o.type==="function_declaration"||o.type==="generator_function_declaration"||o.type==="class_declaration"){let s=o.childForFieldName("name")??o.namedChild(0);(s?.type==="identifier"||s?.type==="type_identifier")&&i.push({name:s.text,startLine:o.startPosition.row})}o=o.parent}return i}function LO(e){return[...new Map([...e.sourceConstructStates.values()].map(t=>vc(e.db,t)).map(t=>[nn(t),t])).values()].sort((t,n)=>t.file.localeCompare(n.file)||t.startLine-n.startLine||t.endLine-n.endLine)}function PO(e,t){return e.anchors.map((n,r)=>{let i=yt("anchor",String(r),n.kind,n.query),o=[...e.symbolStates.values()].filter(u=>u.anchorQueries.has(n.query)).flatMap(u=>{if(!me(u.definition.symbol))return[ar(u.definition.symbol)];let d=t.filter(m=>m.file===u.definition.relativePath).map(m=>Fi(m));return d.length>0?d:[ar(u.definition.symbol)]}),s=[...e.sourceConstructStates.values()].filter(u=>u.anchorQueries.has(n.query)).map(u=>Fi(vc(e.db,u))),a=e.literalHits.filter(u=>u.query===n.query&&u.traversalSeed===!0&&u.ownerSymbol&&e.symbolStates.has(u.ownerSymbol)).map(u=>ar(u.ownerSymbol)),c=e.literalHits.filter(u=>u.query===n.query&&u.traversalSeed===!0&&!u.ownerSymbol&&u.ownerStartLine!==null&&u.ownerStartLine!==void 0&&u.ownerEndLine!==null&&u.ownerEndLine!==void 0).map(u=>Fi(vc(e.db,EO(u)))),l=pe(n.kind==="symbol"?[...o,...s]:a.length+c.length>0?[...a,...c]:n.seedRegionIds??[]);return{id:i,kind:n.kind,query:n.query,status:n.status,nodeIds:n.status==="ambiguous"?[]:l,candidateNodeIds:n.status==="ambiguous"?l:[],omittedCandidates:n.omittedSymbolCandidates??0}})}function DO(e){let t=new Map;for(let n of e)for(let r of[...n.nodeIds,...n.candidateNodeIds]){let i=t.get(r)??[];i.push(n.id),t.set(r,i)}return t}function MO(e,t,n){let r=e.relations.flatMap(s=>[s.fromBoundaryParticipant,s.toBoundaryParticipant].flatMap(a=>a?.ownerName?[a]:[])),i=e.regions.map(s=>({id:s.id,kind:"structural-region",label:s.label,disposition:"folded",location:null,anchorIds:pe(n.get(s.id)??[]),attributes:{workspace:s.workspace,structuralPath:s.structuralPath,minimumDepth:s.minDepth,files:s.fileCount,symbols:s.symbolCount,expanded:s.expanded}}));for(let s of e.symbolStates.values()){let a=e.regionForFile.get(s.definition.relativePath)?.id;if(!a)throw new Error(`System-map symbol ${s.definition.symbol} has no structural region.`);let c=ar(s.definition.symbol),l=Cc(e.db,s.definition);i.push({id:c,kind:"symbol",label:T(s.definition.symbol),disposition:(n.get(c)?.length??0)>0?"emitted":"folded",location:{file:s.definition.relativePath,line:s.definition.startLine,endLine:s.definition.endLine},anchorIds:pe(n.get(c)??[]),attributes:{regionId:a,depth:s.depth,leaf:s.definition.leaf??T(s.definition.symbol),referenceScope:s.referenceScope,...l.evidence.length>0?{publicEntry:!0,publicEntryPriority:l.priority,publicEntryEvidence:l.evidence.join(",")}:{}}})}for(let s of t){let a=e.regionForFile.get(s.file)?.id;if(!a)throw new Error(`Source construct ${s.name} has no structural region.`);let c=Fi(s),u=r.find(m=>m.file===s.file&&m.line>=s.startLine&&m.line<=s.endLine)?.ownerName??s.name,d=IO(e.db,s);i.push({id:c,kind:"source-construct",label:u,disposition:(n.get(c)?.length??0)>0?"emitted":"folded",location:{file:s.file,line:s.startLine,endLine:s.endLine},anchorIds:pe(n.get(c)??[]),attributes:{regionId:a,leaf:u,sourceOwned:!0,...d.evidence.length>0?{publicEntry:!0,publicEntryPriority:d.priority,publicEntryEvidence:d.evidence.join(",")}:{}}})}let o=new Map;for(let s of e.relations)s.fromBoundaryParticipant&&o.set(s.fromBoundaryParticipant.observationId,s.fromBoundaryParticipant),s.toBoundaryParticipant&&o.set(s.toBoundaryParticipant.observationId,s.toBoundaryParticipant);for(let s of[...o.values()].sort((a,c)=>a.observationId.localeCompare(c.observationId))){let a=e.regionForFile.get(s.file)?.id;if(!a)throw new Error(`Runtime-boundary participant ${s.observationId} has no structural region.`);i.push({id:Kd(s.observationId),kind:"runtime-boundary-participant",label:s.address||s.ownerName||`${s.role} ${s.action}`,disposition:"folded",location:{file:s.file,line:s.line,endLine:s.endLine},anchorIds:[],attributes:{regionId:a,action:s.action,protocol:s.protocol,role:s.role,...s.address?{address:s.address}:{},ownerSymbol:s.ownerSymbol}})}return i}function TO(e,t,n,r,i,o,s,a,c,l=!1){let u=r?ar(r):null;if(u&&t.has(u)&&!me(r))return u;let d=i?Kd(i.observationId):null;if(l&&d&&t.has(d))return d;let m=o?Fi(vc(e,o)):null;if(m&&t.has(m))return m;if(d&&t.has(d))return d;let p=c===null?null:(n.get(a)??[]).filter(f=>f.startLine<=c&&f.endLine>=c).sort((f,g)=>f.endLine-f.startLine-(g.endLine-g.startLine)||f.startLine-g.startLine)[0]??null;return p?Fi(p):u&&t.has(u)?u:s}function kO(e,t,n){let r=new Set(t.map(l=>l.id)),i=_e(n,l=>l.file),o=(l,u,d,m,p,f,g=!1)=>TO(e.db,r,i,l,u,d,m,p,f,g),s=[];for(let l of e.symbolStates.values()){let u=e.regionForFile.get(l.definition.relativePath)?.id;if(!u)continue;let d=ar(l.definition.symbol);s.push({id:yt("edge","structural-membership",u,d),kind:"structural-membership",fromNodeId:u,toNodeId:d,directed:!0,disposition:"folded",semantics:ac("structural-membership"),evidence:[{method:"indexed-definition-file",strength:"exact",identity:l.definition.symbol,location:{file:l.definition.relativePath,line:l.definition.startLine,endLine:l.definition.endLine}}]})}let a=_e(e.relations,l=>`${o(l.fromSymbol,l.fromBoundaryParticipant,l.fromSourceConstruct,l.fromRegionId,l.fromFile,l.line,l.kind==="runtime-boundary")}\0${o(l.toSymbol,l.toBoundaryParticipant,l.toSourceConstruct,l.toRegionId,l.toFile,null)}\0${l.kind}`),c=new Set;for(let l of a.values()){let u=l[0],d=o(u.fromSymbol,u.fromBoundaryParticipant,u.fromSourceConstruct,u.fromRegionId,u.fromFile,u.line,u.kind==="runtime-boundary"),m=o(u.toSymbol,u.toBoundaryParticipant,u.toSourceConstruct,u.toRegionId,u.toFile,null);if(u.kind==="runtime-boundary"&&u.fromBoundaryParticipant){let f=Kd(u.fromBoundaryParticipant.observationId),g=o(u.fromSymbol,void 0,u.fromSourceConstruct,u.fromRegionId,u.fromFile,u.line);g!==f&&!c.has(f)&&(c.add(f),s.push({id:yt("edge","boundary-observation",g,f),kind:"boundary-observation",fromNodeId:g,toNodeId:f,directed:!0,disposition:"folded",semantics:ac("boundary-observation"),evidence:[{method:"runtime-boundary-observation-owner",strength:u.strength??"unknown",identity:u.fromBoundaryParticipant.observationId,location:{file:u.fromBoundaryParticipant.file,line:u.fromBoundaryParticipant.line,endLine:u.fromBoundaryParticipant.endLine}}]}))}(d===m?t.find(f=>f.id===d):null)?.kind!=="structural-region"&&s.push({id:yt("edge",u.kind,d,m),kind:u.kind,fromNodeId:d,toNodeId:m,directed:!0,disposition:"folded",semantics:fv(u),evidence:HO(l.map(f=>({method:f.evidence,strength:f.strength??"unknown",identity:f.kind==="runtime-boundary"&&f.runtimeBoundaryKey?f.runtimeBoundaryKey:`${f.fromSymbol??f.fromFile} -> ${f.toSymbol??f.toFile}`,location:f.line===null?null:{file:f.fromFile,line:f.line}})))})}return s}function AO(e,t,n){for(let i of e.externalBoundaries){let o=yt("external",i.kind,i.name),s=pe(i.fromRegionIds);t.push({id:o,kind:i.kind,label:i.name,disposition:"folded",location:null,anchorIds:[],attributes:{}});for(let a of s)n.push({id:yt("edge",i.kind,a,o),kind:i.kind,fromNodeId:a,toNodeId:o,directed:!0,disposition:"folded",semantics:ac("external-import"),evidence:[{method:"indexed-or-source-import",strength:"mixed",identity:`${a} -> ${i.name}`,location:null}]})}let r=[];return e.boundaryFrontiers.forEach((i,o)=>{let s=e.regionForFile.get(i.file)?.id;if(!s)throw new Error(`Runtime-boundary frontier ${i.observationId} has no system-map region.`);let a=yt("unsupported","runtime-boundary",i.observationId,String(o)),c=yt("edge","runtime-boundary-frontier",s,a);t.push({id:a,kind:"runtime-boundary-frontier",label:i.address,disposition:"unsupported",location:{file:i.file,line:i.line},anchorIds:[],attributes:{action:i.action,strength:i.strength,owner:i.ownerShortName}}),n.push({id:c,kind:"runtime-boundary-frontier",fromNodeId:s,toNodeId:a,directed:!0,disposition:"unsupported",evidence:[{method:"runtime-boundary-extractor",strength:i.strength,identity:i.observationId,location:{file:i.file,line:i.line}}]}),r.push({id:yt("frontier","runtime-boundary",i.observationId,String(o)),kind:"runtime-boundary",direction:"unresolved",fromNodeIds:[s],edgeIds:[c],memberNodeIds:[a],memberCount:1,disposition:"unsupported",reason:i.reason,expansion:null})}),r}function FO(e,t){let n=t.topologyFrontiers.some(f=>f==="frontier:program-facts"),r=nC(e,{expandedFrontierIds:t.topologyFrontiers.filter(f=>f!=="frontier:program-facts"),routeIds:t.routeIds}),i=r.nodes.filter(f=>f.disposition==="emitted"||r.anchors.some(g=>g.status==="matched"&&g.nodeIds.includes(f.id))),o=t.relations.filter(f=>i.some(g=>_O(f,g))),s=t.boundaryFrontiers.filter(f=>i.some(g=>OO(f,g))),a=Ev(t.db,o,i),c=wv(t.db,i),l=Bv(t.db,i,s),u=[...a.nodes,...c.nodes,...l.nodes].map(f=>n&&f.disposition==="folded"?{...f,disposition:"emitted"}:f),d=[...a.edges,...c.edges,...l.edges].map(f=>n&&f.disposition==="folded"?{...f,disposition:"emitted"}:f),m=n?null:BO(i,u,d),p=bc({anchors:r.anchors,nodes:[...r.nodes,...u],edges:[...r.edges,...d],paths:r.paths,frontiers:[...r.frontiers,...a.frontiers,...c.frontiers,...l.frontiers,...m?[m]:[]],scope:r.coverage.scope,blindSpots:[...r.coverage.blindSpots,...a.blindSpots,...c.blindSpots,...l.blindSpots],incompleteReasons:r.coverage.status==="incomplete"?[r.coverage.explanation]:[],...r.routeCatalog?{routeCatalog:r.routeCatalog}:{}});p.completion=r.completion;for(let f of p.frontiers)f.disposition==="folded"&&(f.id.startsWith("frontier:program-facts:")||(f.expansion=$O(t,f.id)));return p}function NO(e){let t=LO(e),n=PO(e,t),r=MO(e,t,DO(n)),i=kO(e,r,t),o=AO(e,r,i);return FO(bc({anchors:n,nodes:r,edges:i,paths:[],frontiers:o,scope:`explicit anchors; relations ${e.requestedRelationKinds.join(", ")}; depth ${e.maxDepth}; evidence floor ${e.evidenceFloor}; source scopes ${e.includedSourceScopes.join(", ")}`,blindSpots:[...e.blindSpots],incompleteReasons:e.closureStatus==="incomplete"?[`${e.omittedSymbolCandidates} ambiguous symbol candidate(s) were omitted`]:[]}),e)}function _O(e,t){if(e.fromSymbol&&t.id===ar(e.fromSymbol)||e.toSymbol&&t.id===ar(e.toSymbol))return!0;if(!t.location)return!1;let n=t.location.endLine??t.location.line;return t.location.file===e.fromFile&&e.line!==null&&e.line>=t.location.line&&e.line<=n||t.location.file===e.toFile}function OO(e,t){if(!t.location||t.location.file!==e.file)return!1;let n=t.location.endLine??t.location.line;return e.line>=t.location.line&&e.line<=n||t.label===e.ownerShortName||typeof e.ownerShortName=="string"&&t.label.includes(e.ownerShortName)}function BO(e,t,n){let r=pe(t.filter(o=>o.disposition==="folded").map(o=>o.id)),i=pe(n.filter(o=>o.disposition==="folded").map(o=>o.id));return r.length===0&&i.length===0?null:{id:yt("frontier","program-facts"),kind:"program-facts",direction:"outgoing",fromNodeIds:pe(e.map(o=>o.id)),edgeIds:i,memberNodeIds:r,memberCount:r.length,disposition:"folded",reason:"Control, data, state, and temporal facts are folded beneath the selected high-level owners.",expansion:null}}function $O(e,t){return`scip-query system-map ${[...e.anchors.flatMap(r=>r.kind==="literal"?[`--search ${ye(r.query)}`]:[`--symbol ${ye(r.query)}`]),`--depth ${e.maxDepth}`,...e.requestedRelationKinds.map(r=>`--relation ${ye(r)}`),`--evidence-floor ${ye(e.evidenceFloor)}`,...e.includedSourceScopes.map(r=>`--source-scope ${ye(r)}`),...e.fullLiteralTraversal?["--full-literal-traversal"]:[],`--topology-characters ${e.maxTopologyCharacters}`,...e.expandedRegionIds.map(r=>`--expand ${ye(r)}`),...e.topologyFrontiers.map(r=>`--frontier ${ye(r)}`),...e.routeIds.map(r=>`--route ${ye(r)}`),`--frontier ${ye(t)}`].join(" ")}`}function jO(e){let t=new Set;for(let n of e.nodes){if(n.disposition!=="emitted")continue;n.kind==="structural-region"&&t.add(n.id);let r=n.attributes.regionId;typeof r=="string"&&t.add(r)}return t}function HO(e){let t=new Map;for(let n of e){let r=n.location?`${n.location.file}:${n.location.line}`:"";t.set(`${n.method}\0${n.strength}\0${n.identity??""}\0${r}`,n)}return[...t.values()].sort((n,r)=>n.method.localeCompare(r.method)||(n.identity??"").localeCompare(r.identity??"")||(n.location?.file??"").localeCompare(r.location?.file??"")||(n.location?.line??0)-(r.location?.line??0))}function yt(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function ar(e){return yt("symbol",e)}function UO(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function qO(e,t,n,r,i,o,s,a,c,l){let u=[...r].sort((g,h)=>bC(g,h,i)),m=u.slice(0,iC).map(g=>g.id),p=u.slice(iC).map(g=>g.id),f=[...e.map(g=>`--search ${ye(g)}`),...t.map(g=>`--symbol ${ye(g)}`),`--depth ${n}`,...o.map(g=>`--relation ${ye(g)}`),`--evidence-floor ${ye(s)}`,...a.map(g=>`--source-scope ${ye(g)}`),...c?["--full-literal-traversal"]:[],`--topology-characters ${l}`,...m.map(g=>`--expand ${ye(g)}`)];return{command:m.length===0?null:`scip-query system-map ${f.join(" ")}`,regionCount:m.length,regionIds:m,candidateRegionCount:r.length,omittedRegionIds:p}}function GO(e,t,n,r,i,o,s,a,c,l,u,d,m){let p=[...c].sort((I,k)=>bC(I,k,u)).filter(I=>!m||m.has(I.id)||d.has(I.id)),f=l.length>0?Math.floor(a*.4):0,g=a-f,h=new Set,b=0;for(let I of p){let k=lC(I);!d.has(I.id)&&h.size>0&&b+k>g||(h.add(I.id),b+=k)}let S=l.filter(I=>h.has(I.fromRegionId)&&h.has(I.toRegionId)).sort(zO),y=[];for(let I of S){let k=uC(I);y.length>0&&b+k>a||(y.push(xc(I)),b+=k)}let x=c.filter(I=>!h.has(I.id)).map(I=>I.id).sort(),v=new Set(y),C=l.filter(I=>!v.has(xc(I))).length,R=c.reduce((I,k)=>I+lC(k),0)+l.reduce((I,k)=>I+uC(k),0),E=p.every(I=>h.has(I.id))&&y.length===S.length,w=[...e.map(I=>`--search ${ye(I)}`),...t.map(I=>`--symbol ${ye(I)}`),`--depth ${n}`,...r.map(I=>`--relation ${ye(I)}`),`--evidence-floor ${ye(i)}`,...o.map(I=>`--source-scope ${ye(I)}`),...s?["--full-literal-traversal"]:[],`--topology-characters ${Math.max(a,R)}`];return{maxCharacters:a,estimatedCharacters:b,totalEstimatedCharacters:R,regionIds:[...h],omittedRegionIds:x,relationKeys:y,omittedRelations:C,complete:E,expansionCommand:E?null:`scip-query system-map ${w.join(" ")}`}}function lC(e){return 120+e.id.length+e.anchorQueries.join(",").length+e.relationKinds.join(",").length+e.notableSymbols.slice(0,2).reduce((t,n)=>t+n.shortName.length+n.file.length,0)}function uC(e){return 70+e.fromRegionId.length+e.toRegionId.length+e.kinds.join(",").length+e.evidence.join(",").length}function zO(e,t){let n=r=>r.kinds.includes("runtime-boundary")?0:r.kinds.includes("contract-symbol")?1:2;return n(e)-n(t)||t.relationCount-e.relationCount||xc(e).localeCompare(xc(t))}function xc(e){return`${e.fromRegionId}\0${e.toRegionId}`}function bC(e,t,n){let r=a=>n.has(a.id)?0:1,i=a=>a.sourceFileCount===0?1:0,o=a=>a.symbolCount+a.literalHitCount>0?0:1,s=a=>[...a.incomingRegionIds,...a.outgoingRegionIds].filter(c=>n.has(c)).length;return r(e)-r(t)||o(e)-o(t)||i(e)-i(t)||e.minDepth-t.minDepth||s(t)-s(e)||t.literalHitCount-e.literalHitCount||e.testFileCount-t.testFileCount||e.label.localeCompare(t.label)}function KO(e){let t=[],n=new Set;for(let i of e.filter(o=>o.expanded)){for(let c of i.symbols)c.origins.includes("symbol-anchor")&&n.add(c.file);let o=_e(i.symbols,c=>c.file),s=_e(i.literalHits,c=>c.file),a=[...i.files].sort((c,l)=>VO(c,l,o,s));for(let c of a){let l=(o.get(c.file)??[]).sort(mv)[0];if(l){t.push({kind:"symbol",regionId:i.id,file:l.file,line:l.startLine,endLine:l.endLine,label:l.shortName});continue}let u=(s.get(c.file)??[]).sort(xC)[0];u&&t.push({kind:"literal",regionId:i.id,file:u.file,line:u.line,endLine:null,label:u.ownerShortName??u.query})}}let r=WO(t,n);return{command:r.length===0?null:`scip-query inspect ${r.map(i=>`--at ${ye(`${i.file}:${i.line+1}`)}`).join(" ")} --view behavior`,definitionCommand:null,candidateAnchors:t.length,selectedAnchors:r.length,omittedAnchors:t.length-r.length,anchors:r}}function WO(e,t){let n=[..._e(e,s=>s.regionId).values()],r=[],i=new Set,o=Math.min(cO,24);for(let s of e)if(!(!t.has(s.file)||i.has(s.file))&&(r.push(s),i.add(s.file),r.length===o))return r;for(let s=0;r.length<o;s+=1){let a=!1;for(let c of n){let l=c[s];if(l&&(a=!0,!i.has(l.file)&&(r.push(l),i.add(l.file),r.length===o)))break}if(!a)break}return r}function VO(e,t,n,r){let i=a=>a.kind==="test"?2:a.kind==="barrel"?1:0,o=a=>(r.get(a.file)??[]).some(c=>c.traversalSeed)?0:1,s=a=>{let c=n.get(a.file)??[];return Math.min(5,...c.map(l=>Ti(l.origins)))};return i(e)-i(t)||o(e)-o(t)||s(e)-s(t)||e.depth-t.depth||e.file.localeCompare(t.file)}function ye(e){return`'${e.replaceAll("'","'\\''")}'`}function YO(e,t,n,r){let i=[];for(let o of Z(e,{includeIgnored:!1})){let s=V(e,o);if(s.length===0)continue;let a=[];for(let u=0;u<s.length;u+=1){let d=s[u]??"";d.includes(n)&&a.push({line:u,sourceLine:d})}if(a.length===0)continue;let c=t.definitionsForFile(o),l=K(e,o)?.callables??[];for(let{line:u,sourceLine:d}of a){let m=Ne(c,u),p=Nn(l,u),f=m&&!me(m.symbol)?m:null,g=f?.startLine??p?.startLine??m?.startLine??u,h=f?.endLine??p?.endLine??m?.endLine??u,b=po(e,o,u,g,h),S=r.has(`${o}\0${u}`),y=!!(f?.isFunctionLike||p);i.push({relativePath:o,line:u,sourceLine:d,ownerSymbol:f?.symbol??null,ownerShortName:f?T(f.symbol):p?.name??(m?T(m.symbol):null),ownerStartLine:b.startLine,ownerEndLine:b.endLine,matchKind:ZO(d,n),seedPriority:S?0:y?1:2})}}return i}function JO(e,t){let n={"exact-value":0,boundary:1,embedded:2};return e.seedPriority-t.seedPriority||n[e.matchKind]-n[t.matchKind]||e.relativePath.localeCompare(t.relativePath)||e.line-t.line}function dC(e){return`${e.relativePath}\0${e.line}`}function Ud(e,t,n){let i=Nn(K(e,t)?.callables??[],n)??SC(e,t,n);if(!i)return null;let o=po(e,t,n,i.startLine,i.endLine);return{file:t,name:i.name,startLine:o.startLine,endLine:o.endLine}}function SC(e,t,n){let r=J(e,t)?.rootNode;if(!r||r.startPosition.row>n||r.endPosition.row<n)return null;let i=zd(r,n);for(;i;){if(i.type==="variable_declarator"){let s=i.childForFieldName("name")??i.namedChild(0),a=i.childForFieldName("value")??i.namedChild(1);if(s?.type==="identifier"&&a&&qd(a,n))return{name:s.text,startLine:i.startPosition.row,endLine:i.endPosition.row}}if(i.type==="pair"){let s=i.childForFieldName("key")??i.namedChild(0),a=i.childForFieldName("value")??i.namedChild(1),c=s?.text.replace(/^(?:['"])(.*)(?:['"])$/u,"$1");if(c&&a&&/^[A-Za-z_$][\w$]*$/u.test(c)&&qd(a,n))return{name:c,startLine:i.startPosition.row,endLine:i.endPosition.row}}i=i.parent}let o=fi(e,t,n);return o?{name:`source@${n+1}`,startLine:o.startLine,endLine:o.endLine}:null}function qd(e,t){return["arrow_function","function_expression","generator_function","generator_function_declaration"].includes(e.type)&&e.startPosition.row<=t&&e.endPosition.row>=t?!0:e.namedChildren.some(n=>n.startPosition.row<=t&&n.endPosition.row>=t&&qd(n,t))}function zd(e,t){let n=e.namedChildren.filter(r=>r.startPosition.row<=t&&r.endPosition.row>=t).sort((r,i)=>r.endIndex-r.startIndex-(i.endIndex-i.startIndex)||r.startPosition.row-i.startPosition.row)[0];return n?zd(n,t):e}function XO(e,t){let n=t.match(/^(.+):(\d+)(?:-(\d+))?$/u);if(!n)return null;let r=ei(e,n[1],{allowMultiple:!1})[0]?.relativePath;if(!r)return null;let i=Math.max(0,Number.parseInt(n[2],10)-1),o=n[3]?Math.max(i,Number.parseInt(n[3],10)-1):i,s=(K(e,r)?.callables??[]).filter(a=>a.startLine<=i&&a.endLine>=o).sort((a,c)=>a.endLine-a.startLine-(c.endLine-c.startLine)||a.startLine-c.startLine)[0];return s?{file:r,name:s.name,startLine:s.startLine,endLine:s.endLine}:null}function QO(e){return{symbol:`source-construct:${e.file}:${e.startLine}:${e.endLine}:${e.name}`,shortName:e.name,relativePath:e.file,startLine:e.startLine,endLine:e.endLine}}function ZO(e,t){let n=/[\p{L}\p{N}_$]/u,r=e.indexOf(t);for(;r>=0;){let i=e[r-1]??"",o=e[r+t.length]??"";if((i==="'"||i==='"'||i==="`")&&o===i)return"exact-value";if(!n.test(i)&&!n.test(o))return"boundary";r=e.indexOf(t,r+Math.max(1,t.length))}return"embedded"}function Gd(e){return q(e)==="test"?!1:!/(?:^|[/._-])(?:fixtures?|mocks?|previews?|demos?|examples?|stories)(?:[/._-]|$)/iu.test(e)}function eB(e,t){return e.matchKind!=="embedded"&&t(e.relativePath)&&(Il(e.relativePath)!=="production"||Gd(e.relativePath))}function tB(e,t){let n=[...t].sort(nB),r=[],i=new Set;for(let o of n)if(!i.has(o.relativePath)&&(r.push(o),i.add(o.relativePath),r.length>=rC))break;for(let o of n){if(r.length>=rC)break;r.includes(o)||r.push(o)}return r.map(o=>({query:e,file:o.relativePath,line:o.line,ownerSymbol:o.ownerSymbol,ownerShortName:o.ownerShortName,ownerStartLine:o.ownerStartLine,ownerEndLine:o.ownerEndLine,sourceLine:o.sourceLine.trim(),matchKind:o.matchKind,traversalSeed:!1}))}function nB(e,t){let n={"exact-value":0,boundary:1,embedded:2};return n[e.matchKind]-n[t.matchKind]||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||+!Gd(e.relativePath)-+!Gd(t.relativePath)||e.relativePath.localeCompare(t.relativePath)||e.line-t.line}function rB(e,t){let n=new Map;for(let r of t){let i=iB(r.relativePath);n.set(i,(n.get(i)??0)+1)}return[...n].sort(([r,i],[o,s])=>s-i||r.localeCompare(o)).slice(0,sO).map(([r])=>`scip-query search ${ye(e)} --scope ${ye(r)}`)}function iB(e){let t=e.split("/").filter(Boolean);if(t.length<=1)return e;let n=t.slice(0,-1),r=n.lastIndexOf("src");return r>=0?n.slice(0,Math.min(n.length,r+3)).join("/"):n.slice(0,Math.min(n.length,3)).join("/")}function oB(e,t,n){let r=t.callerFileMap([n],{semantic:!1}).get(n.symbolId)??new Set,i=[];for(let o of[...r].sort()){let s=ae(e,o).filter(u=>u.importedName===n.leaf&&u.sourcePath!==null&&Fe(u.sourcePath,n.relativePath)),a=new Set;if(s.length>0)for(let u of s)a.add(u.localName??u.importedName);else n.leaf&&a.add(n.leaf);let c=[...new Set([...a].flatMap(u=>fn(e,o,u)))].sort((u,d)=>u-d);if(c.length===0){i.push({file:o,line:null,enclosingSymbol:null});continue}let l=t.definitionsForFile(o);for(let u of c)i.push({file:o,line:u,enclosingSymbol:Ne(l,u)?.symbol??null})}return i}function sB(e,t){let n=e.all(`SELECT DISTINCT gs.symbol, def_d.relative_path AS from_file
|
|
78
|
-
FROM mentions m
|
|
79
|
-
JOIN chunks c ON m.chunk_id = c.id
|
|
80
|
-
JOIN documents imp_d ON c.document_id = imp_d.id
|
|
81
|
-
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
82
|
-
LEFT JOIN (
|
|
83
|
-
SELECT m2.symbol_id, c2.document_id
|
|
84
|
-
FROM mentions m2
|
|
85
|
-
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
86
|
-
WHERE m2.role = 1
|
|
87
|
-
GROUP BY m2.symbol_id
|
|
88
|
-
) sym_def ON sym_def.symbol_id = gs.id
|
|
89
|
-
LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
90
|
-
WHERE imp_d.relative_path = ? AND m.role = 2
|
|
91
|
-
ORDER BY def_d.relative_path, gs.symbol`,t);return n.length>0?n.map(r=>({symbol:r.symbol,shortName:T(r.symbol),importedName:mC(T(r.symbol)),localName:mC(T(r.symbol)),fromFile:r.from_file,source:"compiler"})):ae(e,t).map(r=>{let i=aB(r.importedName,r.localName,r.kind),o=r.localName??r.importedName,s=r.importedName==="default"?o:r.importedName;return{symbol:i,shortName:i,importedName:s,localName:o,fromFile:r.sourcePath,source:"parsed-source"}})}function mC(e){return e.slice(e.lastIndexOf(":")+1).replace(/\(\)$/u,"")||e}function aB(e,t,n){return n==="namespace"&&e==="*"&&t?`* as ${t}`:n==="default"&&t?`default as ${t}`:n==="side-effect"?"(side effect import)":t&&t!==e?`${e} as ${t}`:e}function cr(e,t,n){let r=Qe(e,n);if(!r.match)return{matches:[],total:0,omitted:0};let i=[r.match,...r.candidates.map(s=>Qe(e,s.symbol).match)].filter(s=>s!==null),o=new Map;for(let s of i){let a=t.definitionsForFile(s.relativePath).find(c=>c.symbol===s.symbol);a&&o.set(a.symbol,a)}return{matches:[...o.values()],total:r.total,omitted:Math.max(0,r.total-o.size)}}function cB(e){return{symbol:e.symbol,shortName:T(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function bt(e,t){let n=[t.kind,t.fromFile,t.fromSymbol??"",t.toFile,t.toSymbol??"",t.fromBoundaryParticipant?.observationId??"",t.toBoundaryParticipant?.observationId??"",t.fromSourceConstruct?nn(t.fromSourceConstruct):"",t.toSourceConstruct?nn(t.toSourceConstruct):"",t.runtimeBoundaryKey??"",t.line??""].join("\0");e.set(n,t)}function Ni(e){return{observationId:e.id,action:e.action,protocol:e.protocol,role:e.role,address:vC(e),file:e.source.file,line:e.source.startLine,endLine:e.source.endLine,ownerName:e.owner.name,ownerSymbol:e.owner.symbol}}function Sc(e,t){let n=V(e,t.source.file);return ot(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine])}function pC(e,t){let n=[...e.values()];for(let r of[t.owner,t.source]){let i=n.filter(o=>o.file===r.file&&o.startLine<=r.startLine&&o.endLine>=r.startLine).sort((o,s)=>o.endLine-o.startLine-(s.endLine-s.startLine)||o.startLine-s.startLine)[0];if(i)return i}return null}function fC(e,t,n,r,i){let o=[],s=n.get(e.id);s!==void 0&&s<=t&&o.push(s);for(let a of r.values()){if(a.depth>t)continue;let c=a.definition;gC(c,e)&&o.push(a.depth)}for(let a of i.values())a.depth>t||gC(a,e)&&o.push(a.depth);return o.length>0?Math.min(...o):null}function gC(e,t){let n=e.relativePath??e.file;return[t.owner,t.source].some(r=>n===r.file&&e.startLine<=r.startLine&&e.endLine>=r.startLine)}function Kd(e){return yt("runtime-boundary-participant",e)}function lB(e,t,n){let r=ht(e,n),i=ht(t,n);return r.relativeDir!==i.relativeDir?!0:/(?:^|\/)(?:contracts?|schemas?|db\/schema)(?:\/|$)/u.test(t)}function uB(e,t,n){return Xo(e,n).id===Xo(t,n).id}function dB(e,t,n,r){if(e.referenceScope==="all")return!0;let i=Xo(t,r).id;return[...n.values()].some(s=>s.promoteBoundaryImports&&Xo(s.file,r).id===i)?!0:e.referenceScope!=="cross-workspace-or-forward"?!1:ht(t,r).relativeDir!==ht(e.definition.relativePath,r).relativeDir}function mB(e,t){let n={none:0,"forward-regions":1,"cross-workspace-or-forward":2,all:3};return n[e]>=n[t]?e:t}function pB(e,t){let n=sC.get(e);if(n)return n;let r=t.fileDependencyGraph(),i={fileGraph:r,reverseFileGraph:fB(r),workspaces:gB(t.sourceFiles()),runtimeBoundaries:Ys(e)};return sC.set(e,i),i}function fB(e){let t=new Map;for(let[n,r]of e)for(let i of r){let o=t.get(i)??new Set;o.add(n),t.set(i,o)}return t}function ht(e,t){return t.find(n=>e===n.relativeDir||e.startsWith(`${n.relativeDir}/`))??{name:"root",relativeDir:""}}function gB(e){let t=new Set(["apps","packages","services","crates","libs","tools"]),n=new Map;for(let r of e){let i=r.split("/").filter(Boolean);if(i.length<3||!t.has(i[0]))continue;let o=`${i[0]}/${i[1]}`;n.set(o,{name:i[1],relativeDir:o})}return[...n.values()].sort((r,i)=>i.relativeDir.length-r.relativeDir.length)}function Xo(e,t){let n=ht(e,t),i=(n.relativeDir?e.slice(n.relativeDir.length+1):e).split("/").filter(Boolean);i[0]==="src"&&i.shift();let o=hB(i);return{id:`region:${n.relativeDir||"root"}:${o}`,label:`${n.name}:${o}`,workspace:n.name,structuralPath:o}}function hB(e){if(e.length<=1)return"root";let t=e[0],n=e[1];return["components","features","modules"].includes(t)?`${t}/${n}`:t==="db"?`${t}/${n}`:["contracts","routes","services"].includes(t)?t:t==="tests"||t==="__tests__"?"tests":t}function yB(e,t,n,r,i,o,s){let a=_e([...e.values()],p=>o.get(p.file).id),c=_e([...t.values()],p=>o.get(p.definition.relativePath).id),l=_e(n,p=>o.get(p.file).id),u=new Map;for(let p of r)for(let f of new Set([p.fromRegionId,p.toRegionId])){let g=u.get(f)??[];g.push(p),u.set(f,g)}let d=_e(i,p=>p.toRegionId),m=_e(i,p=>p.fromRegionId);return[...a.entries()].map(([p,f])=>{let g=o.get(f[0].file),h=c.get(p)??[],b=l.get(p)??[],S=u.get(p)??[],y=s.has(p),x=h.map(vB).sort(EB).slice(0,aO),v=f.filter(C=>q(C.file)==="test").length;return{id:p,label:g.label,workspace:g.workspace,structuralPath:g.structuralPath,minDepth:Math.min(...f.map(C=>C.depth)),fileCount:f.length,sourceFileCount:f.length-v,testFileCount:v,symbolCount:h.length,literalHitCount:b.length,anchorQueries:pe([...b.map(C=>C.query),...h.flatMap(C=>[...C.anchorQueries])]),relationKinds:pe(S.map(C=>C.kind)),incomingRegionIds:pe((d.get(p)??[]).map(C=>C.fromRegionId)),outgoingRegionIds:pe((m.get(p)??[]).map(C=>C.toRegionId)),memberCallCandidateRelationCount:S.filter(C=>C.evidence==="ast-member-import-candidate").length,notableSymbols:x,omittedNotableSymbols:Math.max(0,h.length-x.length),expanded:y,files:y?f.map(bB).sort(IB):[],symbols:y?h.map(SB).sort(wB):[],literalHits:y?[...b].sort(xC):[],relations:y?[...S].sort(CC):[]}}).sort((p,f)=>p.minDepth-f.minDepth||p.label.localeCompare(f.label))}function bB(e){return{file:e.file,kind:q(e.file),depth:e.depth,origins:pe([...e.origins])}}function SB(e){return{symbol:e.definition.symbol,shortName:T(e.definition.symbol),file:e.definition.relativePath,startLine:e.definition.startLine,endLine:e.definition.endLine,depth:e.depth,origins:pe([...e.origins]),anchorQueries:pe([...e.anchorQueries]),referenceExpansion:e.referenceScope!=="none",referenceScope:e.referenceScope}}function vB(e){return{shortName:T(e.definition.symbol),file:e.definition.relativePath,origins:pe([...e.origins])}}function CB(e){return[..._e(e.filter(n=>n.fromRegionId!==n.toRegionId),n=>`${n.fromRegionId}\0${n.toRegionId}`).values()].map(n=>({fromRegionId:n[0].fromRegionId,toRegionId:n[0].toRegionId,kinds:pe(n.map(r=>r.kind)),relationCount:n.length,fromFiles:pe(n.map(r=>r.fromFile)),toFiles:pe(n.map(r=>r.toFile)),fromSymbols:pe(n.flatMap(r=>r.fromSymbol?[T(r.fromSymbol)]:[])),toSymbols:pe(n.flatMap(r=>r.toSymbol?[T(r.toSymbol)]:[])),evidence:pe(n.map(r=>r.evidence)),strengths:pe(n.map(r=>r.strength??"unknown"))})).sort((n,r)=>n.fromRegionId.localeCompare(r.fromRegionId)||n.toRegionId.localeCompare(r.toRegionId))}function xB(e,t){return[...e.values()].map(n=>({kind:"external-import",name:n.name,fromRegionIds:pe([...n.fromFiles].flatMap(r=>{let i=t.get(r);return i?[i.id]:[]})),fromFiles:pe([...n.fromFiles])})).sort((n,r)=>n.name.localeCompare(r.name))}function RB(e,t,n,r){let i=e.kind==="literal"?t.filter(o=>o.query===e.query).map(o=>o.file):[...n.values()].filter(o=>o.anchorQueries.has(e.query)).map(o=>o.definition.relativePath);return pe(i.map(o=>r.get(o)?.id).filter(o=>!!o))}function vC(e){return e.keyParts.map(t=>`${t.name}=${t.value}`).join(" ")}function pe(e){return[...new Set(e)].sort()}function CC(e,t){return e.fromRegionId.localeCompare(t.fromRegionId)||e.toRegionId.localeCompare(t.toRegionId)||e.kind.localeCompare(t.kind)||e.fromFile.localeCompare(t.fromFile)||e.toFile.localeCompare(t.toFile)||(e.line??-1)-(t.line??-1)}function EB(e,t){return Ti(e.origins)-Ti(t.origins)||e.shortName.localeCompare(t.shortName)}function IB(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)}function wB(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function xC(e,t){return e.file.localeCompare(t.file)||e.line-t.line||e.query.localeCompare(t.query)}var PB=["causal","structure","complete"],DB={causal:["execution","runtime","dataflow","state","temporal"],structure:["contract","identity","ownership","dependencies"],complete:Bt},MB=2,TB=48,RC=64,kB=5e4;function Qo(e,t,n={}){let r=ke([...t.symbols??[],...t.locations??[]]),i=ke(t.searches??[]);if(r.length===0&&i.length===0)throw new Error("evidence requires at least one positional symbol, --symbol, --at, or --search selector.");let o=n.view??"causal",s=AB(n.families,o),a=n.direction??"both",c=ke(n.subtypes??[]),l=n.connecting??!1,u=n.inventoryOnly??!1,d=ke(n.foldIds??[]),m=n.maxDepth??MB,p=n.maxEdges??TB;if(!Number.isSafeInteger(m)||m<0)throw new RangeError(`Evidence depth must be a non-negative safe integer; received ${m}.`);if(!Number.isSafeInteger(p)||p<=0)throw new RangeError(`Evidence max edges must be a positive safe integer; received ${p}.`);if(!["incoming","outgoing","both"].includes(a))throw new Error(`Unsupported graph evidence direction: ${a}.`);if(u&&d.length>0)throw new Error("Evidence fold materialization cannot be combined with --inventory-only.");let f=hC(e,{symbols:r,searches:i,maxDepth:m,maxTopologyCharacters:kB,relations:FB(s)}),g=new Map(f.nodes.map(G=>[G.id,G])),h=f.edges.filter(G=>G.disposition==="emitted"||G.disposition==="folded").flatMap(G=>NB(G,g)),b=h.filter(G=>s.includes(G.family)).filter(G=>c.length===0||c.includes(G.subtype)),S=new Set(f.anchors.flatMap(G=>G.nodeIds));if(l&&S.size<2)throw new Error("Connecting evidence requires at least two resolved root nodes.");let y=new Set(b.map(G=>G.id)),x=Wd(h,S,"incoming").filter(G=>y.has(G.id)),v=Wd(h,S,"outgoing").filter(G=>y.has(G.id)),C=Wd(h,S,"both").filter(G=>y.has(G.id)),R=jB(s,c,x,v,C),E=a==="incoming"?x:a==="outgoing"?v:C,w=l?WB(E,[...S],a):E,I=YB(w,S,a),k=[...w].sort((G,O)=>JB(G,O,I)),D=HB(k,p),F=qB(D,d),L=u?[]:d.length>0?k.filter(G=>F.has(G.id)):k,A=d.length>0?L:L.slice(0,p),P=d.length>0||u?[]:D,j=Math.max(0,L.length-A.length),B=f.frontiers.filter(G=>G.disposition==="unsupported").length,X=f.coverage.status==="incomplete"?"incomplete":j>0?"bounded":"accounted";return{kind:"graph",view:n.families&&n.families.length>0?"custom":o,families:s,selection:{direction:a,subtypes:c,connecting:l,inventoryOnly:u,foldIds:d},targets:f.anchors.map(G=>({kind:G.kind,query:G.query,status:G.status,nodeIds:[...G.nodeIds],omittedCandidates:G.omittedCandidates})),inventory:R,edges:A,folds:P,coverage:{status:X,topologyStatus:f.coverage.status,scope:f.coverage.scope,maxDepth:m,maxEdges:p,matchedEdges:k.length,eligibleEdges:L.length,returnedEdges:A.length,omittedEdges:j,frontierGroups:f.frontiers.length,unsupportedFrontiers:B,blindSpots:ke([...f.coverage.blindSpots,...dv(s)]),explanation:u?`${k.length} relationship(s) match the explicit projection; only exact inventory counts were requested.`:d.length>0?`Every relationship in ${d.length} explicitly selected recoverable fold(s) was emitted.`:X==="accounted"?"Every selected relationship in the bounded topology was emitted.":X==="bounded"?`${j} selected relationship(s) were withheld by the explicit edge budget.`:f.coverage.explanation}}}function AB(e,t){let n=e&&e.length>0?e:DB[t],r=n.filter(i=>!Bt.includes(i));if(r.length>0)throw new Error(`Unsupported graph evidence family: ${r.join(", ")}.`);return ke(n)}function FB(e){return["call","contract-symbol","import","reference","runtime-boundary"]}function NB(e,t){let n=t.get(e.fromNodeId),r=t.get(e.toNodeId);return!n||!r?[]:(e.semantics??[]).flatMap((i,o)=>{let s=OB(i);if(!s)return[];let a=sc(s,i.subtype);if(!a)throw new Error(`No graph relation provider contract is registered for ${s}/${i.subtype}.`);let c=$B(e);return a.relation.evidenceStrengths.includes(c)?[{id:`${e.id}:${o}:${s}`,family:s,semanticFamily:i.family,subtype:i.subtype,from:EC(n),to:EC(r),sourceKind:e.kind,providerId:a.provider.id,supportCeiling:a.relation.supportCeiling,establishes:a.relation.establishes,nonClaims:[...a.relation.nonClaims],recoverWith:[...a.relation.recoverWith],evidenceStrength:c,evidenceMethods:ke(e.evidence.map(l=>l.method)),evidenceConstituents:_B(e.evidence),context:i.context?{...i.context}:null,attributes:i.attributes?{...i.attributes}:null}]:[]})}function _B(e){let t=new Map;for(let n of e)t.set(`${n.method}\0${n.strength}`,n);return[...t.values()].map(({method:n,strength:r})=>({method:n,strength:r}))}function OB(e){switch(e.family){case"control":return e.context?.crossesRuntimeBoundary===!0||e.subtype==="runtime-handoff"?"runtime":"execution";case"data":return"dataflow";case"state":return"state";case"temporal":return"temporal";case"contract":return"contract";case"identity":return e.subtype.startsWith("contains")||e.subtype.startsWith("owns-")?"ownership":e.subtype.startsWith("import")?"dependencies":"identity"}}function EC(e){let t=BB(e);return{id:e.id,kind:e.kind,label:t?T(t):e.label,symbol:t,location:e.location?{...e.location}:null}}function BB(e){return e.kind!=="symbol"||!e.id.startsWith("symbol:")?null:decodeURIComponent(e.id.slice(7))}function $B(e){let t=ke(e.evidence.map(n=>n.strength));return t.length===1?t[0]:t.includes("exact")&&t.every(n=>n==="exact"||n==="derived")?"mixed":t.includes("candidate")?"candidate":t.includes("unknown")||t.length===0?"unknown":"mixed"}function Wd(e,t,n){let r=Vd(e,n),i=new Map,o=new Map,s=[...t].sort();for(let a of s)o.set(a,0);for(let a=0;a<s.length;a+=1){let c=s[a],l=o.get(c);for(let u of r.get(c)??[])i.set(u.edge.id,u.edge),!o.has(u.next)&&(o.set(u.next,l+1),s.push(u.next))}return[...i.values()]}function Vd(e,t){let n=new Map,r=(i,o,s)=>{let a=n.get(i)??[];a.push({edge:s,next:o}),n.set(i,a)};for(let i of e)t!=="incoming"&&r(i.from.id,i.to.id,i),t!=="outgoing"&&r(i.to.id,i.from.id,i);for(let i of n.values())i.sort((o,s)=>o.edge.id.localeCompare(s.edge.id)||o.next.localeCompare(s.next));return n}function jB(e,t,n,r,i){let o=new Set;for(let u of[...n,...r,...i])o.add(`${u.family}\0${u.subtype}`);if(t.length>0)for(let u of e)for(let d of t)o.add(`${u}\0${d}`);let s=u=>{let d=new Map;for(let m of u){let p=`${m.family}\0${m.subtype}`;d.set(p,(d.get(p)??0)+1)}return d},a=s(n),c=s(r),l=s(i);return[...o].map(u=>{let[d,m]=u.split("\0");return{family:d,subtype:m,incoming:a.get(u)??0,outgoing:c.get(u)??0,both:l.get(u)??0}}).sort((u,d)=>Bt.indexOf(u.family)-Bt.indexOf(d.family)||u.subtype.localeCompare(d.subtype))}function HB(e,t){let n=e.slice(t),r=new Map;for(let s of n){let a=UB(s),c=`${s.family}\0${a}`,l=r.get(c)??[];l.push(s),r.set(c,l)}let i=new Map(e.map((s,a)=>[s.id,a+1])),o=[];for(let[s,a]of[...r].sort(([c],[l])=>c.localeCompare(l))){let[c,l]=s.split("\0"),u=[...a].sort((d,m)=>d.id.localeCompare(m.id));for(let d=0;d<u.length;d+=RC){let m=u.slice(d,d+RC),p=m.map(b=>b.id),f=ke(m.map(b=>b.subtype)).sort(),g=f.length===1?f[0]:"mixed",h=[...new Set(m.flatMap(b=>[b.from.id,b.to.id]))].sort();o.push({id:KB(c,f.join("\0"),p),mode:GB(m),family:c,subtype:g,subtypes:f,region:l,edgeCount:p.length,edgeIds:p,nodeIds:h,minimumMaxEdges:Math.max(...p.map(b=>i.get(b)??e.length))})}}return o.sort((s,a)=>Bt.indexOf(s.family)-Bt.indexOf(a.family)||(s.region??"").localeCompare(a.region??"")||s.id.localeCompare(a.id))}function UB(e){let t=e.from.location?.file??`kind:${e.from.kind}`,n=e.to.location?.file??`kind:${e.to.kind}`;return t===n?t:`${t} -> ${n}`}function qB(e,t){if(t.length===0)return new Set;let n=new Map(e.map(i=>[i.id,i])),r=t.filter(i=>!n.has(i));if(r.length>0){let i=e.map(o=>o.id).sort();throw new Error(`Unknown evidence fold ${r.join(", ")} for this projection. Available folds: ${i.join(", ")||"(none)"}.`)}return new Set(t.flatMap(i=>n.get(i).edgeIds))}function GB(e){let t=new Map,n=new Map,r=new Set;for(let o of e){r.add(o.from.id),r.add(o.to.id);let s=t.get(o.from.id)??new Set;s.add(o.to.id),t.set(o.from.id,s);let a=n.get(o.to.id)??new Set;a.add(o.from.id),n.set(o.to.id,a)}return zB(r,t)?"scc":[...r].every(o=>(n.get(o)?.size??0)<=1&&(t.get(o)?.size??0)<=1)?"linear":"topology"}function zB(e,t){let n=new Set,r=new Set,i=o=>{if(n.has(o))return!0;if(r.has(o))return!1;n.add(o);for(let s of t.get(o)??[])if(i(s))return!0;return n.delete(o),r.add(o),!1};return[...e].some(i)}function KB(e,t,n){return`fold:${LB("sha256").update([e,t,...n].join("\0")).digest("hex").slice(0,16)}`}function WB(e,t,n){let r=new Map,i=[...new Set(t)].sort();for(let o=0;o<i.length;o+=1)for(let s=o+1;s<i.length;s+=1)for(let a of VB(e,i[o],i[s],n))r.set(a.id,a);return[...r.values()]}function VB(e,t,n,r){let i=Vd(e,r),o=new Map([[t,0]]),s=new Map,a=[t];for(let l=0;l<a.length;l+=1){let u=a[l],d=o.get(u);if(u!==n)for(let m of i.get(u)??[])o.has(m.next)||(o.set(m.next,d+1),s.set(m.next,{node:u,edge:m.edge}),a.push(m.next))}if(!o.has(n))return[];let c=[];for(let l=n;l!==t;){let u=s.get(l);if(!u)return[];c.push(u.edge),l=u.node}return c.reverse()}function YB(e,t,n){let r=Vd(e,n),i=new Map,o=[...t];for(let s of t)i.set(s,0);for(let s=0;s<o.length;s+=1){let a=o[s],c=i.get(a);for(let{next:l}of r.get(a)??[])i.has(l)||(i.set(l,c+1),o.push(l))}return i}function JB(e,t,n){return IC(e,n)-IC(t,n)||wC(e)-wC(t)||LC(e.evidenceStrength)-LC(t.evidenceStrength)||Bt.indexOf(e.family)-Bt.indexOf(t.family)||e.from.label.localeCompare(t.from.label)||e.to.label.localeCompare(t.to.label)||e.subtype.localeCompare(t.subtype)||e.id.localeCompare(t.id)}function IC(e,t){return Math.min(t.get(e.from.id)??Number.MAX_SAFE_INTEGER,t.get(e.to.id)??Number.MAX_SAFE_INTEGER)}function wC(e){let t=[e.from,e.to].filter(n=>n.kind==="structural-region").length;return t===2?2:t}function LC(e){switch(e){case"exact":return 0;case"mixed":return 1;case"derived":return 2;case"candidate":return 3;case"unknown":return 4}}function Yd(e,t){let n=Rr(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let r=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
|
|
92
|
-
WHERE relative_path IN (${r})
|
|
93
|
-
ORDER BY relative_path`,...n).map(l=>l.relative_path).filter(l=>!e.isIgnored(l)),s=Bs(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:l,...u})=>u),a=_n(e,"forward",n).filter(l=>!e.isIgnored(l)),c=_n(e,"reverse",n).filter(l=>!e.isIgnored(l));return{files:o,symbols:s,dependsOn:a,dependedOnBy:c}}function Jd(e,t){let n=Rr(e,t);return n.length===0?[]:DC([...PC(e,n),...QB(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(MC)}function XB(e,t){let n=Rr(e,t);return n.length===0?[]:DC(PC(e,n)).filter(r=>!e.isIgnored(r.relative_path)).map(r=>({...MC(r),basis:"external-reference"}))}function PC(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
|
|
94
|
-
FROM mentions m
|
|
95
|
-
JOIN chunks c ON m.chunk_id = c.id
|
|
96
|
-
JOIN documents d1 ON c.document_id = d1.id
|
|
97
|
-
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
98
|
-
WHERE d1.relative_path NOT IN (${n})
|
|
99
|
-
AND (
|
|
100
|
-
EXISTS (
|
|
101
|
-
SELECT 1
|
|
102
|
-
FROM defn_enclosing_ranges der
|
|
103
|
-
JOIN documents d2 ON der.document_id = d2.id
|
|
104
|
-
WHERE der.symbol_id = gs.id
|
|
105
|
-
AND d2.relative_path IN (${n})
|
|
106
|
-
)
|
|
107
|
-
OR EXISTS (
|
|
108
|
-
SELECT 1
|
|
109
|
-
FROM mentions def_m
|
|
110
|
-
JOIN chunks def_c ON def_m.chunk_id = def_c.id
|
|
111
|
-
JOIN documents d2 ON def_c.document_id = d2.id
|
|
112
|
-
WHERE def_m.symbol_id = gs.id
|
|
113
|
-
AND def_m.role = 1
|
|
114
|
-
AND d2.relative_path IN (${n})
|
|
115
|
-
)
|
|
116
|
-
)
|
|
117
|
-
AND m.role != 1
|
|
118
|
-
AND ${e.localSymbolPredicate}
|
|
119
|
-
${e.pathExclusionsFor("d1")}
|
|
120
|
-
ORDER BY d1.relative_path`,...t,...t,...t)}function QB(e,t){let n=new H(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>Xe(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function DC(e){let t=new Set;return e.filter(n=>{let r=`${n.relative_path}|${n.symbol}`;return t.has(r)?!1:(t.add(r),!0)})}function MC(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:T(e.symbol)}}var Zo=new WeakMap,TC=dt({kind:"definition-exclusions",invalidation:$e("definition-exclusions"),serialize:e=>JSON.stringify(e),deserialize:ZB});function AC(e,t){let n=se(t);if(!(n==="rust"||n==="typescript"||n==="tsx"||n==="javascript"))return[];let i=W(e,t);if(!i)return[];let o=Rt(e,t,i),s=TC.read(e,t,o);if(s)return s;let a=n==="rust"?a$(e,t):r$(e,t);return TC.write(e,t,o,a),a}function ZB(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=t.map(e$);return n.some(r=>r===null)?null:n}catch{return null}}function e$(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.startLine!="number"||!Number.isFinite(t.startLine)||typeof t.endLine!="number"||!Number.isFinite(t.endLine)||typeof t.reason!="string"||t.containerName!==void 0&&typeof t.containerName!="string")return null;let n=t.disposition===void 0?S$(t.reason):t.disposition;return n!=="exclude"&&n!=="implicit-usage"?null:{startLine:t.startLine,endLine:t.endLine,reason:t.reason,disposition:n,...t.containerName?{containerName:t.containerName}:{}}}var FC=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),t$=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,n$=/\b(?:export\s+)?(?:async\s+)?function\s+use[A-Z][A-Za-z0-9_$]*\b|\b(?:const|let|var)\s+use[A-Z][A-Za-z0-9_$]*\s*(?::[^=;]+)?=\s*(?:async\s*)?(?:function\b|(?:<[^=;{]+>\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>)/;function r$(e,t){let n=W(e,t);if(!n||!i$(n))return[];let r=J(e,t);if(!r)return[];let i=Zo.get(r);if(i)return i;let o=!1,s=r.rootNode;for(let c of s.namedChildren){if(c.type!=="expression_statement")continue;let l=c.namedChild(0);if(!l||l.type!=="call_expression")continue;let u=l.namedChild(0);if(!u)continue;let d=u.type==="member_expression"?u.namedChild(u.namedChildCount-1)?.text:u.text;if(d&&FC.has(d)){o=!0;break}}let a=[];o&&a.push({startLine:0,endLine:s.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)",disposition:"exclude"});for(let c of s.namedChildren){let l=null,u=null;if(c.type==="function_declaration")l=c.namedChild(0)?.text??null,u=c;else if(c.type==="export_statement"){let d=c.namedChild(0);d?.type==="function_declaration"&&(l=d.namedChild(0)?.text??null,u=d)}else if(c.type==="lexical_declaration"){let d=c.namedChild(0);if(d?.type==="variable_declarator"){let m=d.namedChild(0)?.text,p=d.namedChild(1);m&&(p?.type==="arrow_function"||p?.type==="function_expression")&&(l=m,u=d)}}l&&/^use[A-Z]/.test(l)&&u&&a.push({startLine:u.startPosition.row,endLine:u.endPosition.row,reason:"React custom hook (use*)",disposition:"exclude"})}return a.push(...NC(r,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),Zo.set(r,a),a}function i$(e){if(e.includes("scip-query"))return!0;let t=!1;for(let n of FC)if(e.includes(n)){t=!0;break}return t&&t$.test(e)?!0:e.includes("use")&&n$.test(e)}var o$=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function s$(e){return o$.test(e)}function NC(e,t,n){let r=[],i=o=>{if(t.has(o.type)&&o.parent){let a=o.parent.children,c=-1;for(let l=0;l<a.length;l+=1)if(a[l].startIndex===o.startIndex&&a[l].type===o.type){c=l;break}if(c>0)for(let l=c-1;l>=0;l-=1){let u=a[l];if(n.has(u.type)){if(s$(u.text)){r.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"scip-query suppression comment",disposition:"exclude"});break}continue}if(!(u.type==="attribute_item"||u.type==="inner_attribute_item"))break}}for(let s of o.namedChildren)i(s)};return i(e.rootNode),r}function a$(e,t){let n=J(e,t);if(!n)return[];let r=Zo.get(n);if(r)return r;let i=[],o=c$(n);return o?(Zo.set(n,o),o):(_C(n.rootNode,i,!1,!1),i.push(...NC(n,new Set(["function_item","function_signature_item","struct_item","enum_item","union_item","impl_item","mod_item","static_item","const_item"]),new Set(["line_comment","block_comment"]))),i.push(...y$(n.rootNode)),Zo.set(n,i),i)}function c$(e){return v$(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)",disposition:"exclude"}]:null}function _C(e,t,n,r){let i=n,o=r;e.type==="trait_item"&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait declaration body (dynamic dispatch)",disposition:"implicit-usage"}),e.type==="impl_item"&&e.childForFieldName("trait")&&(o=!0,t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl block (dynamic dispatch)",disposition:"implicit-usage"})),e.type==="function_item"||e.type==="function_signature_item"?l$(e,t,n,r):r&&h$(e)?t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl associated item (dynamic dispatch)",disposition:"implicit-usage"}):e.type==="struct_item"||e.type==="enum_item"||e.type==="union_item"?u$(e,t,n):e.type==="mod_item"&&Xd(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)_C(s,t,i,o)}function l$(e,t,n,r){let i=Xd(e),o=null;r?o={reason:"trait impl method (dynamic dispatch)",disposition:"implicit-usage"}:n&&(o={reason:"inside #[cfg(test)] mod",disposition:"exclude"});for(let s of i){if(OC(s)){o={reason:"#[allow(dead_code)]",disposition:"exclude"};break}let a=f$(s);if(a){o=a;break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o.reason,disposition:o.disposition})}function u$(e,t,n){let r=Xd(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(g$)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(...)] - generated impl may access fields",disposition:"implicit-usage",containerName:i}),r.some(OC)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",disposition:"exclude",containerName:i}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",disposition:"exclude",containerName:i})}function Xd(e){let t=e.parent;if(!t)return[];let n=t.children,r=-1;for(let o=0;o<n.length;o+=1)if(n[o].startIndex===e.startIndex&&n[o].type===e.type){r=o;break}if(r<=0)return[];let i=[];for(let o=r-1;o>=0;o-=1){let s=n[o];if(s.type==="attribute_item"||s.type==="inner_attribute_item")i.push(s.text);else{if(s.type==="line_comment"||s.type==="block_comment")continue;break}}return i}var d$=new Set(["test","bench","tokio::test","async_std::test"]),m$=new Set(["no_mangle","export_name","link_name","used","macro_export","proc_macro","proc_macro_derive","proc_macro_attribute"]),p$=new Set(["allow","warn","deny","forbid","cfg","cfg_attr","doc","inline","cold","must_use","deprecated","repr","derive","automatically_derived","non_exhaustive","path","link","link_section","global_allocator","panic_handler"]);function f$(e){if(/#\[\s*cfg\s*\(\s*test\s*\)/.test(e))return{reason:"#[cfg(test)]",disposition:"exclude"};let t=b$(e);return t?d$.has(t)?{reason:`#[${t}]`,disposition:"exclude"}:m$.has(t)?{reason:`Rust ABI/export attribute #[${t}]`,disposition:"implicit-usage"}:p$.has(t)?null:{reason:`Rust attribute macro #[${t}]`,disposition:"implicit-usage"}:null}function g$(e){return/#\[\s*derive\s*\(/.test(e)}function OC(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function h$(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function y$(e){let t=C$(e);if(t.size===0)return[];let n=[];for(let r of e.descendantsOfType("mod_item")){let i=r.childForFieldName("name")?.text;i&&t.has(i)&&n.push({startLine:r.startPosition.row,endLine:r.endPosition.row,reason:'attribute `with = "..."` module - body may be invoked via reflection',disposition:"implicit-usage",containerName:i})}return n}function b$(e){let t=/^#!?\[\s*([A-Za-z_][A-Za-z0-9_]*(?:\s*::\s*[A-Za-z_][A-Za-z0-9_]*)*)/.exec(e);return t?t[1].replace(/\s+/g,""):null}function S$(e){return e==="#[tauri::command]"||e==="#[command]"||e==="#[wasm_bindgen]"||e==="#[no_mangle]"||e==="#[napi]"||e==="#[pyfunction]"||e==="#[pymethod]"||e==="#[pyo3]"||e==="#[doc(hidden)]"||e.startsWith("trait ")||e.startsWith("#[derive(<reflective>)]")||e.startsWith("#[derive(...)]")||e.startsWith('serde `with = "')||e.startsWith('attribute `with = "')||e.startsWith("Rust attribute macro #[")||e.startsWith("Rust ABI/export attribute #[")?"implicit-usage":"exclude"}function v$(e){for(let t=0;t<Math.min(e.namedChildCount,12);t+=1){let n=e.namedChild(t);if(!n||n.type!=="line_comment"&&n.type!=="block_comment")break;if(/@generated\b/.test(n.text)||/This file is .*generated\b/i.test(n.text)||/Code generated by/i.test(n.text)||/Generated by:\s*https?:\/\/openapi-generator/i.test(n.text)||/openapi-generator/i.test(n.text)&&/Generated by/i.test(n.text))return!0}return!1}var kC=/\bwith\s*=\s*"([^"]+)"/g;function C$(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){kC.lastIndex=0;let r;for(;(r=kC.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function BC(e){let t=Qd(e);return(n,r,i,o)=>t(n,r,i,o)?.disposition==="exclude"}function Qd(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=AC(e,r),s=new Map;for(let a of o){if(!a.containerName)continue;let c=s.get(a.containerName)??[];c.push(a),s.set(a.containerName,c)}return i={ranges:o,containers:s},t.set(r,i),i};return(r,i,o,s)=>{let a=n(r),c=[];for(let u of a.ranges)i>=u.startLine&&i<=u.endLine&&c.push(u);let l=new Set;s&&l.add(s);for(let u of $s(o))l.add(u);for(let u of l){let d=a.containers.get(u);d&&c.push(...d)}return x$(c)}}function x$(e){if(e.length===0)return null;let n=e.find(r=>r.disposition==="exclude")??e[0];return{disposition:n.disposition,reason:n.reason}}function Zd(e,t={}){Vi(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function $C(e,t,n={}){Vi(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function jC(e,t){if(t.isIgnoredPath(e.relativePath))return rt("ignored-file");if(me(e.symbol))return rt("module-like-symbol");if(!Rc(e.symbol))return rt("non-value-symbol");if(!e.isFunctionLike&&e.enclosingSymbol&&Rc(e.enclosingSymbol))return rt("nested-non-callable-value");if(!t.includeTests&&!R$(e.relativePath))return rt("test-file");if(!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName))return rt("excluded-file-region");let n=z(e.symbol);if(n==="<constructor>")return rt("implicit-constructor");if(e.symbol.startsWith("scip-python ")){if(n==="__all__")return rt("python-runtime-metadata");if(/^__[^_].*__$/.test(n))return rt("python-protocol-member")}return t.isDeclarationOnlyCallable()?rt("declaration-only-callable"):t.isFrameworkContractCallable()?rt("framework-contract-member"):je(e.symbol)?rt("rust-trait-impl-member"):ii(e.symbol)?rt("rust-test-module"):!t.includeMembers&&!E$(e)?rt("member"):e.endLine-e.startLine+1<t.minLoc?rt("below-min-loc"):{accepted:!0}}function R$(e){return q(e)!=="test"}function rt(e){return{accepted:!1,rejectionReason:e}}function Rc(e){return Se(e)||e.endsWith("().")||e.endsWith(".")}function E$(e){return Xe(e.symbol)||$s(e.symbol).length===0}function HC(){return new Map}function UC(e,t,n){let r=new Map;for(let i of Cf(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||Ic(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function qC(e,t,n,r={}){let i=new Set;if(r.conservative||n.size===0){for(let o of Rf(e,t))i.add(o.symbol_id);return i}for(let o of xf(e,t))e.isIgnored(o.relative_path)||n.has(o.relative_path)||i.add(o.symbol_id);return i}function em(e,t){let n=e.get(t);if(!n)return!1;for(let r of n.values())if(r.occurrences>0)return!0;return!1}function Ec(e,t,n){let r=e.get(t);if(!r)return!1;for(let[i,o]of r)if(i!==n&&o.occurrences>0)return!0;return!1}function GC(e){return e?.occurrences??0}function Ic(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=KC(e,t,n);o.occurrences+=r,o.sources.add(i)}function zC(e,t,n,r,i){if(r<=0)return;let o=KC(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function KC(e,t,n){let r=e.get(t);r||(r=new Map,e.set(t,r));let i=r.get(n);return i||(i={occurrences:0,sources:new Set},r.set(n,i)),i}var I$=new Set(["componentDidCatch","componentDidMount","componentDidUpdate","componentWillUnmount","getDerivedStateFromError","getDerivedStateFromProps","getSnapshotBeforeUpdate","render","shouldComponentUpdate","UNSAFE_componentWillMount","UNSAFE_componentWillReceiveProps","UNSAFE_componentWillUpdate"]);function _i(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=J(e,t.relativePath);if(!n)return!1;let r=n.rootNode.descendantsOfType("method_definition").find(s=>s.startPosition.row<=t.startLine&&s.endPosition.row>=t.endLine);if(!r)return!1;if(/\boverride\b/.test(r.text.slice(0,Math.max(0,r.text.indexOf("{")))))return!0;let i=r.parent;for(;i&&i.type!=="class_declaration"&&i.type!=="class";)i=i.parent;if(!i)return!1;let o=i.text.slice(0,Math.max(0,i.text.indexOf("{")));return/\bimplements\b/.test(o)||/\bextends\b/.test(o)?!0:I$.has(t.leaf)&&/\bextends\s+(?:React\.)?(?:Component|PureComponent)\b/.test(o)}var w$=64,L$=300;function zr(e,t={}){let{scope:n,minLoc:r=1,includeTests:i=!1,skipBarrels:o=!1,includeMembers:s=!1,deadCodeOnly:a=!1,scanLimit:c,semantic:l=!0}=t,u=0,d=N("dead.candidates",()=>{let v=he(P$(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c);return u=v.length,v},()=>({definitions:u})),m=0,p=o?N("dead.inactive-barrels",()=>{let v=new Set(Eb(e));return m=v.size,v},()=>({paths:m})):new Set,f=0,g=a?HC():N("dead.mention-reference-counts",()=>{let v=UC(e,p,d.map(C=>C.symbolId));return f=v.size,v},()=>({definitions:d.length,symbolsWithReferences:f})),h=0,b=a?N("dead.mentioned-symbol-ids",()=>{let v=qC(e,d.map(C=>C.symbolId),p,{conservative:p.size===0});return h=v.size,v},()=>({definitions:d.length,referencedSymbols:h})):new Set,S=a?d.filter(v=>!b.has(v.symbolId)):d.filter(v=>!Ec(g,v.symbolId,v.relativePath));a?N("dead.source-fallback.dead-code-only",()=>N$(e,S,g,{inactiveBarrelPaths:p}),()=>({definitions:S.length,testReferencesIncluded:!0})):N("dead.source-fallback.ast",()=>F$(e,S,g,{inactiveBarrelPaths:p}),()=>({definitions:S.length,testReferencesIncluded:!0}));let y=a?S.filter(v=>!em(g,v.symbolId)):S.filter(v=>!Ec(g,v.symbolId,v.relativePath));N("dead.caller-map-supplement",()=>$$(e,y,g,{inactiveBarrelPaths:p,includeSemantic:!a&&l}),()=>({definitions:y.length,semantic:!a&&l}));let x=a?S.filter(v=>!em(g,v.symbolId)):d;return A$(e,T$(x,g))}function P$(e,t){let n=BC(e),r=[];for(let i of Zi(e,{scope:t.scope,symbolMatches:Rc,sqlPrefilter:"function-like"}))jC(i,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n,isDeclarationOnlyCallable:()=>M$(e,i),isFrameworkContractCallable:()=>_i(e,i)}).accepted&&r.push(i);return r}var D$=["method_signature","abstract_method_signature","call_signature","construct_signature"];function M$(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=J(e,t.relativePath);if(n)return n.rootNode.descendantsOfType([...D$]).some(i=>i.startPosition.row<=t.startLine&&i.endPosition.row>=t.endLine);let r=V(e,t.relativePath).slice(t.startLine,t.endLine+1).join(`
|
|
121
|
-
`).trim();return r.endsWith(";")&&!r.includes("=>")&&!r.includes("{")}function T$(e,t){return e.map(n=>k$(n,t)).filter(n=>n.cross_file_refs===0).sort((n,r)=>r.loc-n.loc||n.relative_path.localeCompare(r.relative_path)||n.start_line-r.start_line)}function k$(e,t){let n=t.get(e.symbolId)??new Map,r=GC(n.get(e.relativePath)),i=0;for(let[o,s]of n)o!==e.relativePath&&(i+=s.occurrences);return{relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine,loc:e.endLine-e.startLine+1,symbol:e.symbol,parent_type_name:e.parentTypeName,same_file_refs:r,cross_file_refs:i}}function A$(e,t){let n=Qd(e),r=[],i=0,o=0,s=0,a=0,c=0,l=0;for(let u of t){if(e.isIgnored(u.relative_path))continue;if(Ue(e,u.relative_path)){a++;continue}if(Te(e,u.symbol,u.relative_path)){c++;continue}let d=n(u.relative_path,u.start_line,u.symbol,u.parent_type_name),m=d?.disposition==="implicit-usage"?d.reason:void 0,p=m?"implicit-usage":u.same_file_refs===0?"dead-code":"file-internal";p==="dead-code"?i++:p==="file-internal"?o++:s++,l+=u.loc,r.push({relativePath:u.relative_path,startLine:u.start_line,endLine:u.end_line,loc:u.loc,symbol:u.symbol,shortName:T(u.symbol),sameFileRefs:u.same_file_refs,kind:p,...m?{implicitUsageReason:m}:{}})}return{symbols:r,counts:{total:r.length,deadCode:i,fileInternal:o,implicitUsage:s,loc:l},applicability:{entrySurfaceExcluded:a,externalRootExcluded:c,implicitUsageSignals:s},totalCount:r.length,deadCodeCount:i,fileInternalCount:o,implicitUsageCount:s,totalLoc:l}}function F$(e,t,n,r){if(t.length===0)return;let i=new H(e),o=new Set(t.map(c=>c.symbolId)),s=new Set(t.map(c=>c.leaf).filter(Boolean)),a=new Set(i.sourceFiles());for(let c of Z(e))a.add(c);i.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:c=>r.inactiveBarrelPaths.has(c)},c=>{o.has(c.target.symbolId)&&(O$(e,c)||Ic(n,c.target.symbolId,c.sourceFile,B$(c),"source-fallback"))})}function N$(e,t,n,r){if(t.length===0)return;let i=new H(e),o=hf(t),s=new Set(i.sourceFiles());for(let u of Z(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=wf(e,u),c.set(u,d)),d};i.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>r.inactiveBarrelPaths.has(u),resolveTargets:({sourceFile:u,name:d,kind:m})=>{let p=o.get(d);return p?_$(u,d,p,()=>l(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),$C(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&WC(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||Ic(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function _$(e,t,n,r,i){let o=n.filter(l=>l.relativePath===e);if(o.length>0)return o;if(!i.permissive&&n.length===1)return[...n];let s=r(),a=s.get(t);if(a)for(let l of a){let u=n.filter(d=>Fe(l,d.relativePath));if(u.length>0)return u}let c=new Set;for(let l of s.values())for(let u of l)c.add(u);for(let l of c){let u=n.filter(d=>Fe(l,d.relativePath));if(u.length>0&&u.length===n.length)return u}return i.permissive?[...n]:[]}function O$(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&WC(e,t)}function B$(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function WC(e,t){return t.occurrences>1?!1:ae(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function $$(e,t,n,r){let i=r.includeSemantic!==!1,o=i&&t.length>=w$&&Z(e).length>=L$,s=(u,d)=>{d===u.relativePath||e.isIgnored(d)||r.inactiveBarrelPaths.has(d)||zC(n,u.symbolId,d,1,"caller-map")};if(o?N("dead.caller-map.per-symbol-non-semantic",()=>{let u=hn(e,t,{semantic:!1,semanticEvidence:re});for(let d of t){let m=u.get(d.symbolId)??[];for(let p of m)s(d,p.file)}},()=>({definitions:t.length,semantic:!1,batched:!0})):N("dead.caller-map.per-symbol",()=>{for(let u of t){let d=Gn(e,u,{semantic:i,semanticEvidence:re});if(d.length!==0)for(let m of d)s(u,m.file)}},()=>({definitions:t.length,semantic:i})),!o)return;let a=0,c=N("dead.caller-map.semantic-candidates",()=>{let u=t.filter(d=>!Ec(n,d.symbolId,d.relativePath));return a=u.length,u},()=>({definitions:t.length,semanticCandidates:a}));if(c.length===0)return;let l=Ry(e,c);for(let u of c){let d=l.get(u.symbolId);if(d)for(let m of d)s(u,m)}}function j$(e,t={}){let{limit:n=30,scope:r}=t,i=r?"AND def_d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[],a=e.all(`SELECT
|
|
122
|
-
gs.symbol,
|
|
123
|
-
COUNT(*) AS ref_count,
|
|
124
|
-
COUNT(DISTINCT ref_d.id) AS file_count,
|
|
125
|
-
def_d.relative_path AS defined_in
|
|
126
|
-
FROM mentions m
|
|
127
|
-
JOIN chunks c ON m.chunk_id = c.id
|
|
128
|
-
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
129
|
-
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
130
|
-
JOIN (
|
|
131
|
-
SELECT m2.symbol_id, c2.document_id
|
|
132
|
-
FROM mentions m2
|
|
133
|
-
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
134
|
-
WHERE m2.role = 1
|
|
135
|
-
GROUP BY m2.symbol_id
|
|
136
|
-
) sym_def ON sym_def.symbol_id = gs.id
|
|
137
|
-
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
138
|
-
WHERE m.role != 1
|
|
139
|
-
AND def_d.id != ref_d.id
|
|
140
|
-
${e.pathExclusionsFor("def_d")}
|
|
141
|
-
${e.symbolNoiseFor("gs")}
|
|
142
|
-
${i}
|
|
143
|
-
GROUP BY gs.id
|
|
144
|
-
ORDER BY ref_count DESC
|
|
145
|
-
LIMIT ?`,...o,n).filter(c=>!e.isIgnored(c.defined_in)).map(c=>({symbol:c.symbol,shortName:T(c.symbol),refCount:c.ref_count,fileCount:c.file_count,definedIn:c.defined_in,basis:"scip-cross-file-mentions",countUnit:"reference-occurrences"}));return a.length>0?a:H$(e,r,n)}function H$(e,t,n){return Le(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>U$(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function U$(e,t){let r=Gn(e,t,{limit:500,semanticEvidence:re}).filter(i=>i.file!==t.relativePath);return{symbol:t.symbol,shortName:T(t.symbol),refCount:r.length,fileCount:new Set(r.map(i=>i.file)).size,definedIn:t.relativePath,basis:"source-backed-incoming-evidence",countUnit:"distinct-incoming-evidence-rows"}}function q$(e,t,n={}){return Z$(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function G$(e,t){let n=ne(e,t),r=W$(e,t);if(r.length>0&&!Y$(n))return r;let i=V$(e,t,n);return tm(t)&&i.length>0?i:J$([...r,...i])}function z$(e,t,n={}){let r=mt(e,t);if(!r)return[];let i=YC(e,r),o=n.semantic===!1?null:VC(e,r);return(o?K$(o,i):i).filter(a=>!a.used).map(a=>({symbol:a.symbol,shortName:a.shortName,importedIn:a.importer}))}function K$(e,t){let n=new Map;for(let i of t){let o=n.get(i.shortName);o?o.push(i):n.set(i.shortName,[i])}let r=e.map(i=>{let o=n.get(i.shortName),s=o?.shift();return o?.length===0&&n.delete(i.shortName),s?{...i,used:i.used||s.used}:i});return r.push(...[...n.values()].flat()),r}function W$(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
|
|
146
|
-
FROM mentions m
|
|
147
|
-
JOIN chunks c ON m.chunk_id = c.id
|
|
148
|
-
JOIN documents d ON c.document_id = d.id
|
|
149
|
-
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
150
|
-
WHERE gs.symbol LIKE ?
|
|
151
|
-
AND m.role = 2
|
|
152
|
-
ORDER BY d.relative_path`,`%${t}%`).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:T(r.symbol),fromFile:r.importer}))}function V$(e,t,n=ne(e,t)){let r=n?.relativePath??null,i=n?z(n.symbol):t.replace(/\(\)$/,""),o=n?me(n.symbol):!1,s=new Set;for(let c of Z(e,{includeIgnored:!1}))for(let l of ae(e,c))X$(l,c,{targetFile:r,targetLeaf:i,targetIsModule:o,targetPattern:t})&&s.add(c);let a=tm(t)?t.trim():null;return[...s].sort().map(c=>({symbol:a??n?.symbol??i,shortName:a??(n?T(n.symbol):i),fromFile:c}))}function Y$(e){return!!(e&&(e.symbol.startsWith("scip-clojure ")||se(e.relativePath)==="clojure"))}function J$(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.fromFile}`;t.has(i)||(t.add(i),n.push(r))}return n.sort((r,i)=>r.fromFile.localeCompare(i.fromFile)||r.shortName.localeCompare(i.shortName))}function X$(e,t,n){return!e.sourcePath||n.targetFile&&it(e.sourcePath)!==it(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&rj(t)||e.kind==="namespace"&&Q$(e,n.targetPattern)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function Q$(e,t){let n=t.trim().replace(/\(\)$/,"");return tm(n)?e.importedName===n||e.localName===n:!1}function tm(e){let t=e.trim().replace(/\(\)$/,"");return t.includes(".")&&!t.includes("/")&&!t.includes(":")}function Z$(e,t,n={}){let r=mt(e,t);return r?ej(e,r,n)??(n.semantic===!1?null:VC(e,r))??YC(e,r):null}function ej(e,t,n){let i=e.all(`SELECT DISTINCT
|
|
153
|
-
gs.symbol,
|
|
154
|
-
def_d.relative_path AS from_file,
|
|
155
|
-
imp_d.relative_path AS importer,
|
|
156
|
-
EXISTS (
|
|
157
|
-
SELECT 1
|
|
158
|
-
FROM mentions ref_m
|
|
159
|
-
JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
|
|
160
|
-
WHERE ref_m.symbol_id = gs.id
|
|
161
|
-
AND ref_m.role != 1
|
|
162
|
-
AND ref_c.document_id = imp_d.id
|
|
163
|
-
) AS used
|
|
164
|
-
FROM mentions m
|
|
165
|
-
JOIN chunks c ON m.chunk_id = c.id
|
|
166
|
-
JOIN documents imp_d ON c.document_id = imp_d.id
|
|
167
|
-
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
168
|
-
LEFT JOIN (
|
|
169
|
-
SELECT m2.symbol_id, c2.document_id
|
|
170
|
-
FROM mentions m2
|
|
171
|
-
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
172
|
-
WHERE m2.role = 1
|
|
173
|
-
GROUP BY m2.symbol_id
|
|
174
|
-
) sym_def ON sym_def.symbol_id = gs.id
|
|
175
|
-
LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
176
|
-
WHERE imp_d.relative_path = ?
|
|
177
|
-
AND m.role = 2
|
|
178
|
-
ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(i.length>0){let o=n.semantic===!1?[]:Po(e,t);return i.map(s=>({symbol:s.symbol,shortName:T(s.symbol),fromFile:s.from_file??"(external)",importer:s.importer,used:s.used!==0||o.some(a=>a.isUsed&&a.sourcePath===s.from_file)}))}return null}function VC(e,t){let n=Po(e,t);return n.length>0?n.map(r=>{let i=JC(r.importedName,r.localName,r.kind);return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:r.kind==="side-effect"?!0:r.isUsed}}):null}function YC(e,t){let n=tj(t,W(e,t));return ae(e,t).map(r=>{let i=JC(r.importedName,r.localName,r.kind),o=r.kind==="side-effect"||nj(t,r)||n.has(r.localName??r.importedName)?!0:r.used;return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:o}})}function tj(e,t){let n=new Set;if(se(e)!=="python")return n;let r=/(?:^|\n)\s*__all__\s*(?:\+?=)\s*[[(]([\s\S]*?)[\])]/g;for(let i of t.matchAll(r)){let o=i[1]??"";for(let s of o.matchAll(/(['"])([A-Za-z_]\w*)\1/g))n.add(s[2])}return n}function nj(e,t){if(se(e)!=="rust"||t.used||t.kind==="side-effect")return!1;let n=t.localName??t.importedName;return n==="_"||/^[A-Z]/.test(n)}function JC(e,t,n){return n==="namespace"&&e==="*"&&t?`* as ${t}`:n==="default"&&t?`default as ${t}`:n==="side-effect"?"(side effect import)":t&&t!==e?`${e} as ${t}`:e}function rj(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function ij(e,t){let n=ne(e,t);if(!n)return[];let i=new H(e).definitionsForFile(n.relativePath).filter(o=>o.symbol!==n.symbol).filter(o=>ff(n.symbol,o.symbol)).sort((o,s)=>o.startLine-s.startLine||o.endLine-s.endLine).map(o=>({symbol:o.symbol,shortName:T(o.symbol),startLine:o.startLine,endLine:o.endLine,kind:wt(o.symbol)??"unknown"}));return se(n.relativePath)!=="clojure"?i:sj(i,oj(e,n))}function oj(e,t){let n=z(t.symbol);if(!n)return[];let r=T(t.symbol);return(K(e,t.relativePath)?.clojureMembers??[]).filter(i=>i.ownerName===n).map(i=>({symbol:`${t.symbol}${i.memberName}().`,shortName:`${r}:${i.memberName}()`,startLine:i.startLine,endLine:i.endLine,kind:i.memberKind}))}function sj(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.shortName}:${r.startLine}:${r.endLine}`,r);return[...n.values()].sort((r,i)=>r.startLine-i.startLine||r.endLine-i.endLine)}function aj(e,t){let n=ne(e,t);if(!n)return[];let r=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
|
|
179
|
-
FROM mentions m
|
|
180
|
-
JOIN chunks c ON m.chunk_id = c.id
|
|
181
|
-
JOIN (
|
|
182
|
-
SELECT m2.symbol_id, c2.document_id
|
|
183
|
-
FROM mentions m2
|
|
184
|
-
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
185
|
-
WHERE m2.role = 1
|
|
186
|
-
GROUP BY m2.symbol_id
|
|
187
|
-
) sym_def ON sym_def.symbol_id = m.symbol_id
|
|
188
|
-
WHERE m.symbol_id = ?
|
|
189
|
-
AND m.role != 1
|
|
190
|
-
AND sym_def.document_id != c.document_id`,n.symbolId);return[{name:T(n.symbol),count:r?.file_count??0,symbol:n.symbol,definedIn:n.relativePath}]}function cj(e,t){let n=mt(e,t);return n?e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
|
|
191
|
-
FROM mentions m
|
|
192
|
-
JOIN chunks c ON m.chunk_id = c.id
|
|
193
|
-
JOIN documents d ON c.document_id = d.id
|
|
194
|
-
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
195
|
-
JOIN (
|
|
196
|
-
SELECT m2.symbol_id, c2.document_id
|
|
197
|
-
FROM mentions m2
|
|
198
|
-
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
199
|
-
WHERE m2.role = 1
|
|
200
|
-
GROUP BY m2.symbol_id
|
|
201
|
-
) sym_def ON sym_def.symbol_id = gs.id
|
|
202
|
-
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
203
|
-
WHERE d.relative_path = ?
|
|
204
|
-
AND m.role != 1
|
|
205
|
-
AND def_d.id != d.id
|
|
206
|
-
GROUP BY d.id
|
|
207
|
-
ORDER BY symbol_count DESC`,n).filter(o=>!e.isIgnored(o.relative_path)).map(o=>({name:o.relative_path,count:o.symbol_count,file:o.relative_path,basis:"external-symbol-references"})):[]}function lj(e,t={}){return uj(e,t).map(n=>({name:T(n.symbol),count:n.file_count,symbol:n.symbol,definedIn:n.defined_in}))}function uj(e,t){let{limit:n=30,scope:r}=t,i=r?"AND def_d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[];return e.all(`SELECT gs.symbol,
|
|
208
|
-
COUNT(DISTINCT c.document_id) AS file_count,
|
|
209
|
-
def_d.relative_path AS defined_in
|
|
210
|
-
FROM mentions m
|
|
211
|
-
JOIN chunks c ON m.chunk_id = c.id
|
|
212
|
-
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
213
|
-
JOIN (
|
|
214
|
-
SELECT m2.symbol_id, c2.document_id
|
|
215
|
-
FROM mentions m2
|
|
216
|
-
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
217
|
-
WHERE m2.role = 1
|
|
218
|
-
GROUP BY m2.symbol_id
|
|
219
|
-
) sym_def ON sym_def.symbol_id = gs.id
|
|
220
|
-
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
221
|
-
WHERE m.role != 1
|
|
222
|
-
AND def_d.id != c.document_id
|
|
223
|
-
${e.pathExclusionsFor("def_d")}
|
|
224
|
-
${e.symbolNoiseFor("gs")}
|
|
225
|
-
${i}
|
|
226
|
-
GROUP BY gs.id
|
|
227
|
-
HAVING file_count > 1
|
|
228
|
-
ORDER BY file_count DESC
|
|
229
|
-
LIMIT ?`,...o,n)}function dj(e,t={}){let{limit:n=30,scope:r}=t,i=r?"AND d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[];return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
|
|
230
|
-
FROM mentions m
|
|
231
|
-
JOIN chunks c ON m.chunk_id = c.id
|
|
232
|
-
JOIN documents d ON c.document_id = d.id
|
|
233
|
-
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
234
|
-
JOIN (
|
|
235
|
-
SELECT m2.symbol_id, c2.document_id
|
|
236
|
-
FROM mentions m2
|
|
237
|
-
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
238
|
-
WHERE m2.role = 1
|
|
239
|
-
GROUP BY m2.symbol_id
|
|
240
|
-
) sym_def ON sym_def.symbol_id = gs.id
|
|
241
|
-
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
242
|
-
WHERE m.role != 1
|
|
243
|
-
AND def_d.id != d.id
|
|
244
|
-
${e.pathExclusionsFor("d")}
|
|
245
|
-
${e.symbolNoiseFor("gs")}
|
|
246
|
-
${i}
|
|
247
|
-
GROUP BY d.id
|
|
248
|
-
ORDER BY symbol_count DESC
|
|
249
|
-
LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}))}var XC=`SELECT COUNT(*) AS shared
|
|
250
|
-
FROM (
|
|
251
|
-
SELECT definition_m.symbol_id
|
|
252
|
-
FROM documents definition_d
|
|
253
|
-
JOIN chunks definition_c ON definition_c.document_id = definition_d.id
|
|
254
|
-
JOIN mentions definition_m ON definition_m.chunk_id = definition_c.id
|
|
255
|
-
AND definition_m.role = 1
|
|
256
|
-
JOIN mentions reference_m ON reference_m.symbol_id = definition_m.symbol_id
|
|
257
|
-
AND reference_m.role != 1
|
|
258
|
-
JOIN chunks reference_c ON reference_c.id = reference_m.chunk_id
|
|
259
|
-
JOIN documents reference_d ON reference_d.id = reference_c.document_id
|
|
260
|
-
WHERE definition_d.relative_path = ?
|
|
261
|
-
AND reference_d.relative_path = ?
|
|
262
|
-
UNION
|
|
263
|
-
SELECT definition_m.symbol_id
|
|
264
|
-
FROM documents definition_d
|
|
265
|
-
JOIN chunks definition_c ON definition_c.document_id = definition_d.id
|
|
266
|
-
JOIN mentions definition_m ON definition_m.chunk_id = definition_c.id
|
|
267
|
-
AND definition_m.role = 1
|
|
268
|
-
JOIN mentions reference_m ON reference_m.symbol_id = definition_m.symbol_id
|
|
269
|
-
AND reference_m.role != 1
|
|
270
|
-
JOIN chunks reference_c ON reference_c.id = reference_m.chunk_id
|
|
271
|
-
JOIN documents reference_d ON reference_d.id = reference_c.document_id
|
|
272
|
-
WHERE definition_d.relative_path = ?
|
|
273
|
-
AND reference_d.relative_path = ?
|
|
274
|
-
)`;function mj(e,t,n){let r=mt(e,t)??t,i=mt(e,n)??n,o=e.get(XC,r,i,i,r);return{...QC(r,i,o?.shared??0)}}function pj(e,t={}){let{limit:n=20,scope:r}=t,i=r?"AND def_d.relative_path LIKE ? AND ref_d.relative_path LIKE ?":"",o=r?[`%${r}%`,`%${r}%`]:[];return e.all(`SELECT
|
|
275
|
-
CASE WHEN def_d.relative_path < ref_d.relative_path THEN def_d.relative_path ELSE ref_d.relative_path END AS file1,
|
|
276
|
-
CASE WHEN def_d.relative_path < ref_d.relative_path THEN ref_d.relative_path ELSE def_d.relative_path END AS file2,
|
|
277
|
-
COUNT(DISTINCT gs.id) AS shared
|
|
278
|
-
FROM mentions m
|
|
279
|
-
JOIN chunks c ON m.chunk_id = c.id
|
|
280
|
-
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
281
|
-
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
282
|
-
JOIN (
|
|
283
|
-
SELECT m2.symbol_id, c2.document_id
|
|
284
|
-
FROM mentions m2
|
|
285
|
-
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
286
|
-
WHERE m2.role = 1
|
|
287
|
-
GROUP BY m2.symbol_id
|
|
288
|
-
) sym_def ON sym_def.symbol_id = gs.id
|
|
289
|
-
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
290
|
-
WHERE m.role != 1
|
|
291
|
-
AND def_d.id != ref_d.id
|
|
292
|
-
${e.pathExclusionsFor("def_d","ref_d")}
|
|
293
|
-
${i}
|
|
294
|
-
GROUP BY file1, file2
|
|
295
|
-
ORDER BY shared DESC, file1, file2
|
|
296
|
-
LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.file1)&&!e.isIgnored(a.file2)).map(a=>QC(a.file1,a.file2,a.shared))}function QC(e,t,n){return{file1:e,file2:t,sharedSymbols:n,actionTier:"signal",couplingKind:"shared-symbol-coupling",evidenceReasons:[`${n} symbol(s) are defined in one file and referenced by the other`],recommendation:"Review whether the shared symbol surface is an intentional boundary or hidden coordination pressure before moving code."}}function Kr(e){let t=new Map,n=[],r=new Map,i=new Map,o=new Set,s=[],a=0,c=l=>(e.get(l)??[]).values();for(let l of e.keys()){if(r.has(l))continue;let u=[];for(r.set(l,a),i.set(l,a),a+=1,s.push(l),o.add(l),u.push({node:l,iter:c(l),pendingChild:null});u.length>0;){let d=u[u.length-1];if(d.pendingChild!==null){let f=d.pendingChild;d.pendingChild=null,i.set(d.node,Math.min(i.get(d.node),i.get(f)))}let m=d.iter.next();if(m.done){if(i.get(d.node)===r.get(d.node)){let f=[];for(;;){let g=s.pop();if(o.delete(g),f.push(g),t.set(g,n.length),g===d.node)break}n.push(f)}u.pop();continue}let p=m.value;r.has(p)?o.has(p)&&i.set(d.node,Math.min(i.get(d.node),r.get(p))):(r.set(p,a),i.set(p,a),a+=1,s.push(p),o.add(p),d.pendingChild=p,u.push({node:p,iter:c(p),pendingChild:null}))}}return{components:n,componentOf:t}}function es(e,t={}){return tx(e,t).cycles}function tx(e,t={}){return nx(e,t)}function nx(e,t={}){let{scope:n,maxDepth:r=10,edgeBasis:i="symbol-references"}=t,o=Me(e,n,i==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-only"}:void 0),{components:s}=Kr(o),a=s.filter(c=>fj(o,c)).map(c=>{let l=[...c].sort(),u=gj(o,l),d=yj(u);return{path:u,component:l,edgeBasis:i,witness:!0,classification:d==="real"?"dependency-cycle":"module-structure-candidate",kind:d}});return a.sort((c,l)=>c.kind!==l.kind?c.kind==="real"?-1:1:c.path.length-l.path.length),{cycles:a,truncated:!1,edgeBasis:i,maxDepth:r}}function fj(e,t){if(t.length>1)return!0;let n=t[0];return n!==void 0&&e.get(n)?.has(n)===!0}function gj(e,t){let n=t[0];if(!n)return[];let r=new Set(t);for(let i of[...e.get(n)??[]].filter(o=>r.has(o)).sort()){if(i===n)return[n,n];let o=hj(e,i,n,r);if(o)return[n,...o]}throw new Error(`Cyclic component did not contain a witness path from ${n}.`)}function hj(e,t,n,r){let i=[t],o=new Map([[t,null]]);for(let s=0;s<i.length;s+=1){let a=i[s];if(a===n){let c=[];for(let l=a;l!==null;l=o.get(l)??null)c.push(l);return c.reverse()}for(let c of[...e.get(a)??[]].filter(l=>r.has(l)).sort())o.has(c)||(o.set(c,a),i.push(c))}return null}function yj(e){for(let r of e){let i=q(r);if(i==="test"||i==="barrel"||i==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":Ei(t)||Ei(n)||ZC(t,n)||ZC(n,t)||ex(t,n)||ex(n,t)||q(t)==="entry"||q(n)==="entry"?"module-hierarchy":"real"}function ZC(e,t){if(!e.endsWith(".rs")||!t.endsWith(".rs"))return!1;let n=t.replace(/\.rs$/,"/");return e.startsWith(n)?!e.slice(n.length).includes("/"):!1}function ex(e,t){if(!e.endsWith(".rs")||!t.endsWith(".rs"))return!1;let n=e.replace(/\.rs$/,""),r=t.replace(/\.rs$/,"");if(n===r+"_tests"||n===r+"/tests")return!0;let i=e.split("/"),o=t.split("/");if(i.length===o.length&&i.includes("tests")&&o.includes("src")){let s=i[i.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}function lr(e,t){let n=rx(e),r=rx(t);if(n.endsWith("/**")){let i=n.slice(0,-3);return r===i||r.startsWith(`${i}/`)}if(n.endsWith("/*")){let i=n.slice(0,-2);if(!r.startsWith(`${i}/`))return!1;let o=r.slice(i.length+1);return o.length>0&&!o.includes("/")}return n==="**"?!0:n==="*"?r.length>0&&!r.includes("/"):n===r}function rx(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}import{readdirSync as bj}from"fs";import{join as ix}from"path";function Sj(e){return ox(e).replace(/\/\*\*?$/,"")}function wc(e,t){let n=ox(t),r=Sj(n),i=n.endsWith("/**"),o=[],s=(a,c)=>{let l;try{l=bj(a,{withFileTypes:!0})}catch{return}for(let u of l){if(u.name.startsWith("."))continue;let d=c?`${c}/${u.name}`:u.name;lr(n,d)&&o.push(d),i&&u.isDirectory()&&s(ix(a,u.name),d)}};return s(ix(e,r),r),o.sort()}function ox(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}var vj=/\.(test|spec)\.(ts|tsx|js|jsx|mts|cts)$/,sx=new Map;function ax(e,t,n,r){if(!t?.testPaths?.length)return[];let i=Cj(t),o=[];for(let s of xj(e,t.testPaths)){let a=Rj(e,s,r),c=a?n(a):null;if(c)for(let l of ae(e,s)){let u=l.sourcePath;if(!u)continue;let d=n(u);d&&d!==c&&(i.get(c)?.has(d)||o.push({testFile:s,ownerBoundary:c,importedFile:u,importedBoundary:d,reason:"outside-owner-policy"}))}}return Ej(o)}function Cj(e){let t=e.allowedDependencies??{},n=e.boundaries.map(s=>s.name),r=new Map,i=(s,a)=>{for(let c of t[s]??[])a.has(c)||(a.add(c),i(c,a))};for(let s of n){let a=new Set;i(s,a),r.set(s,a)}let o=new Map;for(let s of n){let a=new Set(r.get(s));for(let c of n)c!==s&&r.get(c)?.has(s)&&a.add(c);o.set(s,a)}return o}function xj(e,t){let n=`${e.config.projectRoot}\0${t.join("\0")}`,r=sx.get(n);if(r)return r;let i=new Set;for(let s of t)for(let a of wc(e.config.projectRoot,s))vj.test(a)&&i.add(a);let o=[...i].sort();return sx.set(n,o),o}function Rj(e,t,n){let r=t.replace(/^tests\//,"src/").replace(/\.(test|spec)\.(\w+)$/,".$2");if(r!==t&&n(r))return r;let i=t.split("/").pop().replace(/\.(test|spec)\.(\w+)$/,".$2"),o=ae(e,t).map(s=>s.sourcePath).filter(s=>!!s&&n(s)&&s.split("/").pop()===i);return o.length===1?o[0]:null}function Ej(e){let t=new Map;for(let n of e){let r=`${n.testFile}\0${n.importedBoundary}`;t.has(r)||t.set(r,n)}return[...t.values()].sort((n,r)=>n.testFile.localeCompare(r.testFile)||n.importedBoundary.localeCompare(r.importedBoundary))}function cx(e,t){let n=(e?.boundaries??[]).filter(r=>r.paths.some(i=>lr(i,t)));return n.length===1?n[0].name:null}var Pn="architecture:";function lx(e,t,n,r={}){let i=wj(e,t);if(!n||n.boundaries.length===0)return{configured:!1,boundaries:[],edges:[],forbiddenEdges:[],reciprocalPairs:[],cycles:[],coarseBoundaries:[],staleAllowances:[],boundaryLimits:[],fragileEdges:[],testBoundaryViolations:[],coverage:{totalFiles:i.length,mappedFiles:0,unmappedFiles:[],ambiguousFiles:[]},policyCoverage:{declaredRows:0,totalBoundaries:0,missingRows:[],requiresCompletePolicy:!1,requiresCompleteCoverage:!1,requiresMinimalPolicy:!1}};let o=new Map,s=new Map(n.boundaries.map(y=>[y.name,new Set])),a=[],c=[];for(let y of i){let x=n.boundaries.filter(v=>v.paths.some(C=>lr(C,y))).map(v=>v.name).sort();if(x.length===0)a.push(y);else if(x.length>1)c.push({file:y,boundaries:x});else{let v=x[0];o.set(y,v),s.get(v).add(y)}}let l=new Map;for(let[y,x]of e){let v=o.get(y);if(v)for(let C of x){let R=o.get(C);if(!R||v===R)continue;let E=Oi(v,R),w=l.get(E);w||(w={from:v,to:R,fileEdges:[],importers:new Set,importedFiles:new Set},l.set(E,w)),w.fileEdges.push({fromFile:y,toFile:C}),w.importers.add(y),w.importedFiles.add(C)}}let u=[...l.values()].map(y=>Lj(y,n)).sort(Nj),d=u,m=new Map(d.map(y=>[Oi(y.from,y.to),y])),p=new Map(n.boundaries.map(y=>[y.name,new Set]));for(let y of d)p.get(y.from).add(y.to);let f=[];for(let y of d){if(y.from>=y.to)continue;let x=m.get(Oi(y.to,y.from));x&&f.push({boundaries:[y.from,y.to],forward:y,reverse:x})}let{components:g}=Kr(p),h=g.filter(y=>y.length>1).map(y=>Dj(y,d,n.requireAcyclic===!0)).sort((y,x)=>x.boundaries.length-y.boundaries.length||y.boundaries.join("/").localeCompare(x.boundaries.join("/"))),b=n.allowedDependencies??{},S=n.boundaries.map(y=>y.name).filter(y=>!Object.hasOwn(b,y)).sort();return{configured:!0,boundaries:n.boundaries.map(y=>({name:y.name,paths:[...y.paths],fileCount:s.get(y.name).size,dependencyPolicyDeclared:Object.hasOwn(b,y.name)})).sort((y,x)=>y.name.localeCompare(x.name)),edges:u,forbiddenEdges:d.filter(y=>y.policyStatus==="forbidden"),reciprocalPairs:f,cycles:h,staleAllowances:Tj(n,d),boundaryLimits:kj(n,d,s),fragileEdges:d.filter(y=>y.fragile),testBoundaryViolations:r.testBoundaryViolations??[],coarseBoundaries:Mj(e,s,r.isModuleHierarchyFile,n.requireResolvedBoundaries===!0,y=>n.boundaries.find(x=>x.name===y)?.subUnits??"directory"),coverage:{totalFiles:i.length,mappedFiles:o.size,unmappedFiles:a,ambiguousFiles:c},policyCoverage:{declaredRows:n.boundaries.length-S.length,totalBoundaries:n.boundaries.length,missingRows:S,requiresCompletePolicy:n.requireCompletePolicy===!0,requiresCompleteCoverage:n.requireCompleteCoverage===!0,requiresMinimalPolicy:n.requireMinimalPolicy===!0}}}function ts(e,t={}){let n=Me(e,t.scope,{scipEdges:"imports-only",sourceEdges:"imports-and-reexports"}),r=Z(e,{includeIgnored:!1}).filter(o=>!t.scope||o.includes(t.scope)),i=new Set(r);return lx(n,r,e.config.architecture,{isModuleHierarchyFile:o=>Ij(e,o),testBoundaryViolations:ax(e,e.config.architecture,o=>cx(e.config.architecture,o),o=>i.has(o))})}function Ij(e,t){let n=q(t);return n==="test"||n==="entry"?!0:n!=="barrel"?!1:U(e,t).length===0}function nm(e){let t=e.forbiddenEdges.map(r=>`${Pn}forbidden-edge:${encodeURIComponent(r.from)}:${encodeURIComponent(r.to)}`);if(e.policyCoverage.requiresCompletePolicy)for(let r of e.policyCoverage.missingRows)t.push(`${Pn}missing-policy-row:${encodeURIComponent(r)}`);if(e.policyCoverage.requiresCompleteCoverage){for(let r of e.coverage.unmappedFiles)t.push(`${Pn}unmapped-file:${encodeURIComponent(r)}`);for(let r of e.coverage.ambiguousFiles)t.push(`${Pn}ambiguous-file:${encodeURIComponent(r.file)}:${r.boundaries.map(i=>encodeURIComponent(i)).sort().join("|")}`)}if(e.policyCoverage.requiresMinimalPolicy)for(let r of e.staleAllowances)t.push(`${Pn}stale-allowance:${encodeURIComponent(r.from)}:${encodeURIComponent(r.to)}`);for(let r of e.testBoundaryViolations)t.push(`${Pn}test-boundary:${encodeURIComponent(r.testFile)}:${encodeURIComponent(r.importedBoundary)}`);for(let r of e.boundaryLimits)t.push(`${Pn}boundary-limit:${r.kind}:${encodeURIComponent(r.boundary)}`);let n=new Map;for(let r of e.coarseBoundaries)r.violatesPolicy&&n.set(r.boundary,(n.get(r.boundary)??0)+1);for(let[r,i]of n){let o=`${Pn}coarse-boundary:${encodeURIComponent(r)}`;t.push(o);for(let s=2;s<=i;s+=1)t.push(`${o}:component:${s}`)}for(let r of e.cycles)r.violatesPolicy&&t.push(`${Pn}cycle:${r.boundaries.map(i=>encodeURIComponent(i)).sort().join("|")}`);return[...new Set(t)].sort()}function wj(e,t){let n=new Set(t);for(let[r,i]of e){n.add(r);for(let o of i)n.add(o)}return[...n].sort()}function Lj(e,t){let n=[...e.fileEdges].sort((r,i)=>r.fromFile.localeCompare(i.fromFile)||r.toFile.localeCompare(i.toFile));return{from:e.from,to:e.to,policyStatus:Pj(t,e.from,e.to),fileEdgeCount:n.length,importerCount:e.importers.size,importedFileCount:e.importedFiles.size,examples:n.slice(0,5),fragile:n.length===1}}function Pj(e,t,n){return!e.allowedDependencies||!Object.hasOwn(e.allowedDependencies,t)?"undeclared":e.allowedDependencies[t].includes(n)?"allowed":"forbidden"}function Dj(e,t,n){let r=[...e].sort(),i=new Set(r),o=t.filter(a=>i.has(a.from)&&i.has(a.to)),s=Math.min(...o.map(a=>a.fileEdgeCount));return{boundaries:r,internalEdges:o,narrowestEdges:o.filter(a=>a.fileEdgeCount===s),violatesPolicy:n}}function Mj(e,t,n=Aj,r=!1,i=()=>"directory"){let o=[];for(let[s,a]of t){let c=i(s)==="file"?f=>f:Fj,l=[...a].filter(f=>!n(f));if(l.length<2)continue;let u=new Set(l),d=new Map,m=new Map;for(let f of l)m.set(c(f),new Set);for(let f of l)for(let g of e.get(f)??[]){if(!u.has(g))continue;let h=c(f),b=c(g);if(h===b)continue;let S=Oi(h,b),y=d.get(S);y||(y={from:h,to:b,fileEdges:[]},d.set(S,y)),y.fileEdges.push({fromFile:f,toFile:g}),m.get(h).add(b)}let{components:p}=Kr(m);for(let f of p){if(f.length<2)continue;let g=new Set(f),h=[...d.values()].filter(S=>g.has(S.from)&&g.has(S.to)).map(S=>({from:S.from,to:S.to,fileEdgeCount:S.fileEdges.length,examples:S.fileEdges.slice(0,5)})).sort((S,y)=>S.from.localeCompare(y.from)||S.to.localeCompare(y.to)),b=Math.min(...h.map(S=>S.fileEdgeCount));o.push({boundary:s,violatesPolicy:r,subUnits:[...f].sort(),internalEdges:h,narrowestEdges:h.filter(S=>S.fileEdgeCount===b)})}}return o.sort((s,a)=>a.subUnits.length-s.subUnits.length||s.boundary.localeCompare(a.boundary))}function Tj(e,t){let n=new Set(t.map(s=>Oi(s.from,s.to))),r=e.allowedDependencies??{},i=new Set(e.boundaries.map(s=>s.name)),o=[];for(let[s,a]of Object.entries(r))if(i.has(s))for(let c of a)!i.has(c)||n.has(Oi(s,c))||o.push({from:s,to:c});return o.sort((s,a)=>s.from.localeCompare(a.from)||s.to.localeCompare(a.to))}function kj(e,t,n){let r=[],i=new Map;for(let o of t)i.set(o.from,(i.get(o.from)??0)+1);for(let o of e.boundaries){if(e.maxBoundaryFanOut!==void 0){let a=i.get(o.name)??0;a>e.maxBoundaryFanOut&&r.push({boundary:o.name,kind:"fan-out",observed:a,limit:e.maxBoundaryFanOut})}let s=o.maxFiles??e.maxBoundaryFiles;if(s!==void 0){let a=n.get(o.name)?.size??0;a>s&&r.push({boundary:o.name,kind:"files",observed:a,limit:s})}}return r.sort((o,s)=>o.boundary.localeCompare(s.boundary)||o.kind.localeCompare(s.kind))}function Aj(e){let t=q(e);return t==="test"||t==="entry"}function Fj(e){let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)}function Oi(e,t){return`${e}\0${t}`}function Nj(e,t){return e.from.localeCompare(t.from)||e.to.localeCompare(t.to)}function _j(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:o=2,scanLimit:s}=t,a=new H(e),c=he(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s),l=t.semantic!==!1,u=hn(e,c,{limit:500,semantic:l,semanticEvidence:re});return c.map(m=>Oj(e,m,l,u.get(m.symbolId)??[])).filter(m=>m.fanIn>=i&&m.fanOut>=o).sort((m,p)=>p.score-m.score||p.fanIn-m.fanIn).slice(0,n)}function Oj(e,t,n,r){let i=[...new Set(r.map(m=>m.file))].sort(),o=[...new Set(r.filter(m=>m.source!=="caller-map-inversion"||m.callEvidence==="scip-chunk").map(m=>m.file))].sort(),s=new Map;for(let m of Pt(e,t,{limit:500,semantic:n,semanticEvidence:re})){if(m.file===t.relativePath)continue;let p=`${m.symbol}|${m.file}`;s.has(p)||s.set(p,{symbol:m.symbol,shortName:T(m.symbol),file:m.file,evidenceStrength:m.source==="scip-chunk"?"candidate":"exact",evidenceSource:m.source})}let a=[...s.values()].sort((m,p)=>m.file.localeCompare(p.file)||m.symbol.localeCompare(p.symbol)),c=i.length,l=a.length,u=c*l,d=a.filter(m=>m.evidenceStrength==="candidate").map(m=>m.symbol);return{symbol:t.symbol,shortName:T(t.symbol),fanIn:c,fanOut:l,callerFiles:i,candidateCallerFiles:o,externalCallees:a.map(({symbol:m,shortName:p,file:f})=>({symbol:m,shortName:p,file:f})),externalCalleeEvidence:a,candidateExternalCallees:d,inputBasis:"mixed-static-call-or-reference-evidence",score:u,definedIn:t.relativePath,actionTier:"signal",riskKind:"coordination-hotspot",evidenceReasons:[`${c} incoming file(s) reference this symbol`,`${l} distinct cross-file callee symbol(s) are reached from it`,`centrality score is ${u} (fan-in * fan-out)`,`${o.length} incoming file(s) and ${d.length} outgoing target(s) rely on candidate rather than exact call evidence`],recommendation:"Review ownership, API stability, and caller groups before changing this central symbol; do not refactor solely from graph centrality."}}function ns(e,t={}){let{scope:n,minLoc:r=3,scanLimit:i}=t,o=new H(e),s=t.semantic!==!1,a=0,c=N("isolated.candidates",()=>{let C=he(o.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:typeof i=="number"&&i>0}),i).filter(R=>!_i(e,R));return a=C.length,C},()=>({definitions:a})),l=0,u=N("isolated.strict-callees",()=>{let v=o.symbolsWithNonSelfCallees(c,{additive:!1,semantic:!1});return l=v.size,v},()=>({definitions:c.length,symbols:l})),d=c.filter(v=>!u.has(v.symbolId)),m=0,p=N("isolated.scip-callers",()=>{let v=o.crossFileCallerMap(d,{semantic:!1});return m=v.size,v},()=>({definitions:d.length,symbols:m})),f=new Set(p.keys());for(let v of o.frameworkReferencedSymbolIds(d))f.add(v);let g=d.filter(v=>!f.has(v.symbolId));if(s&&g.length>0){for(let v of Jn(e,g).keys())f.add(v);for(let v of o.symbolsWithNonSelfCallees(g,{additive:!1,semantic:!0}))u.add(v);g=g.filter(v=>!f.has(v.symbolId)).filter(v=>!u.has(v.symbolId))}let h=0,b=N("isolated.source-fallback-callers",()=>{let v=o.sourceFallbackCallerFiles(g,{skipPath:C=>q(C)==="test"});return h=v.size,v},()=>({definitions:g.length,symbols:h}));for(let v of b.keys())f.add(v);let S=g.filter(v=>!f.has(v.symbolId)),y=0,x=N("isolated.additive-callees",()=>{let v=o.symbolsWithNonSelfCallees(S,{additive:!0,semantic:s});return y=v.size,v},()=>({definitions:S.length,symbols:y}));for(let v of x)u.add(v);return S.filter(v=>!u.has(v.symbolId)).sort((v,C)=>ee(C)-ee(v)||v.relativePath.localeCompare(C.relativePath)||v.startLine-C.startLine).map(v=>({symbol:v.symbol,shortName:T(v.symbol),relativePath:v.relativePath,startLine:v.startLine,endLine:v.endLine,loc:ee(v)}))}import{SymbolInformation_Kind as Ke}from"@c4312/scip";var ux=500;function Bj(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=pg.get(n);if(r!==void 0)return r;for(let[i,o]of Qs)if(o.toLowerCase().includes(n))return i;return null}function $j(e,t,n={}){let{scope:r,limit:i=100}=n,o=Bj(t);return o===null?[]:Hj(e,r).map(a=>({row:a,resolvedKind:mx(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:T(a.symbol),kind:c,kindName:ro(c),relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function jj(e,t={}){let n=Uj(e,t.scope);for(let r of qj(e,t.scope)){let i=mx(r);i===null||i===0||n.set(i,(n.get(i)??0)+1)}return[...n.entries()].sort((r,i)=>i[1]-r[1]||r[0]-i[0]).map(([r,i])=>({kind:r,kindName:ro(r),count:i}))}function Hj(e,t){return Le(e,{scope:t}).map(Gj)}function Uj(e,t){let n=new Map;for(let r of dx(Z(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", "),o=e.all(`SELECT gs.kind AS kind, COUNT(*) AS count
|
|
297
|
-
FROM defn_enclosing_ranges der
|
|
298
|
-
JOIN global_symbols gs ON der.symbol_id = gs.id
|
|
299
|
-
JOIN documents d ON der.document_id = d.id
|
|
300
|
-
WHERE gs.kind IS NOT NULL
|
|
301
|
-
AND gs.kind != 0
|
|
302
|
-
AND gs.symbol NOT LIKE '%#'
|
|
303
|
-
AND d.relative_path IN (${i})
|
|
304
|
-
GROUP BY gs.kind`,...r);for(let s of o)n.set(s.kind,(n.get(s.kind)??0)+s.count)}return n}function qj(e,t){let n=[];for(let r of dx(Z(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", ");n.push(...e.all(`SELECT gs.symbol,
|
|
305
|
-
gs.kind,
|
|
306
|
-
gs.documentation,
|
|
307
|
-
gs.enclosing_symbol,
|
|
308
|
-
d.relative_path,
|
|
309
|
-
der.start_line,
|
|
310
|
-
der.end_line
|
|
311
|
-
FROM defn_enclosing_ranges der
|
|
312
|
-
JOIN global_symbols gs ON der.symbol_id = gs.id
|
|
313
|
-
JOIN documents d ON der.document_id = d.id
|
|
314
|
-
WHERE (gs.kind IS NULL OR gs.kind = 0 OR gs.symbol LIKE '%#')
|
|
315
|
-
${e.symbolNoiseFor("gs")}
|
|
316
|
-
AND d.relative_path IN (${i})
|
|
317
|
-
ORDER BY d.relative_path, der.start_line, der.end_line, gs.symbol`,...r))}return n}function dx(e){let t=[];for(let n=0;n<e.length;n+=ux)t.push(e.slice(n,n+ux));return t}function Gj(e){return{symbol:e.symbol,kind:e.kind,documentation:e.documentation,enclosing_symbol:e.enclosingSymbol,relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine}}function mx(e){return e.kind!==null&&e.kind!==0?zj(e.kind,e.symbol,e.documentation):Kj(e.symbol,e.documentation,e.enclosing_symbol)}function zj(e,t,n){let r=(n??"").toLowerCase();if(wt(t)==="type"){if(r.includes("type "))return Ke.TypeAlias;if(r.includes("interface "))return Ke.Interface;if(r.includes("struct "))return Ke.Struct;if(r.includes("trait "))return Ke.Trait;if(r.includes("class "))return Ke.Class}return e}function Kj(e,t,n){let r=Bn(e);if("kind"in r)return null;let i=r.descriptors,o=i[i.length-2]??null,s=wt(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?Ke.TypeAlias:a.includes("interface ")?Ke.Interface:a.includes("struct ")?Ke.Struct:a.includes("trait ")?Ke.Trait:a.includes("class ")?Ke.Class:Ke.Class:s==="method"?o?.suffix==="type"?Ke.Method:Ke.Function:s==="namespace"?Ke.Module:s!=="term"?null:a.includes("async def ")||a.includes("def ")?Ke.Function:(n?wt(n):o?.suffix??null)==="type"?Ke.Field:Ke.Variable}function Wj(e,t={}){let{limit:n=10,scope:r,minDepth:i=3,edgeBasis:o="symbol-references"}=t,s=Me(e,r,o==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-only"}:void 0),{components:a,componentOf:c}=Kr(s),l=new Map;for(let h=0;h<a.length;h++)l.set(h,new Set);for(let[h,b]of s){let S=c.get(h);for(let y of b){let x=c.get(y);x!==S&&l.get(S).add(x)}}let u=new Array(a.length),d=new Array(a.length);for(let h=0;h<a.length;h++){let b=[],S=0;for(let y of[...l.get(h)].sort((x,v)=>x-v)){let x=d[y];(x>S||x===S&&Vj(u[y],b,a)<0)&&(S=x,b=u[y])}u[h]=[h,...b],d[h]=1+S}function m(h){return u[h]}let p=a.map(h=>[...h].sort()),f=new Set,g=[];for(let h=0;h<a.length;h++){let S=m(h).map(v=>p[v]),y=S.map(v=>v[0]);if(S.length<i)continue;let x=y.join(" ");f.has(x)||(f.add(x),g.push(Yj(y,S,o)))}return g.sort((h,b)=>b.depth-h.depth||h.chain.join("\0").localeCompare(b.chain.join("\0"))),Jj(g).slice(0,n)}function Vj(e,t,n){if(t.length===0)return-1;let r=e.map(o=>[...n[o]].sort()[0]??"").join("\0"),i=t.map(o=>[...n[o]].sort()[0]??"").join("\0");return r.localeCompare(i)}function Yj(e,t,n){let r=t.reduce((o,s)=>o+s.length,0),i=t.filter(o=>o.length>1).length;return{chain:e,components:t,depth:t.length,fileCount:r,edgeBasis:n,actionTier:"signal",chainKind:"transitive-dependency-depth",evidenceReasons:[`${t.length} condensed dependency component(s) form the representative transitive path`,`${r} file(s) are represented; ${i} component(s) contain a dependency cycle`,`edge basis: ${n==="imports"?"resolved file imports":"cross-file symbol references plus resolved source imports"}`,"cycles count once toward depth and retain their full membership separately"],recommendation:"Review whether the chain crosses ownership or layer boundaries; shorten it only when the dependency direction is accidental."}}function Jj(e){let t=[];for(let n of e)t.some(r=>Xj(n.chain,r.chain))||t.push(n);return t}function Xj(e,t){if(e.length>=t.length)return!1;let n=t.length-e.length;for(let r=0;r<e.length;r++)if(e[r]!==t[n+r])return!1;return!0}function Qj(e,t){let n=ne(e,t);if(!n)return[];let r=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
|
|
318
|
-
WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:T(r.symbol),depth:0}],o=r.enclosing_symbol,s=1,a=new Set([r.symbol]);for(;o&&!a.has(o)&&s<20;){a.add(o);let d=e.get("SELECT symbol, enclosing_symbol FROM global_symbols WHERE symbol = ?",o);if(!d)break;i.push({symbol:d.symbol,shortName:T(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(i.length>1)return i;let c=Bn(r.symbol);if("kind"in c)return i;let l=c.descriptors;if(l.length<=1)return i;let u=[i[0]];for(let d=l.length-2,m=1;d>=0;d--,m++){let f=l.slice(0,d+1).map(g=>g.suffix==="method"?`${g.name}()`:g.name.replace(/\.(ts|tsx|js|jsx|mjs|cjs|py|pyi|rs|java|scala|kt|kts|rb|go|cs|vb|dart|php|c|cc|cpp|cxx|h|hpp)$/,"")).join(":");u.push({symbol:f,shortName:f,depth:m})}return u}function Zj(e,t={}){let r=new H(e).productionCallableDefinitions({scope:t.scope,requireCallableSymbol:!0,includeSuppressed:!0}),i=hx(e,r),o=t.search?.trim().toLocaleLowerCase();return r.map(s=>yx(e,s,i.get(s.symbolId)??[])).filter(s=>s!==null).map(s=>s.result).filter(s=>!o||n1(s).includes(o)).sort(r1)}function e1(e,t,n={}){let r=Qe(e,t);if(!r.match)return{kind:"missing",query:t};if(r.total>1)return{kind:"ambiguous",query:t,total:r.total,candidates:[{symbol:r.match.symbol,shortName:T(r.match.symbol),relativePath:r.match.relativePath,startLine:r.match.startLine},...r.candidates]};let i=new H(e),o=i.definitionsForFile(r.match.relativePath).find(p=>p.symbol===r.match.symbol);if(!o?.isFunctionLike)return{kind:"not-entry",query:t,symbol:r.match.symbol,shortName:T(r.match.symbol),file:r.match.relativePath,reason:"The resolved symbol is not a callable definition."};let s=hx(e,[o]),a=yx(e,o,s.get(o.symbolId)??[]);if(!a)return{kind:"not-entry",query:t,symbol:o.symbol,shortName:T(o.symbol),file:o.relativePath,reason:"The callable is neither an external root nor an uncalled callable on a detected entry surface."};let c=i1(e,i,o),l=new Set(n.expand??[]),u=c1(c,l),d=new Set(u.regions.filter(p=>p.expanded).map(p=>p.id)),m=[...l].filter(p=>!d.has(p)).sort();return{kind:"matched",query:t,entry:a.result,regions:u.regions,regionEdges:u.regionEdges,unmatchedExpansions:m,coverage:{completeWithinIndexedStaticCallEdges:!0,completeWithinSelectedStaticEvidence:!0,candidateReachabilityIncluded:c.edges.some(p=>p.evidenceStrength==="candidate"),dynamicDispatchRepresented:!1,symbolCount:c.symbols.length,symbolEdgeCount:c.edges.length,exactSymbolEdgeCount:c.edges.filter(p=>p.evidenceStrength==="exact").length,candidateSymbolEdgeCount:c.edges.filter(p=>p.evidenceStrength==="candidate").length,regionCount:u.regions.length,regionEdgeCount:u.regionEdges.length,externalCallCount:c.externalCalls.length}}}function hx(e,t){let n=t.filter(r=>bx(e,r.relativePath)||Ii(e,r.symbol,r.relativePath).length>0);return hn(e,n,{semantic:!1,semanticEvidence:re})}function yx(e,t,n){let r=t1(e,t),i=r.length>0,o=bx(e,t.relativePath)&&n.length===0;if(!i&&!o)return null;let s=[...r];return o&&s.push("entry-surface-without-indexed-caller"),{definition:t,result:{symbol:t.symbol,shortName:T(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,documentation:t.documentation,confidence:i?"root":"candidate",evidence:s,indexedCallerCount:n.length}}}function bx(e,t){return Ue(e,t)||/(?:^|\/)entry\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(t)}function t1(e,t){let n=Ii(e,t.symbol,t.relativePath),r=[];return px(n,["package-surface-file","transitive-package-surface"])&&pt(e,t)&&r.push("package-public-export"),n.includes("rust-public-library")&&r.push("rust-public-library"),n.includes("framework-entrypoint")&&r.push("framework-dispatched-export"),px(n,["configured-file","configured-path-prefix","configured-qualified-var","configured-symbol-pattern"])&&r.push("configured-entry-root"),r}function px(e,t){return t.some(n=>e.includes(n))}function n1(e){return[e.symbol,e.shortName,e.file,e.documentation??"",...e.evidence].join(`
|
|
319
|
-
`).toLocaleLowerCase()}function r1(e,t){return fx(e.confidence)-fx(t.confidence)||e.file.localeCompare(t.file)||e.startLine-t.startLine||e.symbol.localeCompare(t.symbol)}function fx(e){return e==="root"?0:1}function i1(e,t,n){let r=new Map([[n.symbol,0]]),i=new Map,o=new Map([[n.symbol,n]]),s=new Map,a=new Map,c=[n];for(;c.length>0;){let l=t.calleeMap(c,{additive:!1,semantic:!1}),u=[];for(let d of c){let m=r.get(d.symbol)??0;i.set(d.symbol,gx(d,m));for(let p of l.get(d.symbolId)??[]){let f=o1(t,p,o);if(!f){let S=a1(d,p);a.set(d1(S),S);continue}let g=m+1,h=r.get(f.symbol);(h===void 0||g<h)&&r.set(f.symbol,g),i.set(f.symbol,gx(f,Math.min(g,h??g)));let b=s1(d,f,p);s.set(u1(b),b),h===void 0&&u.push(f)}}c=u}return{symbols:[...i.values()].sort(m1),edges:[...s.values()].sort(p1),externalCalls:[...a.values()].sort(f1)}}function o1(e,t,n){let r=n.get(t.symbol);if(r)return r;let i=e.definitionsForFile(t.file).find(o=>o.symbol===t.symbol)??null;return i&&n.set(i.symbol,i),i}function gx(e,t){return{symbol:e.symbol,shortName:T(e.symbol),file:e.relativePath,depth:t}}function s1(e,t,n){return{fromSymbol:e.symbol,fromShortName:T(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:T(t.symbol),toFile:t.relativePath,source:n.source,evidenceStrength:n.source==="scip-chunk"?"candidate":"exact"}}function a1(e,t){return{fromSymbol:e.symbol,fromShortName:T(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:T(t.symbol),reportedFile:t.file,source:t.source,evidenceStrength:t.source==="scip-chunk"?"candidate":"exact"}}function c1(e,t){let n=_e(e.symbols,l=>l.file),r=_e(e.edges.filter(l=>l.fromFile===l.toFile),l=>l.fromFile),i=_e(e.externalCalls,l=>l.fromFile),o=l1(e.edges.filter(l=>l.fromFile!==l.toFile)),s=_e(o,l=>l.toRegionId),a=_e(o,l=>l.fromRegionId);return{regions:[...n.entries()].map(([l,u])=>{let d=rm(l),m=t.has(d),p=r.get(l)??[],f=i.get(l)??[];return{id:d,file:l,minDepth:Math.min(...u.map(g=>g.depth)),symbolCount:u.length,internalEdgeCount:p.length,externalCallCount:f.length,incomingRegionIds:rs((s.get(d)??[]).map(g=>g.fromRegionId)),outgoingRegionIds:rs((a.get(d)??[]).map(g=>g.toRegionId)),expanded:m,symbols:m?u:[],internalEdges:m?p:[],externalCalls:m?f:[]}}).sort((l,u)=>l.minDepth-u.minDepth||l.file.localeCompare(u.file)),regionEdges:o}}function l1(e){let t=new Map;for(let n of e){let r=`${n.fromFile}\0${n.toFile}`,i=t.get(r)??[];i.push(n),t.set(r,i)}return[...t.values()].map(n=>{let r=n[0];return{fromRegionId:rm(r.fromFile),fromFile:r.fromFile,toRegionId:rm(r.toFile),toFile:r.toFile,callCount:n.length,exactCallCount:n.filter(i=>i.evidenceStrength==="exact").length,candidateCallCount:n.filter(i=>i.evidenceStrength==="candidate").length,fromSymbols:rs(n.map(i=>i.fromShortName)),toSymbols:rs(n.map(i=>i.toShortName)),evidence:rs(n.map(i=>i.source))}}).sort((n,r)=>n.fromFile.localeCompare(r.fromFile)||n.toFile.localeCompare(r.toFile))}function rm(e){return`file:${e}`}function rs(e){return[...new Set(e)].sort()}function u1(e){return`${e.fromSymbol}\0${e.toSymbol}`}function d1(e){return`${e.fromSymbol}\0${e.toSymbol}`}function m1(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function p1(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function f1(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function kt(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function We(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function ur(e,t){if(e.size===0&&t.size===0)return 0;let n=0;for(let i of e)t.has(i)&&(n+=1);let r=e.size+t.size-n;return r===0?0:n/r}function Sx(e,t){if(e.size===0)return 0;let n=0;for(let r of e)t.has(r)&&(n+=1);return n/e.size}function im(e,t){if(t<=0)return new Map;let n=new Map;for(let[r,i]of e)i>0&&n.set(r,Math.log(t/i));return n}function Bi(e){let t=[...e.values()].sort((r,i)=>r-i);if(t.length===0)return 0;let n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function $i(e,t){let n=0;for(let r of e){let i=t.get(r)??0;n+=i*i}return Math.sqrt(n)}function vx(e,t,n,r={}){let i=0,o=0,s=0,a=r.medianIdf??Bi(n),c=[],l=[];for(let m of e){let p=n.get(m)??0;o+=p*p,t.has(m)&&(i+=p*p,p>=a?c.push(m):l.push(m))}if(c.length===0&&l.length===0)return{similarity:0,significantShared:[],trivialShared:[]};for(let m of t){let p=n.get(m)??0;s+=p*p}let u=Math.sqrt(o)*Math.sqrt(s),d=u>0?i/u:0;return c.sort((m,p)=>(n.get(p)??0)-(n.get(m)??0)),{similarity:d,significantShared:c,trivialShared:l}}function Cx(e,t,n,r){let i=0,o=r.medianIdf??Bi(n),s=[],a=[];for(let u of e){if(!t.has(u))continue;let d=n.get(u)??0;i+=d*d,d>=o?s.push(u):a.push(u)}if(s.length===0&&a.length===0)return{similarity:0,significantShared:[],trivialShared:[]};let c=r.magnitudeA*r.magnitudeB,l=c>0?i/c:0;return s.sort((u,d)=>(n.get(d)??0)-(n.get(u)??0)),{similarity:l,significantShared:s,trivialShared:a}}function is(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=R1(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!Se(o.symbol))return[];if(o.callees.size===0)return xx(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"});let s=h1(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):xx(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"})}function cm(e,t,n,r={}){let i=ne(e,t),o=ne(e,n);if(!i||!o)return null;let s=is(e,i.symbol,{minSimilarity:0,limit:Number.POSITIVE_INFINITY,semantic:r.semantic,scanLimit:r.scanLimit}).find(l=>l.symbolB===o.symbol||l.symbolA===o.symbol);if(!s)return null;let a=i.endLine-i.startLine+1,c=o.endLine-o.startLine+1;return{symbolA:{symbol:i.symbol,shortName:T(i.symbol),file:i.relativePath,loc:a},symbolB:{symbol:o.symbol,shortName:T(o.symbol),file:o.relativePath,loc:c},similarity:s.similarity,similarityBasis:s.similarityBasis??"callees",sharedEvidence:s.sharedCallees,uniqueToA:s.uniqueToA,uniqueToB:s.uniqueToB,evidenceClass:s.evidenceClass,actionTier:s.actionTier,recommendation:s.recommendation,consolidationStrategy:g1(s)}}function g1(e){let t=e.similarityBasis==="source-tokens"?"source-token":"tracked callee";return e.sharedCallees.length===0?`No shared ${t} evidence survived similar's weighting. Inspect the source before attempting consolidation.`:e.uniqueToA.length===0&&e.uniqueToB.length===0?`The functions have identical ${t} evidence under similar's weighting. Verify signatures, guards, and return values before consolidating.`:e.uniqueToA.length===0?`A's ${t} evidence is a subset of B's. B may subsume part of A's structure, but verify signatures, guards, and non-call logic first.`:e.uniqueToB.length===0?`B's ${t} evidence is a subset of A's. A may subsume part of B's structure, but verify signatures, guards, and non-call logic first.`:e.uniqueToA.length<=2&&e.uniqueToB.length<=2?`Create a shared helper around the ${e.sharedCallees.length} shared ${t}(s). Pass the ${e.uniqueToA.length+e.uniqueToB.length} divergent point(s) as parameters or callbacks.`:`Extract the ${e.sharedCallees.length} shared ${t}(s) into a common helper. Keep each function's unique logic outside that helper (${e.uniqueToA.length} item(s) in A, ${e.uniqueToB.length} in B).`}function h1(e,t,n,r){let i=ji(e).calleeIndex({minCallees:3,scanLimit:r.scanLimit,semantic:r.semantic}),o=T1(t,i.corpus),s=P1(o,i),a=y1(o,i),c=Bi(a),l=$i(o.callees,a),u=[];for(let d of s){if(d.callees.size<3)continue;let m=$i(d.callees,a),p=wx(o,d,a,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:c,magnitudeA:l,magnitudeB:m});p&&u.push(p)}return u.sort((d,m)=>m.similarity-d.similarity),u}function y1(e,t){let n=new Map(t.docFreq);for(let r of e.callees)n.set(r,(n.get(r)??0)+1);return im(n,t.corpus.length+1)}function wx(e,t,n,r){let i=S1(e,t,n,r);if(!v1(i,r))return null;let{similarity:o,significantShared:s,trivialShared:a}=i,c=s.length>0?s:a,l=Tx(c,"callees");return{symbolA:e.symbol,shortNameA:T(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:T(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:c.map(T),uniqueToA:[...We(e.callees,t.callees)].map(T),uniqueToB:[...We(t.callees,e.callees)].map(T),...l}}function b1(e,t,n,r){let i=r.magnitudeA??$i(e.callees,n),o=r.magnitudeB??$i(t.callees,n),s=0,a=0,c=0,l=r.medianIdf??Bi(n);for(let m of e.callees){if(!t.callees.has(m))continue;let p=n.get(m)??0;s+=p*p,c+=1,p>=l&&(a+=1)}if(c===0)return!1;let u=i*o;return(u>0?s/u:0)<r.minSimilarity?!1:a>=r.requireSignificantShared||c>=r.requireSharedCount}function S1(e,t,n,r){return r.magnitudeA===void 0||r.magnitudeB===void 0?vx(e.callees,t.callees,n,{medianIdf:r.medianIdf}):Cx(e.callees,t.callees,n,{medianIdf:r.medianIdf,magnitudeA:r.magnitudeA,magnitudeB:r.magnitudeB})}function v1(e,t){if(e.similarity<t.minSimilarity)return!1;let n=e.significantShared.length+e.trivialShared.length;return e.significantShared.length>=t.requireSignificantShared||n>=t.requireSharedCount}function os(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=t.semantic!==!1,l=be(),u=0,d=0,m=0,p=0,f=0,g=0,h=0;return N("similar.all",()=>{let S=ji(e).calleeIndex({minCallees:o,scope:i,scanLimit:a,semantic:c}),y=S.corpus;u=y.length;let x=t.focusFiles,v=[],C=0;return N("similar.all.pair-scan",()=>{for(let R=0;R<y.length;R+=1){let E=y[R],w=x?.has(E.file)??!1,I=S.weightedMagnitudes[R],k=new Set;for(let D of E.callees){let F=S.candidateIndexesByCallee.get(D);if(F)for(let L of F)L<=R||x&&!w&&!x.has(y[L].file)||k.add(L)}l&&(m+=k.size,k.size>0&&(d+=1));for(let D of k){let F=y[D];if(s&&E.file===F.file){l&&(f+=1);continue}if(Lx(E,F)){l&&(g+=1);continue}l&&(p+=1);let L=wx(E,F,S.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:S.medianIdf,magnitudeA:I,magnitudeB:S.weightedMagnitudes[D]});L&&(C1(v,L,r,C),l&&(h+=1),C+=1)}}},()=>({corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:p,crossFileSkips:f,signatureSkips:g,insertedResults:h,topResults:v.length})),N("similar.all.sort-project",()=>(v.sort((R,E)=>E.result.similarity-R.result.similarity||R.order-E.order),v.map(R=>R.result)),()=>({topResults:v.length}))},()=>({minSimilarity:n,limit:r,scope:i,minCallees:o,crossFileOnly:s,scanLimit:a,semantic:c,corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:p,crossFileSkips:f,signatureSkips:g,insertedResults:h}))}function lm(e,t={}){let{minSimilarity:n=.5,scope:r,minCallees:i=4,crossFileOnly:o=!1,scanLimit:s}=t,a=t.semantic!==!1,c=be(),l=0,u=0,d=0,m=0,p=0,f=0,g=0;return N("similar.all-count",()=>{let b=ji(e).calleeIndex({minCallees:i,scope:r,scanLimit:s,semantic:a}),S=b.corpus;l=S.length;let y=t.focusFiles;return N("similar.all-count.pair-scan",()=>{for(let x=0;x<S.length;x+=1){let v=S[x],C=y?.has(v.file)??!1,R=b.weightedMagnitudes[x],E=new Set;for(let w of v.callees){let I=b.candidateIndexesByCallee.get(w);if(I)for(let k of I)k<=x||y&&!C&&!y.has(S[k].file)||E.add(k)}c&&(d+=E.size,E.size>0&&(u+=1));for(let w of E){let I=S[w];if(o&&v.file===I.file){c&&(p+=1);continue}if(Lx(v,I)){c&&(f+=1);continue}c&&(m+=1),b1(v,I,b.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:b.medianIdf,magnitudeA:R,magnitudeB:b.weightedMagnitudes[w]})&&(g+=1)}}},()=>({corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:p,signatureSkips:f,insertedResults:g})),g},()=>({minSimilarity:n,scope:r,minCallees:i,crossFileOnly:o,scanLimit:s,semantic:a,corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:p,signatureSkips:f,insertedResults:g}))}function Lx(e,t){if(e.paramCount<0||t.paramCount<0)return!1;let n=Math.abs(e.paramCount-t.paramCount),r=Math.max(2,Math.ceil(Math.max(e.paramCount,t.paramCount)*.5));return n>r}var Px=dt({kind:"source-fingerprints",invalidation:$e("source-fingerprints"),serialize:X1,deserialize:J1});function C1(e,t,n,r){if(n<=0)return;if(e.length<n){e.push({result:t,order:r});return}let i=0;for(let s=1;s<e.length;s+=1){let a=e[s],c=e[i];(a.result.similarity<c.result.similarity||a.result.similarity===c.result.similarity&&a.order>c.order)&&(i=s)}let o=e[i];t.similarity<=o.result.similarity||(e[i]={result:t,order:r})}var x1=["ScipDatabase#all","ScipDatabase#get","ScipDatabase#prepare","ScipDatabase#pathExclusionsFor","ScipDatabase#isIgnored","ScipDatabase#symbolNoiseFor","PerDbValue#get","PerDbValue#has",":storage:db:ScipDatabase:all",":storage:db:ScipDatabase:get",":storage:db:ScipDatabase:prepare",":storage:db:ScipDatabase:pathExclusionsFor",":storage:db:ScipDatabase:isIgnored",":storage:db:ScipDatabase:symbolNoiseFor",":storage:per-db-cache:PerDbValue:get",":storage:per-db-cache:PerDbValue:has"];function R1(e,t,n){let r=ne(e,t);if(!r||!Se(r.symbol))return null;let i=new H(e),o=Pt(e,r,{semantic:n.semantic,semanticEvidence:re});return{symbol:r.symbol,file:r.relativePath,callees:Lc(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}var E1=ge("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),I1=ge("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function Dx(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=t.semantic!==!1,a=E1.get(e,()=>new Map),c=`${n}|${r??""}|${o??""}|${s}`,l=!0,u=0,d=0;return N("similar.callee-fingerprints.resolve",()=>{let m=a.get(c);if(l=m!==void 0,m||(m=D1(e,{minCallees:n,scope:r,scanLimit:o,semantic:s}),a.set(c,m)),u=m.length,i===void 0)return m;let p=m.filter(f=>f.symbol!==i);return d=m.length-p.length,p},()=>({minCallees:n,scope:r,scanLimit:o,semantic:s,cacheHit:l,corpusSize:u,excludeSymbol:i!==void 0,excludedSymbols:d}))}function w1(e,t){let{minCallees:n,scope:r,scanLimit:i}=t,o=t.semantic!==!1,s=I1.get(e,()=>new Map),a=`${n}|${r??""}|${i??""}|${o}`,c=!0,l=0,u=0,d=0;return N("similar.callee-index.resolve",()=>{let m=s.get(a);return c=m!==void 0,m||(m=L1(Dx(e,{minCallees:n,scope:r,scanLimit:i,semantic:o})),s.set(a,m)),l=m.corpus.length,u=m.docFreq.size,d=m.candidateIndexesByCallee.size,m},()=>({minCallees:n,scope:r,scanLimit:i,semantic:o,cacheHit:c,corpusSize:l,indexedCallees:u,candidateBuckets:d}))}function ji(e){return{calleeCorpus:t=>Dx(e,t),calleeIndex:t=>w1(e,t),sourceCorpus:(t={})=>_x(e,t),sourceIndex:(t={})=>Ix(e,t),sourceCandidates:(t,n)=>(n.candidateMode??"full")==="target-pruned"?U1(e,t,{minSimilarity:n.minSimilarity,scanLimit:n.scanLimit}):H1(t,Ix(e,{scanLimit:n.scanLimit}))}}function L1(e){let t=be(),n=0,r=N("similar.callee-index.doc-frequency",()=>{let m=new Map;for(let p of e)for(let f of p.callees)m.set(f,(m.get(f)??0)+1);return n=m.size,m},()=>({corpusSize:e.length,uniqueCallees:n})),i=Math.max(8,Math.ceil(Math.sqrt(e.length))),o=N("similar.callee-index.idf-weights",()=>im(r,e.length),()=>({corpusSize:e.length,uniqueCallees:r.size})),s=N("similar.callee-index.weighted-magnitudes",()=>e.map(m=>$i(m.callees,o)),()=>({corpusSize:e.length})),a=0,c=0,l=0,u=N("similar.callee-index.candidate-buckets",()=>{let m=new Map;for(let p=0;p<e.length;p+=1){let f=e[p];for(let g of f.callees){if((r.get(g)??0)>i){t&&(c+=1);continue}let h=m.get(g);h||(h=[],m.set(g,h)),h.push(p),t&&(a+=1)}}return t&&(l=m.size),m},()=>({corpusSize:e.length,buckets:l,candidateRefs:a,ubiquitousSkips:c,ubiquityThreshold:i})),d=N("similar.callee-index.median-idf",()=>Bi(o),()=>({uniqueCallees:o.size}));return{corpus:e,candidateIndexesByCallee:u,docFreq:r,idfWeights:o,weightedMagnitudes:s,medianIdf:d,ubiquityThreshold:i}}function P1(e,t){let n=new Map;for(let r of e.callees)for(let i of t.candidateIndexesByCallee.get(r)??[]){let o=t.corpus[i];o.symbol!==e.symbol&&n.set(o.symbol,o)}return n.size>0?[...n.values()]:t.corpus.filter(r=>r.symbol!==e.symbol)}function D1(e,t){let{minCallees:n,scope:r,scanLimit:i,semantic:o}=t,s=be(),a=new H(e),c=0,l=N("similar.callee-fingerprints.candidates",()=>{let g=he(a.productionCallableDefinitions({scope:r,minLoc:5,sortByLocDesc:typeof i=="number"&&i>0}),i);return c=g.length,g},()=>({scope:r,scanLimit:i,candidateCount:c})),u=0,d=N("similar.callee-fingerprints.callee-map",()=>{let g=a.calleeMap(l,{semantic:o});if(s)for(let h of g.values())u+=h.length;return g},()=>({candidateCount:c,semantic:o,calleeEdges:u})),m=0,p=0,f=0;return N("similar.callee-fingerprints.shape",()=>{let g=l.map(S=>({symbol:S.symbol,file:S.relativePath,callees:Lc((d.get(S.symbolId)??[]).map(y=>y.symbol)),paramCount:a.callableSignature(S)?.paramCount??-1})),h=M1(g);s&&(f=h.filter((S,y)=>S.callees.size!==g[y].callees.size).length);let b=h.filter(S=>S.callees.size>=n);return m=b.length,s&&(p=b.reduce((S,y)=>S+y.callees.size,0)),b},()=>({candidateCount:c,fingerprintCount:m,retainedCalleeCount:p,minCallees:n,siblingSaturatedFingerprints:f}))}var Mx=5;function M1(e){let t=new Map;for(let n of e){let r=t.get(n.file);r||(r=new Map,t.set(n.file,r));for(let i of n.callees)r.set(i,(r.get(i)??0)+1)}return e.map(n=>{let r=t.get(n.file);if(!r)return n;let i=[...n.callees].filter(s=>(r.get(s)??0)>=Mx);if(i.length===0)return n;let o=new Set(n.callees);for(let s of i)o.delete(s);return{...n,callees:o}})}function T1(e,t){let n=new Map;for(let o of t)if(!(o.file!==e.file||o.symbol===e.symbol))for(let s of o.callees)n.set(s,(n.get(s)??0)+1);let r=[...e.callees].filter(o=>(n.get(o)??0)+1>=Mx);if(r.length===0)return e;let i=new Set(e.callees);for(let o of r)i.delete(o);return{...e,callees:i}}function Lc(e){return new Set([...e].filter(t=>!k1(t)))}function k1(e){return x1.some(t=>e.includes(t))}function xx(e,t,n){let r=_1(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=n.candidateMode??"full",a=0,c=0,l=0,u=0;return N("similar.source-shape",()=>{let m=ji(e).sourceCandidates(r,{minSimilarity:i,scanLimit:n.scanLimit,candidateMode:s});a=m.length;for(let p of m){if(p.symbol===r.symbol||p.tokens.size<3)continue;c+=1;let f=kt(r.tokens,p.tokens);if(f.size<2){l+=1;continue}let g=new Set([...r.tokens,...p.tokens]),h=g.size>0?f.size/g.size:0;if(h<i){u+=1;continue}o.push({symbolA:r.symbol,shortNameA:T(r.symbol),fileA:r.file,symbolB:p.symbol,shortNameB:T(p.symbol),fileB:p.file,similarity:h,similarityBasis:"source-tokens",sharedCallees:[...f].sort(),uniqueToA:[...We(r.tokens,p.tokens)].sort(),uniqueToB:[...We(p.tokens,r.tokens)].sort(),...Tx([...f],"source-tokens")})}return o.sort((p,f)=>f.similarity-p.similarity||p.shortNameB.localeCompare(f.shortNameB)),o.slice(0,n.limit)},()=>({symbol:r.symbol,file:r.file,targetTokens:r.tokens.size,candidateMode:s,candidates:a,comparedPairs:c,sharedSkips:l,similaritySkips:u,results:o.length}))}function Tx(e,t){let n=e.flatMap(sm),r=e.flatMap(h=>Rx(h,t)),i=om(n,kx),o=om(n,Ax),s=om(r,am),a=[...new Set(r.filter(Ex))],c=e.filter(h=>{let b=Rx(h,t);return b.some(S=>am.has(S))&&b.some(Ex)}).length,l=[];i.length>0&&l.push(`access/query scaffolding: ${i.slice(0,5).join(", ")}`),o.length>0&&l.push(`framework/generic scaffolding: ${o.slice(0,5).join(", ")}`),s.length>0&&l.push(`domain behavior verbs: ${s.slice(0,5).join(", ")}`),s.length>0&&a.length>0&&l.push(`domain-specific terms: ${a.slice(0,5).join(", ")}`);let u=t==="source-tokens"&&n.length>0&&n.every(h=>Fx.has(h));u&&l.push("shared source tokens are generic scaffolding");let d=s.length>0&&a.length>0,m=i.length+o.length>0,p=t==="callees"&&d&&e.length>=4&&a.length>=4&&c>=2,f=p?"domain-behavior":d?m?"mixed":"domain-behavior":i.length>0?"access-query-scaffolding":o.length>0||u?"framework-scaffolding":"structural-overlap";f==="structural-overlap"&&e.length>0&&l.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let g=f==="domain-behavior"&&(e.length>=3||p)?"direct":"signal";return{evidenceClass:f,actionTier:g,evidenceClassReasons:l,recommendation:A1(f,g)}}function A1(e,t){return t==="direct"?"Shared domain behavior looks concrete; review for an extract/reuse opportunity.":e==="mixed"?"Shared evidence mixes domain behavior with scaffolding; review semantics before extracting anything.":e==="access-query-scaffolding"?"Shared evidence is mostly access/query scaffolding; compare product semantics before reusing code.":e==="structural-overlap"?"Shared structure has no domain or scaffolding classification; inspect names and behavior before reusing code.":"Shared evidence is mostly framework or generic scaffolding; treat as a contextual signal."}function om(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function sm(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function Rx(e,t){if(t==="source-tokens")return sm(e);let n=z(e);return sm(n.length>0?n:F1(e))}function F1(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(r=>r.trim()).filter(r=>/[A-Za-z]/.test(r)).at(-1)?.replace(/\.$/,"")??e}function Ex(e){return e.length>3&&!am.has(e)&&!kx.has(e)&&!Ax.has(e)&&!Fx.has(e)&&!N1.has(e)}var am=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),kx=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),Ax=new Set(["bytes","computed","crypto","describe","effect","expect","fetch","filter","hex","hook","json","map","mounted","on","promise","random","react","reduce","ref","render","state","test","token","trim","uuid","vue","watch"]),Fx=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),N1=new Set(["best","backend","conflict","database","effect","effects","error","errors","frontend","found","helpers","javascript","module","modules","scip","shared","source","typescript","utils","with","workflow","workflows"]);function _1(e,t){let n=ne(e,t);if(!n||!Se(n.symbol))return null;let r=O1(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function O1(e,t){let n=z(t.symbol),r=W1(e,t.relativePath,t.startLine,t.endLine,n),i=$x(r,n);return i.size>0?i:null}var B1=ge("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),$1=ge("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function Nx(e){return`${e.scanLimit??""}`}function _x(e,t={}){let n=B1.get(e,()=>new Map),r=Nx(t),i=n.get(r);return i||(i=K1(e,t),n.set(r,i)),i}function Ix(e,t={}){let n=$1.get(e,()=>new Map),r=Nx(t),i=n.get(r);return i||(i=j1(_x(e,t)),n.set(r,i)),i}function j1(e){let t=new Map;for(let i of e)for(let o of i.tokens)t.set(o,(t.get(o)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),r=new Map;for(let i of e)for(let o of i.tokens){if((t.get(o)??0)>n)continue;let s=r.get(o);s||(s=[],r.set(o,s)),s.push(i)}return{corpus:e,candidateByToken:r,docFreq:t,ubiquityThreshold:n}}function H1(e,t){let n=new Map;for(let r of e.tokens)for(let i of t.candidateByToken.get(r)??[])i.symbol!==e.symbol&&n.set(i.symbol,i);return n.size>0?[...n.values()]:t.corpus.filter(r=>r.symbol!==e.symbol)}function U1(e,t,n){let r=be(),i=new H(e),o=q1(t.tokens.size,n.minSimilarity),s=0,a=0,c=0,l=N("similar.source-shape.target-files",()=>{let f=[...t.tokens],g=[];for(let h of Z(e,{includeIgnored:!1})){s+=1;let b=W(e,h);b&&(a+=1,G1(b,f,o)&&g.push(h))}return c=g.length,g},()=>({symbol:t.symbol,targetTokens:t.tokens.size,requiredSharedTokens:o,scannedFiles:s,readableFiles:a,candidateFiles:c})),u=0,d=N("similar.source-shape.target-definitions",()=>{let f=he(i.productionCallableDefinitions({files:l,sortByLocDesc:typeof n.scanLimit=="number"&&n.scanLimit>0}),n.scanLimit);return u=f.length,f},()=>({symbol:t.symbol,candidateFiles:c,scanLimit:n.scanLimit,definitionCount:u})),m=0;return N("similar.source-shape.target-fingerprints",()=>{let f=Ox(e,d);return r&&(m=f.length),f},()=>({symbol:t.symbol,definitionCount:u,fingerprintCount:m})).filter(f=>f.symbol!==t.symbol)}function q1(e,t){return Math.max(2,Math.ceil(e*t))}function G1(e,t,n){if(t.length<n)return!1;let r=e.toLowerCase(),i=0;for(let o of t)if(z1(r,o)&&(i+=1,i>=n))return!0;return!1}function z1(e,t){return t==="num"?/\b\d+\b/.test(e):e.includes(t)}function K1(e,t={}){let n=new H(e),{scanLimit:r}=t,i=he(n.productionCallableDefinitions({sortByLocDesc:typeof r=="number"&&r>0}),r);return Ox(e,i)}function Ox(e,t){let n=new Map;for(let i of t){let o=n.get(i.relativePath)??[];o.push(i),n.set(i.relativePath,o)}let r=new Map;for(let[i,o]of n){let s=W(e,i);if(!s)continue;let a=Rt(e,i,s),c=Y1(e,i,a),l=!1,u=null;for(let d of o){let m=V1(d),p=c.get(m),f=p?new Set(p.tokens):null;f||(u??=V(e,i),f=$x(Bx(u,d.startLine,d.endLine,d.leaf),d.leaf),c.set(m,{key:m,symbol:d.symbol,startLine:d.startLine,endLine:d.endLine,leaf:d.leaf,tokens:[...f].sort()}),l=!0),f.size>0&&r.set(d.symbol,{symbol:d.symbol,file:d.relativePath,tokens:f})}l&&Q1(e,i,a,c)}return t.map(i=>r.get(i.symbol)).filter(i=>!!i)}function W1(e,t,n,r,i){let o=V(e,t);return o.length===0?"":Bx(o,n,r,i)}function Bx(e,t,n,r){if(n>=t&&n-t<=12)return e.slice(t,n+1).join(`
|
|
320
|
-
`);let i=[new RegExp(`\\bdef\\s+${Ce(r)}\\b`),new RegExp(`\\bfun\\s+${Ce(r)}\\b`),new RegExp(`\\bfn\\s+${Ce(r)}\\b`),new RegExp(`\\bfunction\\s+${Ce(r)}\\b`),new RegExp(`\\b${Ce(r)}\\s*\\(`)],o=e.findIndex(s=>i.some(a=>a.test(s)));if(o>=0){let s=o;for(let a=o+1;a<e.length&&a<=o+8;a++){let c=e[a]??"";if(a>o&&eH(c)||(s=a,c.trim()===""&&a>o+1))break}return e.slice(o,s+1).join(`
|
|
321
|
-
`)}return e.slice(t,Math.min(e.length,t+8)).join(`
|
|
322
|
-
`)}function V1(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function Y1(e,t,n){return Px.read(e,t,n)??new Map}function J1(e){try{let t=JSON.parse(e);if(!Array.isArray(t.entries))return null;let n=new Map;for(let r of t.entries){if(!r||typeof r.key!="string"||typeof r.symbol!="string"||typeof r.startLine!="number"||typeof r.endLine!="number"||typeof r.leaf!="string"||!Array.isArray(r.tokens)||!r.tokens.every(i=>typeof i=="string"))return null;n.set(r.key,r)}return n}catch{return null}}function X1(e){let t={entries:[...e.values()].sort((n,r)=>n.key.localeCompare(r.key))};return JSON.stringify(t)}function Q1(e,t,n,r){Px.write(e,t,n,new Map(r))}function $x(e,t){if(!e)return new Set;let n=new Set(["public","private","protected","final","static","class","def","fun","fn","function","return","string","bool","boolean","void","unit","self","this","new","const","let","var","end","pub"]),r=Z1(t),o=e.replace(/["'`]/g," ").replace(/\b\d+\b/g," NUM ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^A-Za-z0-9_]+/g," ").replace(/_/g," ").toLowerCase().split(/\s+/).map(s=>s.trim()).filter(s=>s.length>1).filter(s=>!n.has(s)).filter(s=>!r.has(s));return new Set(o)}function Z1(e){return new Set(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9_]+|_/).map(t=>t.toLowerCase()).filter(t=>t.length>1))}function eH(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function rn(e,t){let n=new Map;return e.forEach((r,i)=>{let o=new Set;for(let s of t(r)){if(o.has(s))continue;o.add(s);let a=n.get(s);a?a.push(i):n.set(s,[i])}}),{candidatesFor:(r,i)=>{let o=new Set;for(let s of t(r)){let a=n.get(s);if(a)for(let c of a)c!==i&&o.add(c)}return[...o].sort((s,a)=>s-a)}}}function on(e){let t=jx(e.profile?.name),n=()=>{let r=[];t=jx(e.profile?.name,e);let i=(s,a)=>{let c=e.profiles[s],l=e.profiles[a];t.candidatePairs+=1,t.comparedPairs+=1;let u=e.compare(c,l);u&&r.push(u)};if(e.filePattern){let s=e.profiles.findIndex(a=>a.file.includes(e.filePattern));if(s>=0){let a=e.profiles[s];for(let c of tH(e,s)){let l=e.profiles[c];e.focusFiles&&!e.focusFiles.has(a.file)&&!e.focusFiles.has(l.file)||i(s,c)}}}else if(e.focusFiles?.size!==0){let s=typeof e.overrunFactor=="number"&&Number.isFinite(e.limit)?e.limit*e.overrunFactor:Number.POSITIVE_INFINITY;for(let a=0;a<e.profiles.length;a+=1){let c=e.profiles[a],l=e.focusFiles?.has(c.file)??!1;for(let u of nH(e,a))e.focusFiles&&!l&&!e.focusFiles.has(e.profiles[u].file)||i(a,u);if(r.length>s){t.overrunApplied=!0;break}}}r.sort(e.sort??((s,a)=>a.similarity-s.similarity)),t.matchedResults=r.length;let o=r.slice(0,e.limit);return t.emittedResults=o.length,e.onProfile?.({...t}),o};return e.profile?N(`pairwise-profile:${e.profile.name}`,n,()=>({...rH(e.profile?.metadata),...t})):n()}function tH(e,t){if(e.candidateIndex)return Hx(e,t,-1);let n=[];for(let r=0;r<e.profiles.length;r+=1)r!==t&&n.push(r);return n}function nH(e,t){if(e.candidateIndex)return Hx(e,t,t);let n=[];for(let r=t+1;r<e.profiles.length;r+=1)n.push(r);return n}function Hx(e,t,n){let r=e.profiles[t],i=new Set;for(let o of e.candidateIndex?.candidatesFor(r,t,e.profiles)??[])o<=n||o!==t&&(o<0||o>=e.profiles.length||i.add(o));return[...i].sort((o,s)=>o-s)}function jx(e,t){return{pipeline:e,profileCount:t?.profiles.length??0,focusedProfileCount:t?.focusFiles?t.profiles.filter(n=>t.focusFiles.has(n.file)).length:0,candidatePairs:0,comparedPairs:0,matchedResults:0,emittedResults:0,candidateIndexApplied:t?.candidateIndex!==void 0,focusApplied:t?.focusFiles!==void 0,filePatternApplied:t?.filePattern!==void 0,overrunApplied:!1}}function rH(e){return typeof e=="function"?e():e??{}}function iH(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=oH(e,{scope:i,minDeps:s}),l=rn(a,u=>u.deps);return on({profiles:a,limit:r,filePattern:o,overrunFactor:5,candidateIndex:l,profile:{name:"similar-files"},compare:(u,d)=>aH(u,d,n,c)})}function oH(e,t){let{scope:n,minDeps:r}=t,i=Me(e,n),{universalDeps:o,distinctiveDeps:s}=sH(i),a=[];for(let[c,l]of i)l.size>=r&&a.push({file:c,deps:new Set([...l].filter(u=>!o.has(u)))});return{profiles:a,distinctiveDeps:s}}function sH(e){let t=new Set,n=new Set,r=e.size;if(r===0)return{universalDeps:t,distinctiveDeps:n};let i=new Map;for(let s of e.values())for(let a of s)i.set(a,(i.get(a)??0)+1);let o=Math.max(3,Math.ceil(r*.03));for(let[s,a]of i)a>=5&&a/r>.3?t.add(s):a<=o&&n.add(s);return{universalDeps:t,distinctiveDeps:n}}function aH(e,t,n,r){let i=new Set;for(let l of e.deps)t.deps.has(l)&&i.add(l);if(i.size<3||e.deps.size<4||t.deps.size<4)return null;let o=0;for(let l of i)r.has(l)&&o++;if(o<2)return null;let s=ur(e.deps,t.deps);if(s<n)return null;let a=[];for(let l of e.deps)t.deps.has(l)||a.push(l);let c=[];for(let l of t.deps)e.deps.has(l)||c.push(l);return{fileA:e.file,fileB:t.file,similarity:s,sharedDeps:[...i],uniqueToA:a,uniqueToB:c}}function dr(e){let t=[],n=[],r=[];for(let l of e.primitiveGroups)l.values.length!==0&&Ux(l.bucket,n,r).push(`${l.reasonPrefix}: ${l.values.join(", ")}`);for(let l of e.nameGroups)cH(l.names,l.label,e.genericWords,e.stripPrefixes??[],t,Ux(l.fallbackBucket,n,r));let i=t.length>0,o=n.length>0,s=r.length>0,a=i?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...r,...n].slice(0,6),recommendation:e.recommendation(a)}}function Pc(e,t){if(e.size===0||t.size===0)return 0;let i=kt(e,t).size/Math.min(e.size,t.size)*Math.min(1,Math.min(e.size,t.size)/(.35*Math.max(e.size,t.size)));return Math.max(ur(e,t),i)}function mr(e,t){let n=Object.fromEntries(e.map(r=>[r.name,r.count]));for(let r of t)if(Object.entries(r.min).every(([o,s])=>(n[o]??0)>=s))return{pass:!0,reason:r.reason,counts:n};return{pass:!1,reason:"shared tokens did not meet calibrated overlap thresholds",counts:n}}function Dc(e,t,n){let r=t.map(c=>{let l=c.value(e),u=c.weightedValue?c.weightedValue(e,l):l;return{axis:c,value:l,weighted:u,qualifies:c.qualifies?c.qualifies(e,l):l>0}}),i=r.filter(c=>c.qualifies&&c.axis.reason).map(c=>c.axis.reason(e,c.value)),o=r.filter(c=>c.qualifies&&c.axis.dominantEligible!==!1).sort((c,l)=>l.weighted-c.weighted)[0],s=o&&o.weighted>0?o.axis.axis:n,a=[...new Set(r.filter(c=>c.qualifies).map(c=>c.axis.axis).concat(i.length>0?[]:[s]))];return{dominantPressure:s,pressureKinds:a,reasons:i}}function de(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function et(e){return[...e].sort()}function cH(e,t,n,r,i,o){let s=[],a=[];for(let c of e)lH(c,r).filter(u=>!n.has(u)).length>0?s.push(c):a.push(c);s.length&&i.push(`${t} has domain term(s): ${s.slice(0,6).join(", ")}`),a.length&&o.push(`${t} is generic workflow: ${a.slice(0,6).join(", ")}`)}function lH(e,t){let n=e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2");for(let r of t)n=n.replace(r,"");return n.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function Ux(e,t,n){return e==="generic"?t:n}function ss(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=It(e).reactProfiles({scope:o,minJsxTokens:r,scanLimit:s}).filter(d=>d.kind==="component").map(d=>({file:d.file,component:d.name,tokens:d.jsxTokens,profile:d})),u=rn(l,d=>d.tokens);return on({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-component-duplicates"},compare:(d,m)=>uH(d,m,n),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.componentA.localeCompare(m.componentA)||d.fileB.localeCompare(m.fileB)||d.componentB.localeCompare(m.componentB)})}function uH(e,t,n){let r=kt(e.tokens,t.tokens);if(r.size<6||!dH(r))return null;let i=ur(e.tokens,t.tokens);if(i<n)return null;let o=de(r,"component:"),s=de(r,"native:"),a=de(r,"prop:"),c=de(r,"event:"),l=de(r,"binding:"),u=mH({sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:i,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:et(r),sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l,evidenceClass:u.evidenceClass,actionTier:u.actionTier,evidenceClassReasons:u.reasons,recommendation:u.recommendation,uniqueToA:et(We(e.tokens,t.tokens)).slice(0,25),uniqueToB:et(We(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function dH(e){let t=0,n=0;for(let r of e)r.startsWith("component:")&&(t+=1),(r.startsWith("prop:")||r.startsWith("event:")||r.startsWith("native:")||r.startsWith("jsx:"))&&(n+=1);return mr([{name:"component",count:t},{name:"shape",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{shape:4},reason:"shared JSX structure"}]).pass}function mH(e){return dr({genericWords:fH,primitiveGroups:[{values:e.sharedNativeTags,reasonPrefix:"shared native tags",bucket:"generic"},{values:e.sharedProps,reasonPrefix:"shared props",bucket:"generic"},{values:e.sharedEvents,reasonPrefix:"shared events",bucket:"generic"}],nameGroups:[{names:e.sharedComponents,label:"shared component",fallbackBucket:"generic"},{names:e.sharedBindings,label:"shared binding",fallbackBucket:"generic"}],recommendation:pH})}function pH(e){switch(e){case"domain-behavior":case"mixed":return"Review for a shared component or feature-specific UI primitive around the named domain structure.";case"shared-abstraction":return"Review the existing shared component usage first; extract only if duplicated structure remains outside it.";case"generic-workflow-scaffolding":return"Generic structural overlap \u2014 verify intent before consolidating."}}var fH=new Set(["actions","app","button","card","children","content","container","dialog","field","form","header","input","item","label","layout","list","modal","page","panel","row","section","shell","table","text","toolbar","ui","value","view","wrapper"]);function as(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=It(e).reactProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,component:d.name,tokens:d.behaviorTokens,profile:d})),u=rn(l,d=>d.tokens);return on({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-hook-candidates"},compare:(d,m)=>gH(d,m,n,r),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.componentA.localeCompare(m.componentA)||d.fileB.localeCompare(m.fileB)||d.componentB.localeCompare(m.componentB)})}function gH(e,t,n,r){let i=kt(e.tokens,t.tokens);if(i.size<r||!bH(i))return null;let o=Pc(e.tokens,t.tokens);if(o<n)return null;let s=de(i,"hook:"),a=de(i,"react-hook:"),c=de(i,"effect:"),l=de(i,"state:"),u=de(i,"request:"),d=de(i,"handler:"),m=de(i,"handler-verb:"),p=hH({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:et(i),sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m,evidenceClass:p.evidenceClass,actionTier:p.actionTier,evidenceClassReasons:p.reasons,recommendation:p.recommendation,uniqueToA:et(We(e.tokens,t.tokens)).slice(0,25),uniqueToB:et(We(t.tokens,e.tokens)).slice(0,25),reason:SH({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function hH(e){return dr({genericWords:vH,stripPrefixes:CH,primitiveGroups:[{values:e.sharedReactHooks,reasonPrefix:"shared React primitives",bucket:"generic"},{values:e.sharedEffects,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedHooks,label:"shared hook",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedState,label:"shared state",fallbackBucket:"generic"},{names:e.sharedHandlers,label:"shared handler",fallbackBucket:"generic"},{names:e.sharedHandlerVerbs,label:"shared action verb",fallbackBucket:"generic"}],recommendation:yH})}function yH(e){switch(e){case"domain-behavior":return"Review for a shared hook, controller, or feature module around the named domain behavior.";case"mixed":return"Separate generic React mechanics from domain-specific behavior before extracting a shared hook.";case"shared-abstraction":return"Review the existing shared hook usage first; extract only if duplicated behavior remains outside it.";case"generic-workflow-scaffolding":return"Treat as support evidence for a repeated workflow shape, not direct hook-extraction evidence."}}function bH(e){let t=0,n=0,r=0,i=0,o=0,s=0,a=0;for(let u of e)u.startsWith("hook:")?t+=1:u.startsWith("react-hook:")?n+=1:u.startsWith("effect:")?r+=1:u.startsWith("request:")?i+=1:u.startsWith("handler:")||u.startsWith("handler-verb:")?o+=1:u.startsWith("state:")?s+=1:u.startsWith("state-hook:")&&(a+=1);let c=s+a,l=t+n+r+i+o+c;return mr([{name:"requests",count:i},{name:"customHooks",count:t},{name:"namedStates",count:s},{name:"handlers",count:o},{name:"effects",count:r},{name:"reactHooks",count:n},{name:"namedBehavior",count:l}],[{min:{requests:1,namedBehavior:4},reason:"shared request workflow"},{min:{customHooks:1,requests:1,namedBehavior:5},reason:"shared custom hook and request workflow"},{min:{customHooks:1,namedStates:1,namedBehavior:5},reason:"shared custom hook and state"},{min:{customHooks:1,handlers:2,namedBehavior:5},reason:"shared custom hook and handlers"},{min:{namedStates:1,handlers:2,effects:1,namedBehavior:5},reason:"shared stateful effects"},{min:{namedStates:1,handlers:2,reactHooks:2,namedBehavior:5},reason:"shared stateful React primitives"}]).pass}function SH(e){let t=[];return e.sharedHooks.length&&t.push(`shared hooks: ${e.sharedHooks.join(", ")}`),e.sharedReactHooks.length&&t.push(`shared React hooks: ${e.sharedReactHooks.join(", ")}`),e.sharedEffects.length&&t.push(`shared effects: ${e.sharedEffects.join(", ")}`),e.sharedState.length&&t.push(`shared state: ${e.sharedState.join(", ")}`),e.sharedRequests.length&&t.push(`shared requests: ${e.sharedRequests.join(", ")}`),e.sharedHandlers.length&&t.push(`shared handlers: ${e.sharedHandlers.slice(0,6).join(", ")}`),e.sharedHandlerVerbs.length&&t.push(`shared action verbs: ${e.sharedHandlerVerbs.slice(0,6).join(", ")}`),t.join("; ")||"shared React behavior profile"}var vH=new Set(["add","apply","async","callback","cancel","change","clear","close","create","data","delete","draft","edit","effect","error","fetch","filter","form","handle","has","is","item","items","load","loader","loading","memo","name","open","reducer","refresh","ref","remove","request","reset","resource","row","rows","save","saving","search","select","selected","state","store","submit","toggle","update","use","value"]),CH=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function um(e,t={}){let{minComponentLines:n=300,minFileLines:r=800,minJsxTokens:i=80,minBehaviorTokens:o=40,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return It(e).reactProfiles({scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>xH(d,{minComponentLines:n,minFileLines:r,minJsxTokens:i,minBehaviorTokens:o})).filter(d=>d!==null).sort((d,m)=>m.componentLines-d.componentLines||m.fileLines-d.fileLines||d.file.localeCompare(m.file)).slice(0,s)}function xH(e,t){let n=Math.max(80,Math.floor(t.minComponentLines/2)),r=Dc(e,RH({minComponentLines:t.minComponentLines,minFileLines:t.minFileLines,minJsxTokens:t.minJsxTokens,minBehaviorTokens:t.minBehaviorTokens,substantialComponentLines:n}),"component"),{reasons:i}=r;if(i.length===0)return null;let o=r.dominantPressure,s=r.pressureKinds,a=EH(e),c=IH(o,s,a);return{file:e.file,component:e.name,componentLines:e.loc,fileLines:e.fileLines,jsxTokens:e.jsxTokens.size,behaviorTokens:e.behaviorTokens.size,dominantPressure:o,pressureKinds:s,contextKind:a,recommendationKind:c,recommendation:wH(c,a),reasons:i,loc:e.loc}}function RH(e){return[{axis:"component",value:t=>t.loc,qualifies:(t,n)=>n>=e.minComponentLines,reason:(t,n)=>`${n} component line(s)`},{axis:"file",value:t=>t.fileLines,qualifies:(t,n)=>n>=e.minFileLines&&t.loc>=e.substantialComponentLines,reason:(t,n)=>`${n} file line(s)`},{axis:"jsx-structure",value:t=>t.jsxTokens.size,weightedValue:(t,n)=>n*3,qualifies:(t,n)=>n>=e.minJsxTokens,reason:(t,n)=>`${n} JSX structure token(s)`},{axis:"hook-behavior",value:t=>t.behaviorTokens.size,weightedValue:(t,n)=>n*4,qualifies:(t,n)=>n>=e.minBehaviorTokens,reason:(t,n)=>`${n} behavior token(s)`}]}function EH(e){let t=e.file.split(/[\\/]+/).filter(Boolean),n=t.slice(0,-1).map(m=>m.toLowerCase()),r=(t.at(-1)??e.name).replace(/\.[^.]+$/,""),o=n.findIndex(m=>PH.has(m))>=0,s=n.some(m=>LH.has(m));if(qx(r)||qx(e.name))return"component";let c=DH.has(r.toLowerCase()),l=/(?:Page|Route|Screen)$/.test(e.name),u=o&&/View$/.test(e.name),d=!s&&r.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()===e.name.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()&&/(?:Page|Route|Screen|View)$/.test(r);return c||l||u||d?"route-page":"component"}function qx(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&Gx.has(t.at(-1))?!0:[...Gx].some(n=>e.endsWith(MH(n)))}function IH(e,t,n){return e==="hook-behavior"?"behavior-extraction":n==="route-page"?"route-page-decomposition":t.includes("hook-behavior")?"behavior-extraction":t.includes("jsx-structure")?"jsx-decomposition":t.includes("file")?"file-decomposition":e==="jsx-structure"?"jsx-decomposition":e==="file"&&!t.includes("component")?"file-decomposition":"component-decomposition"}function wH(e,t){switch(e){case"behavior-extraction":return"Extract independent state, effects, requests, or handlers into hooks, controllers, or feature modules.";case"route-page-decomposition":return"Split route/page orchestration from reusable panels and feature controllers.";case"jsx-decomposition":return t==="route-page"?"Split page JSX into named layout sections before extracting behavior.":"Split repeated JSX sections into named presentational components.";case"file-decomposition":return"Review file-level decomposition; split colocated panels or helpers before changing behavior.";case"component-decomposition":return"Review component boundaries around props, state ownership, and independently changing UI sections."}}var LH=new Set(["component","components","panel","panels","partial","partials"]),Gx=new Set(["banner","button","card","dialog","drawer","filter","form","grid","header","item","list","menu","modal","nav","panel","picker","rail","row","section","selector","shell","sidebar","table","toolbar"]),PH=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),DH=new Set(["page","route","screen"]);function MH(e){return e.charAt(0).toUpperCase()+e.slice(1)}function cs(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=TH(e,{scope:o,minTokens:r,scanLimit:s}),u=rn(l,d=>d.tokens);return on({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-component-duplicates"},compare:(d,m)=>AH(d,m,n),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function TH(e,t){return It(e).vueProfiles({scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:kH(n)}))}function kH(e){return e.totalLines}function AH(e,t,n){let r=kt(e.tokens,t.tokens);if(r.size<6||!FH(r))return null;let i=ur(e.tokens,t.tokens);if(i<n)return null;let o=de(r,"component:"),s=de(r,"prop:"),a=de(r,"event:"),c=de(r,"directive:"),l=de(r,"slot:"),u=de(r,"id:"),d=NH({sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:c,sharedSlots:l,sharedIdentifiers:u});return{fileA:e.file,fileB:t.file,similarity:i,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:et(r),sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:c,sharedSlots:l,sharedIdentifiers:u,evidenceClass:d.evidenceClass,actionTier:d.actionTier,evidenceClassReasons:d.reasons,recommendation:d.recommendation,uniqueToA:et(We(e.tokens,t.tokens)).slice(0,25),uniqueToB:et(We(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function FH(e){let t=0,n=0;for(let r of e)r.startsWith("component:")&&(t+=1),(r.startsWith("prop:")||r.startsWith("event:")||r.startsWith("directive:")||r.startsWith("slot:"))&&(n+=1);return mr([{name:"component",count:t},{name:"behavior",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{behavior:3},reason:"shared Vue template structure"}]).pass}function NH(e){return dr({genericWords:OH,primitiveGroups:[{values:e.sharedProps,reasonPrefix:"shared props",bucket:"generic"},{values:e.sharedEvents,reasonPrefix:"shared events",bucket:"generic"},{values:e.sharedDirectives,reasonPrefix:"shared directives",bucket:"generic"},{values:e.sharedSlots,reasonPrefix:"shared slots",bucket:"generic"}],nameGroups:[{names:e.sharedComponents,label:"shared component",fallbackBucket:"generic"},{names:e.sharedIdentifiers,label:"shared identifier",fallbackBucket:"generic"}],recommendation:_H})}function _H(e){switch(e){case"domain-behavior":case"mixed":return"Review for a shared component or feature-specific Vue primitive around the named domain structure.";case"shared-abstraction":return"Review the existing shared component usage first; extract only if duplicated structure remains outside it.";case"generic-workflow-scaffolding":return"Generic structural overlap \u2014 verify intent before consolidating."}}var OH=new Set(["actions","app","button","card","content","container","dialog","field","form","header","input","item","label","layout","list","modal","page","panel","row","section","shell","table","text","toolbar","ui","value","view","wrapper"]);function ls(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=It(e).vueProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,tokens:d.behaviorTokens,profile:d})),u=rn(l,d=>d.tokens);return on({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-composable-candidates"},compare:(d,m)=>BH(d,m,n,r),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function BH(e,t,n,r){let i=kt(e.tokens,t.tokens);if(i.size<r||!HH(i))return null;let o=Pc(e.tokens,t.tokens);if(o<n)return null;let s=de(i,"composable:"),a=de(i,"store:"),c=de(i,"reactivity:"),l=de(i,"lifecycle:"),u=de(i,"request:"),d=de(i,"function:"),m=de(i,"function-verb:"),p=de(i,"template-binding:"),f=de(i,"template-event:"),g=$H({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:f});return{fileA:e.file,fileB:t.file,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:et(i),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:f,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:et(We(e.tokens,t.tokens)).slice(0,25),uniqueToB:et(We(t.tokens,e.tokens)).slice(0,25),reason:UH({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function $H(e){return dr({genericWords:qH,primitiveGroups:[{values:e.sharedReactivity,reasonPrefix:"shared reactivity primitive",bucket:"generic"},{values:e.sharedLifecycle,reasonPrefix:"shared lifecycle primitive",bucket:"generic"}],nameGroups:[{names:e.sharedComposables,label:"shared composable",fallbackBucket:"shared-abstraction"},{names:e.sharedStores,label:"shared store",fallbackBucket:"shared-abstraction"},{names:e.sharedRequests,label:"shared request",fallbackBucket:"generic"},{names:e.sharedFunctions,label:"shared function",fallbackBucket:"generic"},{names:e.sharedFunctionVerbs,label:"shared action verb",fallbackBucket:"generic"},{names:e.sharedBindings,label:"shared binding",fallbackBucket:"generic"},{names:e.sharedTemplateEvents,label:"shared template event",fallbackBucket:"generic"}],recommendation:jH})}function jH(e){switch(e){case"domain-behavior":return"Review for a shared composable, store, or feature module around the named domain behavior.";case"mixed":return"Separate generic Vue mechanics from domain-specific behavior before extracting a composable.";case"shared-abstraction":return"Review the existing composable/store usage first; extract only if duplicated behavior remains outside it.";case"generic-workflow-scaffolding":return"Treat as support evidence for a repeated workflow shape, not direct composable-extraction evidence."}}function HH(e){let t=0,n=0,r=0,i=0,o=0,s=0,a=0;for(let u of e)u.startsWith("composable:")?t+=1:u.startsWith("store:")?n+=1:u.startsWith("request:")?r+=1:u.startsWith("lifecycle:")?i+=1:u.startsWith("function:")?o+=1:u.startsWith("reactivity:")?s+=1:(u.startsWith("function-verb:")||u.startsWith("template-binding:")||u.startsWith("template-event:"))&&(a+=1);let c=t+n,l=c+r+i+o+a;return mr([{name:"requests",count:r},{name:"lifecycle",count:i},{name:"functions",count:o},{name:"reusableHooks",count:c},{name:"reactivity",count:s},{name:"namedBehavior",count:l}],[{min:{requests:1,namedBehavior:4},reason:"shared request workflow"},{min:{lifecycle:1,functions:2,namedBehavior:4},reason:"shared lifecycle workflow"},{min:{reusableHooks:2,requests:1,namedBehavior:5},reason:"shared reusable Vue hooks and requests"},{min:{reusableHooks:2,functions:2,namedBehavior:5},reason:"shared reusable Vue hooks and functions"},{min:{functions:2,reactivity:1,namedBehavior:4},reason:"shared reactive functions"}]).pass}function UH(e){let t=[];return e.sharedComposables.length&&t.push(`shared composables: ${e.sharedComposables.join(", ")}`),e.sharedStores.length&&t.push(`shared stores: ${e.sharedStores.join(", ")}`),e.sharedRequests.length&&t.push(`shared request helpers: ${e.sharedRequests.join(", ")}`),e.sharedLifecycle.length&&t.push(`shared lifecycle: ${e.sharedLifecycle.join(", ")}`),e.sharedFunctions.length&&t.push(`shared functions: ${e.sharedFunctions.slice(0,6).join(", ")}`),e.sharedFunctionVerbs.length&&t.push(`shared action verbs: ${e.sharedFunctionVerbs.slice(0,6).join(", ")}`),e.sharedBindings.length&&t.push(`shared template bindings: ${e.sharedBindings.slice(0,6).join(", ")}`),t.join("; ")||"shared Vue behavior profile"}var qH=new Set(["add","apply","cancel","change","clear","close","composable","create","data","delete","draft","edit","error","fetch","filter","form","item","items","load","loading","name","open","reactive","ref","refresh","remove","request","reset","resource","row","rows","save","saving","search","select","selected","store","submit","toggle","update","use","value","watch"]);function dm(e,t={}){let{minTotalLines:n=800,minTemplateLines:r=300,minScriptLines:i=300,minStyleLines:o=500,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return It(e).vueProfiles({scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>GH(d,{minTotalLines:n,minTemplateLines:r,minScriptLines:i,minStyleLines:o})).filter(d=>d!==null).sort((d,m)=>m.totalLines-d.totalLines||d.file.localeCompare(m.file)).slice(0,s)}function GH(e,t){let n=Dc(e,zH(t),"total"),{reasons:r}=n;if(r.length===0)return null;let i=n.dominantPressure,o=n.pressureKinds.includes("total")?[...new Set([...n.pressureKinds,i])]:n.pressureKinds,s=KH(e.file),a=WH(i,s),c=e.totalLines+e.delegatedComposableLines;return{file:e.file,totalLines:c,sfcLines:e.sfcLines,templateLines:e.templateLines,scriptLines:e.scriptLines,styleLines:e.styleLines,externalScriptLines:e.externalScriptLines,externalScriptPaths:e.externalScriptPaths,customBlockLines:e.customBlockLines,delegatedComposableLines:e.delegatedComposableLines,delegatedComposablePaths:e.delegatedComposablePaths,dominantPressure:i,pressureKinds:o,contextKind:s,recommendationKind:a,recommendation:VH(a,s),reasons:r,loc:c}}function zH(e){return[{axis:"total",value:t=>t.totalLines+t.delegatedComposableLines,qualifies:(t,n)=>n>=e.minTotalLines,reason:(t,n)=>t.delegatedComposableLines>0?`${n} total line(s) (${t.totalLines} component + ${t.delegatedComposableLines} delegated composable line(s) across ${t.delegatedComposablePaths.length} file(s))`:`${n} total component line(s)`,dominantEligible:!1},{axis:"template",value:t=>t.templateLines,qualifies:(t,n)=>n>=e.minTemplateLines,reason:(t,n)=>`${n} template line(s)`},{axis:"script",value:t=>t.scriptLines-t.externalScriptLines,qualifies:t=>t.scriptLines>=e.minScriptLines,reason:t=>`${t.scriptLines} script line(s)`},{axis:"style",value:t=>t.styleLines,qualifies:(t,n)=>n>=e.minStyleLines,reason:(t,n)=>`${n} style line(s)`},{axis:"external-script",value:t=>t.externalScriptLines,qualifies:(t,n)=>n>=e.minScriptLines},{axis:"custom-block",value:t=>t.customBlockLines,qualifies:()=>!1}]}function KH(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(r=>YH.has(r))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function WH(e,t){return e==="style"?"style-decomposition":e==="template"?"template-decomposition":e==="external-script"?"external-script-boundary":e==="custom-block"?"custom-block-review":t==="route-page"?"route-page-decomposition":e==="script"?"script-behavior-extraction":"total-size-review"}function VH(e,t){switch(e){case"template-decomposition":return t==="route-page"?"Split route template sections into named panels before extracting script behavior.":"Split repeated template sections into named presentational components.";case"script-behavior-extraction":return"Extract independent script behavior into composables, controllers, or feature modules.";case"style-decomposition":return"Review UI/style decomposition; move repeated styling to component or style primitives, not composables.";case"external-script-boundary":return"Review the external script boundary and split controller/composable modules by workflow.";case"custom-block-review":return"Review custom block ownership before splitting template or script code.";case"route-page-decomposition":return"Split route/page orchestration from reusable panels and feature controllers.";case"total-size-review":return"Review the largest block first, then split by the dominant reason to change."}}var YH=new Set(["landing","page","pages","route","routes","view","views"]);function JH(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=Me(e,i),c=iU(a,o,s);if(c.length===0)return[];let l=XH(c);return l.length<2?[]:rU(eU(l,n,r),r)}function XH(e){let t=QH(e),n=[];for(let r of e){let i=r.filter(o=>!t.has(o));i.length>=2&&n.push({original:r,filtered:i})}return n}function QH(e){let{nodeFreq:t,tailFreq:n}=ZH(e),r=e.length*.9,i=e.length*.8,o=new Set;for(let[a,c]of t)c>r&&o.add(a);for(let[a,c]of n)c>i&&o.add(a);let s=["index.ts","index.js","cli.ts","main.ts","health.ts","health.js"];for(let a of t.keys()){let c=a.split("/").pop()??"";s.includes(c)&&o.add(a)}return o}function ZH(e){let t=new Map,n=new Map;for(let r of e){let i=new Set;for(let o of r)i.has(o)||(t.set(o,(t.get(o)??0)+1),i.add(o));for(let o=Math.max(0,r.length-2);o<r.length;o++)n.set(r[o],(n.get(r[o])??0)+1)}return{nodeFreq:t,tailFreq:n}}function eU(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=tU(e[i],e[o],t);s&&r.push(s)}if(r.length>n*10)break}return r.sort((i,o)=>Math.abs(o.similarity-i.similarity)>.01?o.similarity-i.similarity:i.divergencePoints.length-o.divergencePoints.length),r}function tU(e,t,n){if(!nU(e.filtered,t.filtered))return null;let{distance:r,ops:i}=oU(e.filtered,t.filtered),o=Math.max(e.filtered.length,t.filtered.length);if(o===0)return null;let s=1-r/o;if(s<n||r===0)return null;let a=i.filter(l=>l.type==="substitute").map(l=>({index:l.indexA,nodeA:e.filtered[l.indexA],nodeB:t.filtered[l.indexB]}));return a.length===0||i.filter(l=>l.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:s,editDistance:r,divergencePoints:a,commonPrefix:sU(e.original,t.original),commonSuffix:aU(e.original,t.original)}}function nU(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function rU(e,t){let n=[];for(let r of e)if(n.some(o=>zx(r.chainA,o.chainA)&&zx(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function iU(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;Kx(e,o,[o],new Set([o]),t,n,r,500)}return r}function Kx(e,t,n,r,i,o,s,a){if(s.length>=a)return;if(n.length>=o){n.length>=i&&s.push([...n]);return}let c=e.get(t);if(!c||c.size===0){n.length>=i&&s.push([...n]);return}let l=!1;for(let u of c)if(!r.has(u)&&(r.add(u),n.push(u),Kx(e,u,n,r,i,o,s,a),n.pop(),r.delete(u),l=!0,s.length>=a))return;!l&&n.length>=i&&s.push([...n])}function oU(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let c=0;c<=n;c++)i[c][0]=c;for(let c=0;c<=r;c++)i[0][c]=c;for(let c=1;c<=n;c++)for(let l=1;l<=r;l++)e[c-1]===t[l-1]?i[c][l]=i[c-1][l-1]:i[c][l]=1+Math.min(i[c-1][l],i[c][l-1],i[c-1][l-1]);let o=[],s=n,a=r;for(;s>0||a>0;)s>0&&a>0&&e[s-1]===t[a-1]?(o.unshift({type:"match",indexA:s-1,indexB:a-1}),s--,a--):s>0&&a>0&&i[s][a]===i[s-1][a-1]+1?(o.unshift({type:"substitute",indexA:s-1,indexB:a-1}),s--,a--):a>0&&i[s][a]===i[s][a-1]+1?(o.unshift({type:"insert",indexA:s,indexB:a-1}),a--):(o.unshift({type:"delete",indexA:s-1,indexB:a}),s--);return{distance:i[n][r],ops:o}}function sU(e,t){let n=[];for(let r=0;r<Math.min(e.length,t.length)&&e[r]===t[r];r++)n.push(e[r]);return n}function aU(e,t){let n=[],r=e.length-1,i=t.length-1;for(;r>=0&&i>=0&&e[r]===t[i];)n.unshift(e[r]),r--,i--;return n}function zx(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function At(e){let t=cU(e.profile?.name),n=()=>{let r=e.candidates(),i=e.filterCandidate?r.filter(e.filterCandidate):r,o=e.orderCandidates?[...i].sort(e.orderCandidates):i,s=he(o,e.scanLimit);t={pipeline:e.profile?.name,loadedCandidates:r.length,filteredCandidates:i.length,scannedCandidates:s.length,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:s.length<i.length,resultLimitApplied:!1};let a=e.prepare?.(s)??void 0,c=[];for(let u of s){t.evaluatedCandidates+=1;let d=e.evaluate(u,a);d&&c.push(d)}t.matchedResults=c.length,e.orderResults&&c.sort(e.orderResults);let l=typeof e.limit=="number"?c.slice(0,e.limit):c;return t.emittedResults=l.length,t.resultLimitApplied=l.length<c.length,e.onProfile?.({...t}),l};return e.profile?N(`candidate-pipeline:${e.profile.name}`,n,()=>({...lU(e.profile?.metadata),...t})):n()}function cU(e){return{pipeline:e,loadedCandidates:0,filteredCandidates:0,scannedCandidates:0,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:!1,resultLimitApplied:!1}}function lU(e){return typeof e=="function"?e():e??{}}function us(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new H(e);return At({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:r,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,profile:{name:"extract-candidates"},prepare:c=>a.calleeMap(c,{semantic:t.semantic!==!1}),evaluate:(c,l)=>uU(c,l.get(c.symbolId)??[],i),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function uU(e,t,n){let r=new Set(t.map(l=>l.symbol));if(r.size<n)return null;let i=gU(r,t),o=hU(r,i);if(o.length<2)return null;let s=yU(o,i);if(s.length===0)return null;let a=T(e.symbol),c=dU(a,r.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:ee(e),totalCallees:r.size,extractionKind:c.extractionKind,actionTier:"signal",evidenceReasons:c.evidenceReasons,recommendation:c.recommendation,clusters:s}}function dU(e,t,n,r){let i=Math.max(...r.map(c=>c.callees.length)),o=Math.max(...r.map(c=>c.isolation)),s=[`${t} distinct callees across ${n} co-occurrence cluster(s)`,`${r.length} extractable cluster(s) passed size and isolation thresholds`,`largest extractable cluster has ${i} callees at ${Math.round(o*100)}% isolation`],a=mU(e,t,n);return a!==null?{extractionKind:"workflow-orchestration",evidenceReasons:[...s,a],recommendation:"Review the isolated helper group as a possible private or feature-local helper, but keep the orchestration sequence together when it preserves the workflow."}:i>=6?{extractionKind:"broad-helper-cluster",evidenceReasons:[...s,"one isolated helper group is broad enough to deserve a named review"],recommendation:"Review whether the broad helper cluster has a stable concept name before extracting it; avoid creating a bag-of-helpers abstraction."}:{extractionKind:"cohesive-helper-cluster",evidenceReasons:s,recommendation:"Review the isolated callee group as a possible same-file or feature-local helper; extract only if the new name preserves the current behavior."}}function mU(e,t,n){if(t>=10)return`callee breadth suggests orchestration: ${t} callees`;if(n>=4)return`multiple disconnected callee groups suggest orchestration: ${n} groups`;let r=pU(e);return fU.has(r)?`caller verb suggests orchestration: ${r}`:null}function pU(e){return e.split(":").pop()?.replace(/\(\)$/,"").replace(/[^A-Za-z0-9_]/g,"").replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\s-]+/).filter(Boolean)[0]?.toLowerCase()??""}var fU=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function gU(e,t){let n=new Map;for(let i of e)n.set(i,new Set);let r=new Map;for(let i of t){let o=r.get(i.chunkId);o||(o=new Set,r.set(i.chunkId,o)),o.add(i.symbol)}for(let i of r.values()){let o=[...i];for(let s=0;s<o.length;s++)for(let a=s+1;a<o.length;a++)n.get(o[s]).add(o[a]),n.get(o[a]).add(o[s])}return n}function hU(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let o=new Set,s=[i];for(;s.length>0;){let a=s.pop();if(!n.has(a)){n.add(a),o.add(a);for(let c of t.get(a)??[])n.has(c)||s.push(c)}}r.push(o)}return r}function yU(e,t){return e.filter(n=>n.size>=3).map(n=>bU(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function bU(e,t,n){let r=new Set;for(let a of t)if(a!==e)for(let c of a)r.add(c);let i=0;for(let a of e)for(let c of n.get(a)??[])r.has(c)&&i++;let o=e.size*r.size,s=o>0?1-i/o:1;return{callees:[...e].map(T),isolation:s}}import{posix as Hi}from"path";import{spawnSync as SU}from"child_process";import{createHash as vU}from"crypto";import{existsSync as CU}from"fs";import{dirname as Wx,join as xU}from"path";import{fileURLToPath as RU}from"url";var Jx=An("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),Vx=dt({kind:"consumer-file-usage",invalidation:$e("consumer-file-usage"),serialize:AU,deserialize:FU});function Dn(e,t){return{forDefinitions(n,r){return EU(e,t,n,r)}}}function Mn(e){let t=new Map;for(let[n,r]of e)t.set(n,new Set(r.files.map(i=>i.file)));return t}function Tc(e,t,n){return Qx(e,t,n).partition}function EU(e,t,n,r){let i=Xx(n.length),o=be()?mn(e):null,s=o?IU(n,r,o):void 0,a=s?{workIdentity:s,workOutcome:"computed"}:{};return N("consumer-evidence.product",()=>{let c=N("consumer-evidence.provenance",()=>wU(e,t,n,r),()=>({...a,definitions:n.length,semantic:r.semantic,sourceFallback:r.sourceFallback!==!1})),l=new Map;i={...i,...c.counters};let u=LU(n,c.sources);return N("consumer-evidence.classify",()=>{let d=PU(e,n,c.sources,u);for(let m of n){let p=d.get(m.symbolId)??MU();i.realFiles+=p.partition.realConsumers.length,i.reexportOnlyFiles+=p.partition.barrelConsumers,i.importOnlyFiles+=p.partition.importOnlyConsumers,l.set(m.symbolId,{definition:m,files:p.files,...p.partition})}},()=>({...a,...u,realFiles:i.realFiles,reexportOnlyFiles:i.reexportOnlyFiles,importOnlyFiles:i.importOnlyFiles})),l},()=>({...a,...i}))}function IU(e,t,n){let r=vU("sha256").update("consumer-evidence-v1\0").update(n).update("\0").update(t.semantic?"semantic\0":"indexed\0").update(t.sourceFallback===!1?"no-source-fallback":"source-fallback");for(let i of e.map(o=>o.symbol).sort())r.update("\0").update(i);return r.digest("hex").slice(0,24)}function Xx(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function wU(e,t,n,r){let i=Xx(n.length),o=new Map;return mm(o,i,"indexed",t.crossFileCallerMap(n,{semantic:!1})),r.semantic&&mm(o,i,"semantic",Jn(e,n)),r.sourceFallback!==!1&&mm(o,i,"source-fallback",t.sourceFallbackCallerFiles(n)),i.totalFiles=[...o.values()].reduce((s,a)=>s+a.size,0),{sources:o,counters:i}}function LU(e,t){return{definitions:e.length,consumerFiles:[...t.values()].reduce((n,r)=>n+r.size,0),nativeAttempted:!1,nativeUsed:!1,nativeReason:"not-attempted"}}function mm(e,t,n,r){let i=0;for(let[o,s]of r){let a=e.get(o);a||(a=new Map,e.set(o,a));for(let c of s){i++;let l=a.get(c)??new Set;l.add(n),a.set(c,l)}}n==="indexed"?t.indexedFiles+=i:n==="semantic"?t.semanticFiles+=i:t.fallbackFiles+=i}function PU(e,t,n,r){let i=HU(e,t,n,r);return i||DU(e,t,n)}function DU(e,t,n){let r=new Map;for(let i of t){let o=n.get(i.symbolId)??new Map;r.set(i.symbolId,Qx(e,i,[...o.keys()],o))}return r}function Qx(e,t,n,r=new Map){let i=[],o=0,s=0,a=z(t.symbol),c=[];for(let l of n){let u;NU(e,l,t.relativePath,a)?(o++,u="reexport-only"):pm(e,l,a)?(s++,u="import-only"):(i.push(l),u="real"),c.push({file:l,sources:[...r.get(l)??[]],classification:u})}return{partition:{realConsumers:i,barrelConsumers:o,importOnlyConsumers:s},files:c}}function MU(){return{partition:{realConsumers:[],barrelConsumers:0,importOnlyConsumers:0},files:[]}}function pm(e,t,n){if(!n)return!1;let r=se(t);if(!r)return!1;let i=Jx.get(e,t,()=>Zx(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function Zx(e,t,n){let r=On(e).forFile(t,{text:!0,ast:!0}),i=r.text;if(!i)return kU();let o=Rt(e,t,i),s=Vx.read(e,t,o);if(s)return s;let a=TU(r.ast,n);return Vx.write(e,t,o,a),a}function TU(e,t){let n=new Set,r=new Set;if(!e)return{importedLeaves:n,usedLeaves:r};let i=t==="rust"?new Set(["use_declaration"]):t==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),o=(s,a)=>{let c=a||i.has(s.type);(s.type==="identifier"||s.type==="type_identifier"||s.type==="property_identifier"||s.type==="field_identifier")&&(c?n.add(s.text):r.add(s.text));for(let l of s.children)o(l,c)};return o(e.rootNode,!1),{importedLeaves:n,usedLeaves:r}}function kU(){return{importedLeaves:new Set,usedLeaves:new Set}}function AU(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function FU(e){try{let t=JSON.parse(e);return!Array.isArray(t.importedLeaves)||!Array.isArray(t.usedLeaves)?null:{importedLeaves:new Set(t.importedLeaves.filter(n=>typeof n=="string")),usedLeaves:new Set(t.usedLeaves.filter(n=>typeof n=="string"))}}catch{return null}}function NU(e,t,n,r){if(!r)return!1;let i=On(e).forFile(t,{lines:!0,reexports:!0}),o=i.lines??[];if(o.length===0)return!1;let s=i.reexports??[];return eR(o,s,r)}function eR(e,t,n){if(e.length===0||t.length===0)return!1;let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\b${r}\\b`),o=0;for(let s=0;s<e.length;s++){if(!i.test(e[s]??""))continue;if(o++,!t.find(c=>c.startLine<=s&&s<=c.endLine))return!1}return o>0}var _U="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY",OU="SCIP_QUERY_NATIVE_KERNELS_BIN",BU="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY_MIN_FILES",Yx=1e3,$U=5e3,jU=64*1024*1024,Mc;function HU(e,t,n,r){let i=process.env[_U]?.toLowerCase();if(i!=="1"&&i!=="true")return r.nativeReason=i==="0"||i==="false"?"disabled":"opt-in-required",null;if(r.consumerFiles<VU())return r.nativeReason="below-threshold",null;let o=YU();if(!o)return r.nativeReason="binary-missing",null;r.nativeAttempted=!0;let s=UU(e,t,n),a=SU(o,["consumer-classify"],{input:JSON.stringify(s),encoding:"utf8",timeout:$U,maxBuffer:jU});if(a.status!==0||a.error)return r.nativeReason=a.error?`spawn-error:${a.error.message}`:`exit-${a.status??"null"}`,null;try{let c=JSON.parse(a.stdout),l=GU(c,t);return l?(r.nativeUsed=!0,r.nativeReason="used",l):(r.nativeReason="invalid-response",null)}catch{return r.nativeReason="invalid-json",null}}function UU(e,t,n){let r=new Map,i=[];for(let a of t){let c=z(a.symbol),u=[...(n.get(a.symbolId)??new Map).entries()].map(([d,m])=>{let p=r.get(d)??new Set;return c&&p.add(c),r.set(d,p),{file:d,sources:[...m]}});i.push({symbol_id:a.symbolId,leaf:c,consumer_files:u})}let o={},s={};for(let[a,c]of r){let l=se(a);if(l){let d=Jx.get(e,a,()=>Zx(e,a,l));o[a]={imported_leaves:[...d.importedLeaves],used_leaves:[...d.usedLeaves]}}let u=qU(e,a,c);u.length>0&&(s[a]=u)}return{definitions:i,file_usages:o,reexport_only_leaves:s}}function qU(e,t,n){if(n.size===0)return[];let r=On(e).forFile(t,{lines:!0,reexports:!0}),i=r.lines??[],o=r.reexports??[];return i.length===0||o.length===0?[]:[...n].filter(s=>eR(i,o,s))}function GU(e,t){if(!Array.isArray(e.entries)||e.entries.length!==t.length)return null;let n=new Set(t.map(i=>i.symbolId)),r=new Map;for(let i of e.entries){let o=zU(i);if(!o||!n.has(o.symbol_id))return null;r.set(o.symbol_id,{partition:{realConsumers:o.real_consumers,barrelConsumers:o.barrel_consumers,importOnlyConsumers:o.import_only_consumers},files:o.files})}for(let i of n)if(!r.has(i))return null;return r}function zU(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.symbol_id!="number"||!Array.isArray(t.real_consumers)||typeof t.barrel_consumers!="number"||typeof t.import_only_consumers!="number"||!Array.isArray(t.files)||!t.real_consumers.every(r=>typeof r=="string"))return null;let n=[];for(let r of t.files){if(!r||typeof r!="object")return null;let i=r;if(typeof i.file!="string"||!Array.isArray(i.sources)||!i.sources.every(KU)||!WU(i.classification))return null;n.push({file:i.file,sources:i.sources,classification:i.classification})}return{symbol_id:t.symbol_id,real_consumers:t.real_consumers,barrel_consumers:t.barrel_consumers,import_only_consumers:t.import_only_consumers,files:n}}function KU(e){return e==="indexed"||e==="semantic"||e==="source-fallback"}function WU(e){return e==="real"||e==="reexport-only"||e==="import-only"}function VU(){let e=process.env[BU];if(!e)return Yx;let t=Number(e);return Number.isFinite(t)&&t>=0?t:Yx}function YU(){if(Mc!==void 0)return Mc;let e=process.env[OU],t=process.platform==="win32"?"scip-query-kernels.exe":"scip-query-kernels";return Mc=[...e?[e]:[],...JU().map(r=>xU(r,"target","release",t))].find(r=>CU(r))??null,Mc}function JU(){let e=new Set,t=Wx(RU(import.meta.url));for(let n=0;n<5;n++)e.add(t),t=Wx(t);return[...e]}var XU=20,QU=1,ZU=new Map([["app","app"],["apps","app"],["component","component"],["components","component"],["composable","composable"],["composables","composable"],["contract","contract"],["contracts","contract"],["domain","domain"],["domains","domain"],["feature","feature"],["features","feature"],["hook","hook"],["hooks","hook"],["lib","library"],["module","module"],["modules","module"],["package","package"],["packages","package"],["page","page"],["pages","page"],["route","route"],["routes","route"],["screen","screen"],["screens","screen"],["service","service"],["services","service"],["shared","shared"],["src","source-root"],["store","state"],["stores","state"],["test","test"],["tests","test"],["util","utility"],["utils","utility"],["view","view"],["views","view"]]),eq=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),tq=new Set(["access","api","auth","config","db","effect","errors","hooks","lib","middleware","permissions","routes","schemas","servicetasks","services","startup","store","stores","test-utils","repository","repositories","tests","types","ui","utils","workflow","workflows"]);function nq(e,t={}){let n=hm(t.limit,XU),r=hm(t.minConsumers,QU),i=new H(e),o=i.fileDependencyGraph(t.scope),s=xq(Z(e,{includeIgnored:!1})),a=Iq(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?rq(e,i,t.target):iq(e,t.scope,t.scanLimit)).map(u=>oq(e,i,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=r||t.target).sort(Cq).slice(0,n)}function rq(e,t,n){let r=cq(e,n);if(r)return[oR(r)];let i=ne(e,n);if(!i)return[];let o=t.definitionsForFile(i.relativePath).find(s=>s.symbolId===i.symbolId);return o?[lq(o)]:[{unit:{kind:"symbol",file:i.relativePath,shortName:T(i.symbol),symbol:i.symbol,startLine:i.startLine,endLine:i.endLine}}]}function iq(e,t,n){let r=Z(e,{scope:t,includeIgnored:!1}),i=hm(n,r.length);return r.slice(0,i).map(o=>oR(o))}function oq(e,t,n,r,i,o,s){let a=r.definition?sq(e,t,r.definition,i.semantic):aq(n,r.unit.file),c=r.definition?a.length>0?"exact":"none":a.length>0?"file-level":"none",l=r.unit.file,u=$t(Hi.dirname(l)),d=dq(a),m=uq(u),p=bm([...tR(u),...d?tR(d):[]]),f=mq(r.unit,u,d,a),g=pq(f,r.unit,u,d,a,o,s),h=bq(r.unit,c,d,a,u,g.whyNoSuggestedHome),b=Sq(r.unit,u,d,a,g.suggestedHome,g.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:r.unit,candidatePath:l,currentDirectory:u,directoryAncestry:m,consumerFiles:a,consumerCoverage:c,nearestCommonOwner:d,boundaryMarkers:p,recommendedTier:f,suggestedHome:g.suggestedHome,destinationConfidence:g.confidence,whyNoSuggestedHome:g.whyNoSuggestedHome,counterevidence:h,reasons:b,recommendation:vq(f,g.suggestedHome,c)}}function sq(e,t,n,r){let i=Mn(Dn(e,t).forDefinitions([n],{semantic:r!==!1,sourceFallback:!0}));return uR(i.get(n.symbolId)??[])}function aq(e,t){let n=[];for(let[r,i]of e.entries())r!==t&&i.has(t)&&n.push(r);return uR(n)}function cq(e,t){let n=ws(t),r=Z(e,{includeIgnored:!1}),i=r.find(s=>s===n);if(i)return i;let o=r.find(s=>s.endsWith(`/${n}`));return o||(r.find(s=>s.includes(n))??null)}function lq(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:T(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function oR(e){return{unit:{kind:"file",file:e,shortName:Hi.basename(e)}}}function uq(e){if(e===".")return[{path:".",depth:0,markers:[]}];let t=[],n=e.split("/").filter(Boolean);for(let r=0;r<n.length;r+=1){let i=n.slice(0,r+1).join("/");t.push({path:i,depth:r,markers:ym(i)})}return t}function tR(e){return e==="."?[]:sR(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function ym(e){return bm(sR(e).map(({marker:t})=>t))}function sR(e){let t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){let i=ZU.get(t[r]);i&&n.push({marker:i,prefix:t.slice(0,r+1).join("/")})}return n}function dq(e){if(e.length===0)return null;let t=e.map(r=>$t(Hi.dirname(r))),n=t[0].split("/").filter(Boolean);for(let r of t.slice(1)){let i=r.split("/").filter(Boolean),o=[],s=Math.min(n.length,i.length);for(let a=0;a<s&&n[a]===i[a];a+=1)o.push(n[a]);n=o}return n.length===0?".":n.join("/")}function mq(e,t,n,r){return n?e.kind==="symbol"&&r.length===1?r[0]===e.file?"same-file":"sibling-folder":n==="."||n==="src"?"repository-level-review":rR(n,"package")?"package-level-shared":rR(n,"app")?"app-level-shared":iR(n,["feature","domain","module"])||iR(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function pq(e,t,n,r,i,o,s){let a=fq(e,r);if(a)return pr(a);let c=Rq(t.file),l=gq(e,n,c,i,s);if(l)return l;let u=r;if($t(n)===$t(u))return pr(`${n} is already the nearest common owner for its consumers.`);let d=hq(u,n,c,s);return d||yq(u,n,c,o,s)}function fq(e,t){return t?e==="no-exact-consumers"||e==="repository-level-review"?"The inferred owner is too broad or unsupported for an exact destination.":null:"No consumer owner could be inferred from the current index."}function gq(e,t,n,r,i){if(e==="same-file"){let o=r[0]??null;return o?fm(o):pr("No same-file consumer path was available.")}if(e==="sibling-folder"&&r.length===1){let o=$t(Hi.dirname(r[0])),s=lR(t,n,o,i);return s?pr(s):fm(o)}return null}function hq(e,t,n,r){return Lq(e)?aR(e,t,n,r,`Nearest shared owner ${e} is outside source root ${n}.`):null}function yq(e,t,n,r,i){if(e===".")return pr("The nearest common owner is the repository root.");let o=`${e}/shared`,s=aR(o,t,n,i,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||r.has(o)?s:pr(`${o} does not exist in the indexed project.`)}function aR(e,t,n,r,i){if(!cR(e,n))return pr(i);let o=lR(t,n,e,r);return o?pr(o):fm(e)}function fm(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function pr(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function bq(e,t,n,r,i,o){let s=["Report-only signal; review ownership before moving files."];return t==="none"&&s.push("No consumers were found in the current index."),t==="file-level"&&s.push("File-level import evidence can hide which exported unit is actually used."),(n==="."||n==="src")&&s.push("Nearest common owner is broad, so this is not enough evidence for automatic placement."),r.length===1&&s.push("Only one consumer was found; inlining or same-folder placement may be better than shared extraction."),e.kind==="file"&&s.push("File targets describe module locality, not symbol-level usage."),n&&i.startsWith(`${n}/`)&&s.push("Candidate already lives under the nearest common owner."),o&&s.push(`No exact suggested home: ${o}`),s}function Sq(e,t,n,r,i,o){let s=[];return s.push(`${e.shortName} currently lives in ${t}.`),n?s.push(`${r.length} consumer file(s) share ${n} as their nearest common owner.`):s.push("No consumer owner could be inferred from the current index."),i?s.push(`Suggested home is ${i}.`):o&&s.push(`No exact suggested home: ${o}`),s}function vq(e,t,n){return e==="no-exact-consumers"?"Review references before moving; no consumers were found.":e==="repository-level-review"?"Keep this as a broad locality signal; the inferred owner is too general for automatic relocation.":t?`Review whether ${n==="exact"?"symbol usage":"module import"} supports moving or extracting toward ${t}.`:"Review ownership manually before changing structure."}function Cq(e,t){return nR(t)-nR(e)||e.candidatePath.localeCompare(t.candidatePath)}function nR(e){let t=e.consumerFiles.length*10;return e.consumerCoverage==="exact"&&(t+=5),e.suggestedHome&&(t+=3),e.recommendedTier==="repository-level-review"&&(t*=.1),e.recommendedTier==="no-exact-consumers"&&(t*=.05),t}function xq(e){let t=new Set(["."]);for(let n of e){let r=$t(Hi.dirname(n));for(;!t.has(r)&&(t.add(r),r!==".");)r=$t(Hi.dirname(r))}return t}function Rq(e){let t=gm(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function cR(e,t){let n=$t(e),r=$t(t);return r==="."||n===r||n.startsWith(`${r}/`)}function Eq(e,t,n){let r=gm(e),i=gm(t);return(cR(e,t)?r.slice(i.length):r).some(s=>n.has(s.toLowerCase()))}function lR(e,t,n,r){return $t(e)===$t(n)||!Eq(e,t,r)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function Iq(...e){let t=new Set(tq);for(let n of e)for(let r of n??[]){let i=wq(r);i&&t.add(i)}return t}function wq(e){let t=e.trim().toLowerCase();return t===""?null:t}function rR(e,t){return ym(e).includes(t)}function iR(e,t){let n=ym(e);return t.some(r=>n.includes(r))}function Lq(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?eq.has(n):!1}function $t(e){let t=ws(e);return t===""?".":t}function gm(e){let t=ws(e);return t==="."?[]:t.split("/").filter(Boolean)}function hm(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function uR(e){return bm([...e]).sort((t,n)=>t.localeCompare(n))}function bm(e){return[...new Set(e)]}function Sm(e,t,n={}){return dR(e,t,n).rows}function Pq(e,t,n={}){return dR(e,t,n)}function dR(e,t,n){let{maxDepth:r=5,scope:i}=n,o=r===Number.MAX_SAFE_INTEGER,s=o?null:500,a=ne(e,t);if(!a)return{rows:[],coverage:{status:"incomplete",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:r,reachedDepth:0,perSymbolEvidenceLimit:s,remainingFrontierSymbols:0,reasons:["The requested symbol could not be resolved."]}};let c=[],l=new Set([a.symbolId]),u=new Set,d=[a],m=0,p=!1;for(let h=1;h<=r&&d.length!==0;h++){m=h;let b=[],S=hn(e,d,{...o?{}:{limit:s+1},semanticEvidence:re});for(let y of d){let x=S.get(y.symbolId)??[];s!==null&&x.length>s&&(p=!0);let v=s===null?x:x.slice(0,s);for(let C of Dq(e,y,i,v)){let R=`${C.file}|${C.shortName}`;if(C.symbolId!==null){if(l.has(C.symbolId))continue;l.add(C.symbolId)}else if(u.has(R))continue;u.add(R),c.push({symbol:C.symbol,shortName:C.shortName,file:C.file,depth:h}),C.symbolId!==null&&C.symbolMatch&&b.push(C.symbolMatch)}}d=b}c.sort((h,b)=>h.depth-b.depth||h.file.localeCompare(b.file));let f=d.length>0,g=[];return f&&g.push(`${d.length} symbol(s) remain eligible beyond depth ${r}.`),p&&g.push(`At least one symbol had more than ${s} incoming evidence row(s).`),g.length===0&&g.push("The discovered reverse evidence frontier was exhausted."),{rows:c,coverage:{status:f||p?"bounded":"accounted",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:r,reachedDepth:m,perSymbolEvidenceLimit:s,remainingFrontierSymbols:d.length,reasons:g}}}function Dq(e,t,n,r){let i=r.filter(u=>!e.isIgnored(u.file)).filter(u=>!n||u.file.includes(n)),o=new Set(i.map(u=>u.file)),s=[];for(let u of Mq(e,t,n)){if(o.has(u))continue;let d=U(e,u),m=d.length>0?Ne(d,d[0].startLine):null;s.push({symbol:m?.symbol??u,file:u})}let a=[...i,...s],c=[],l=new Set;for(let u of a){let d=Sr(e,u.symbol);if(!d){let p=`${u.file}|${u.symbol}`;if(l.has(p))continue;l.add(p),c.push({symbolId:null,symbol:u.symbol,shortName:T(u.symbol),file:u.file,symbolMatch:null});continue}if(d.symbolId===t.symbolId||e.isIgnored(d.relativePath)||!Tq(d))continue;let m=`${d.symbolId}|${d.relativePath}`;l.has(m)||(l.add(m),c.push({symbolId:d.symbolId,symbol:d.symbol,shortName:T(d.symbol),file:d.relativePath,symbolMatch:d}))}return c}function Mq(e,t,n){let r=n?"AND consumer_d.relative_path LIKE ?":"",i=[t.symbolId,t.documentId];return n&&i.push(`%${n}%`),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
|
|
323
|
-
FROM mentions m
|
|
324
|
-
JOIN chunks c ON m.chunk_id = c.id
|
|
325
|
-
JOIN documents consumer_d ON consumer_d.id = c.document_id
|
|
326
|
-
WHERE m.symbol_id = ?
|
|
327
|
-
AND m.role != 1
|
|
328
|
-
AND c.document_id != ?
|
|
329
|
-
${e.pathExclusionsFor("consumer_d")}
|
|
330
|
-
${r}`,...i).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function Tq(e){if(e.symbol.startsWith("scip-clojure ")||se(e.relativePath)==="clojure")return!0;let t=wt(e.symbol);return t==="method"||t==="type"||e.symbol.endsWith("().")}function pR(e,t){let n=it(t),r=[],i="complete",o=q(n);o==="entry"&&Tn(r,"operational-root","structural entrypoint path"),o==="worker"&&Tn(r,"operational-root","worker launch convention"),td(n)&&Tn(r,"operational-root","framework-discovered entrypoint"),kq(e,n)&&Tn(r,"operational-root","configured entry root");let s=!1;try{s=Cn(e,n),s&&Tn(r,"published-api","package manifest export");for(let a of pb(e,n))Tn(r,"operational-root",a)}catch(a){i="partial",Tn(r,"metadata-unavailable",`package metadata unavailable: ${mR(a)}`)}try{let a=Ye(e.config.projectRoot,n,{maxBytes:8388608,inputKind:"change-surface source"});Aq(a)&&Tn(r,"operational-root","module contains a direct-execution process guard")}catch(a){i="partial",Tn(r,"metadata-unavailable",Je(a)?"indexed source file is unavailable on disk":`source metadata unavailable: ${mR(a)}`)}return{operationalRoot:r.some(a=>a.kind==="operational-root"),publishedApi:s,coverage:i,reasons:r}}function kq(e,t){let n=e.config.entryRoots;return n?n.files?.some(r=>it(r)===t)?!0:n.pathPrefixes?.some(r=>t.startsWith(it(r)))??!1:!1}function Aq(e){return e.includes("import.meta.url")&&/process\.argv\s*\[\s*1\s*\]/.test(e)||/require\.main\s*===\s*module/.test(e)||/__name__\s*==\s*['"]__main__['"]/.test(e)}function Tn(e,t,n){e.some(r=>r.kind===t&&r.detail===n)||e.push({kind:t,detail:n})}function mR(e){return e instanceof Error?e.message:String(e)}function vm(e,t,n={}){let r=mt(e,t);if(!r)return null;let i=Fq(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=0,a=Nq(e,i.relative_path),c=pR(e,i.relative_path),l=n.semantic===!1?new Map:Jn(e,a);for(let u of a){let d=_q(e,i,u,l.get(u.symbolId)??new Set);s+=d;let m=Oq(d),p=[...c.reasons,...d>0?[{kind:"external-consumers",detail:`${d} external consumer${d===1?"":"s"}`}]:[]];o.push({symbol:u.symbol,shortName:T(u.symbol),startLine:u.startLine,endLine:u.endLine,externalConsumers:d,externalConsumerRiskLevel:m,riskLevel:Bq(m,c),riskReasons:p})}return{file:i.relative_path,symbols:o,totalExternalConsumers:s,fileRisk:c}}function Fq(e,t){return e.get(`SELECT id, relative_path FROM documents
|
|
331
|
-
WHERE relative_path = ?
|
|
332
|
-
${e.pathExclusionsFor("documents")}
|
|
333
|
-
LIMIT 1`,t)??null}function Nq(e,t){return new H(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function _q(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
|
|
334
|
-
FROM mentions m
|
|
335
|
-
JOIN chunks c ON m.chunk_id = c.id
|
|
336
|
-
JOIN documents consumer_d ON consumer_d.id = c.document_id
|
|
337
|
-
WHERE m.symbol_id = ?
|
|
338
|
-
AND m.role != 1
|
|
339
|
-
AND c.document_id != ?`,n.symbolId,t.id);return new Set([...i.map(o=>o.relative_path),...[...r].filter(o=>o!==t.relative_path)]).size}function Oq(e){return e>10?"high":e>0?"medium":"low"}function Bq(e,t){return e==="high"?"high":e==="medium"||t.operationalRoot||t.publishedApi||t.coverage==="partial"?"medium":"low"}function $q(e,t={}){let{scope:n,minLoc:r=1,maxDepth:i=5,scanLimit:o}=t,s=new H(e),a=jq(e,n,r,o),c=new Cm;for(let g of a)c.add(g);let l=[],u=[];a.length>0&&l.push(fR(e,0,a,c));let d=a.map(g=>g.definition).filter(g=>g!==null),m=new Set(a.map(g=>g.symbol));for(let g=1;g<=i&&d.length>0;g++){let h=s.calleeMap(d,{semantic:!1}),b=new Set;for(let y of d)for(let x of h.get(y.symbolId)??[])m.has(x.symbol)||b.add(x.symbol);let S=[];for(let y of b){m.add(y);let x=gR(e,y);if(!x||e.isIgnored(x.relativePath)||Ue(e,x.relativePath)||Te(e,x.symbol,x.relativePath)||s.fileKind(x.relativePath)==="test"||s.hasSuppressionComment(x))continue;let v=Uq(e,x,c);v.removable?S.push(Hq(x,"cascade")):v.blockingFiles.length>0&&u.push({shortName:T(x.symbol),file:x.relativePath,blockingFiles:v.blockingFiles.slice(0,3)})}if(S.length===0)break;for(let y of S)c.add(y);l.push(fR(e,g,S,c)),d=S.map(y=>y.definition).filter(y=>y!==null)}let p=l.reduce((g,h)=>g+h.loc,0),f=l.reduce((g,h)=>g+h.entries.length,0);return{batches:l,totalSymbols:f,totalLoc:p,blocked:u}}function jq(e,t,n,r){let i=zr(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:r,semantic:!1}),o=[];for(let s of i.symbols)s.kind==="dead-code"&&(Ue(e,s.relativePath)||Te(e,s.symbol,s.relativePath)||o.push({symbol:s.symbol,shortName:s.shortName,file:s.relativePath,startLine:s.startLine,endLine:s.endLine,loc:s.loc,evidence:"graph-fact",definition:gR(e,s.symbol)}));return o}function Hq(e,t){return{symbol:e.symbol,shortName:T(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function gR(e,t){let n=e.get(`SELECT d.relative_path
|
|
340
|
-
FROM global_symbols gs
|
|
341
|
-
JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
342
|
-
JOIN documents d ON d.id = der.document_id
|
|
343
|
-
WHERE gs.symbol = ?
|
|
344
|
-
LIMIT 1`,t);return n?U(e,n.relative_path).find(r=>r.symbol===t)??null:null}function Uq(e,t,n){let r=eo(e,t);if(r.length===0)return{removable:!1,blockingFiles:[]};let i=new Set;for(let o of r)o.file===t.relativePath&&o.line>=t.startLine&&o.line<=t.endLine||n.contains(o.file,o.line)||i.add(o.file);return{removable:i.size===0,blockingFiles:[...i]}}function fR(e,t,n,r){let i=[...n].sort((a,c)=>a.file.localeCompare(c.file)||a.startLine-c.startLine),o=new Set(i.map(a=>a.file)),s=[];for(let a of o){let c=U(e,a);c.length>0&&c.every(l=>r.contains(a,l.startLine))&&s.push(a)}return{depth:t,entries:i.map(({definition:a,...c})=>c),loc:i.reduce((a,c)=>a+c.loc,0),filesEmptied:s.sort()}}var Cm=class{ranges=new Map;add(t){let n=this.ranges.get(t.file)??[];n.push({start:t.startLine,end:t.endLine}),this.ranges.set(t.file,n)}contains(t,n){let r=this.ranges.get(t);return r?r.some(i=>n>=i.start&&n<=i.end):!1}};import{execFileSync as Ui}from"child_process";import{existsSync as qq}from"fs";import{basename as hR}from"path";function kc(e){let t=new Map;for(let n of e){let r=t.get(n.file);r||(r=[],t.set(n.file,r)),r.push(n)}return t}var wm="Unable to compute git diff.",Gq={semanticConsumers:Jn,sourceFallbackConsumers:ko},Lm={resolveCommit:dl,readBatch({projectRoot:e,resolvedBase:t,relativePaths:n}){let r=n.map(i=>`${t}:./${i}
|
|
345
|
-
`).join("");return Ui("git",["cat-file","--batch"],{cwd:e,input:r,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"]})}};function Ac(e,t={}){let n=t.plan??qi(e,t);return n.note?zq(n.note,n.changedFileLines):n.changedFiles.length===0?Kq(n.changedFileLines):Fc(n.changedFiles,[vR(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function qi(e,t={}){let{base:n="HEAD"}=t;try{let r=dl(e.config.projectRoot,n),i=Wq(e.config.projectRoot,r),o=i.changedFileLines,s=Zq(e,o),a=eG(e,i.changedRanges);return{changedFileLines:o,changedFiles:s,changedRanges:a,renamedFiles:Jq(e.config.projectRoot,r,s,i),note:o.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:wm}}}function vR(e,t,n,r=[],i={}){let o=i.evidenceRuntime??Gq,s=new H(e),a=new Set(n),c=kc(r),l=[],u=new Map,d=t.flatMap(E=>s.definitionsForFile(E)).filter(hG),m=d.filter(E=>nG(E,c)),p=iG(e,d,m,c),f=aG([...m,...p.definitions]).sort((E,w)=>E.relativePath.localeCompare(w.relativePath)||E.startLine-w.startLine),g=f.map(E=>E.symbolId),h=pG(e,g),b=fG(e,g,n),S=f.filter(E=>(h.get(E.symbolId)??0)===0),y=SR("semantic-consumers",S.length,()=>o.semanticConsumers(e,S)),x=y.values,v=S.filter(E=>(x.get(E.symbolId)?.size??0)===0),C=SR("source-fallback-consumers",v.length,()=>o.sourceFallbackConsumers(e,v)),R=C.values;for(let E of f)uG(e,E,a,l,u,x.get(E.symbolId)??new Set,R.get(E.symbolId)??new Set,h.get(E.symbolId)??0,b.get(E.symbolId)??new Set);return{changedSymbols:l,consumerEntries:[...u.entries()].map(([E,w])=>({file:E,symbols:[...w].sort()})),attributionNotes:p.notes,evidenceTiers:[y.status,C.status]}}function Fc(e,t){let n=new Map,r=t.flatMap(a=>a.changedSymbols),i=t.flatMap(a=>a.attributionNotes??[]),o=dG(t);for(let a of t)for(let c of a.consumerEntries){let l=n.get(c.file);l||(l=new Set,n.set(c.file,l));for(let u of c.symbols)l.add(u)}let s=gG(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:s,attributionNotes:i,evidenceTiers:o,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:s.length}}}function zq(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:LR(),summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function Kq(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:LR(),summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function Wq(e,t){let n=Ui("git",["diff","--name-status","--find-renames",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864}),r=Ui("git",["diff","--name-status","--find-renames","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),i=Ui("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),o=Ui("git",["diff","--unified=0",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),s=Ui("git",["diff","--unified=0","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),a=Xq([n,r]);return{changedFileLines:[...new Set([...a.changedFiles,...RR(i)])],changedRanges:IR([...bR(o),...bR(s)]),renamedFiles:a.renamedFiles,deletedFiles:a.deletedFiles}}function Vq(e,t,n){let r=typeof e=="string"?{projectRoot:e,base:t,relativePath:n}:e;if(typeof r.projectRoot!="string"||typeof r.base!="string"||typeof r.relativePath!="string")throw new TypeError("fileContentAtBase requires projectRoot, base, and relativePath.");let i={projectRoot:r.projectRoot,base:r.base,relativePath:r.relativePath},{relativePath:o}=i,s=Pm(i);if(s.state==="unavailable")throw new Error(`Base content unavailable for ${o}: ${s.reason}`);return s.state==="present"?s.content:null}function Pm(e,t=Lm){return xR(e.relativePath),Dm({projectRoot:e.projectRoot,base:e.base,relativePaths:[e.relativePath]},t).get(e.relativePath)??{state:"unavailable",reason:`Base-content lookup omitted ${e.relativePath}.`}}function Dm(e,t=Lm){for(let s of e.relativePaths)xR(s);let n=[...new Set(e.relativePaths)];if(n.length===0)return new Map;let r;try{r=t.resolveCommit(e.projectRoot,e.base)}catch(s){return xm(n,Rm(s))}let i;try{i=t.readBatch({projectRoot:e.projectRoot,resolvedBase:r,relativePaths:n})}catch(s){return xm(n,Rm(s))}let o;try{o=Yq(i,n)}catch(s){return xm(n,`Malformed git cat-file batch output: ${Rm(s)}`)}return new Map(n.map(s=>{let a=o.get(s)??null;return[s,a===null?{state:"absent"}:{state:"present",content:a}]}))}function Mm(e,t=Lm){let n=Dm({projectRoot:e.projectRoot,base:e.base,relativePaths:e.preloadPaths??[]},t);return r=>(n.has(r)||n.set(r,Pm({projectRoot:e.projectRoot,base:e.base,relativePath:r},t)),n.get(r)??{state:"unavailable",reason:`Base-content reader omitted ${r}.`})}function CR(e,t=e.changedFiles){let n=new Map(e.renamedFiles.map(r=>[r.to,r.from]));return[...new Set(t.map(r=>n.get(r)??r))]}function xR(e){un(e)}function xm(e,t){return new Map(e.map(n=>[n,{state:"unavailable",reason:t}]))}function Rm(e){let n=(e instanceof Error?e.message:String(e)).replaceAll(/\s+/g," ").trim().slice(0,500);return n===""?"Git base-content lookup failed without a reason.":n}function Yq(e,t){let n=new Map,r=0;for(let i of t){let o=e.indexOf(10,r);if(o<0)throw new Error("git cat-file batch output ended before object header");let s=e.subarray(r,o).toString("utf-8");if(r=o+1,s.endsWith(" missing")){n.set(i,null);continue}let a=/^[0-9a-f]+ ([^ ]+) (\d+)$/.exec(s);if(!a)throw new Error(`unexpected git cat-file batch header: ${s}`);let[,c,l]=a,u=Number(l);if(!Number.isFinite(u)||u<0)throw new Error(`unexpected git cat-file batch size: ${s}`);if(r+u>e.length)throw new Error("git cat-file batch output ended before blob payload");let d=e.subarray(r,r+u);n.set(i,c==="blob"?d.toString("utf-8"):null),r+=u,e[r]===10&&(r+=1)}return n}function Jq(e,t,n,r){if(n.length===0)return[];let i=new Map,o=new Set;for(let a of r.renamedFiles)n.includes(a.to)&&(i.set(a.to,a),o.add(a.from));let s=r.deletedFiles;if(s.length===0)return[...i.values()].sort((a,c)=>a.to.localeCompare(c.to));for(let a of n){if(i.has(a)||!qq(`${e}/${a}`))continue;let c=s.filter(d=>!o.has(d)).filter(d=>hR(d)===hR(a));if(c.length===0)continue;let l=Ye(e,a),u=c.map(d=>({from:d,to:a,similarity:Qq(Vq({projectRoot:e,base:t,relativePath:d})??"",l)})).sort((d,m)=>m.similarity-d.similarity)[0];u&&u.similarity>=.45&&(i.set(a,u),o.add(u.from))}return[...i.values()].sort((a,c)=>a.to.localeCompare(c.to))}function Xq(e){let t=new Set,n=new Map,r=new Set;for(let i of e.flatMap(o=>RR(o))){let[o,s,a]=i.split(" ");if(!(!o||!s)){if(o.startsWith("R")&&a){t.add(a),n.set(a,{from:s,to:a,similarity:Number(o.slice(1))/100});continue}t.add(s),o.startsWith("D")&&r.add(s)}}return{changedFiles:[...t],renamedFiles:[...n.values()],deletedFiles:[...r]}}function Qq(e,t){let n=new Set(yR(e)),r=new Set(yR(t));if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let i=0;for(let o of n)r.has(o)&&(i+=1);return 2*i/(n.size+r.size)}function yR(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function RR(e){return e.split(`
|
|
346
|
-
`).map(t=>t.trim()).filter(t=>t.length>0)}function Zq(e,t){let n=ER(e),r=[];for(let i of t){let o=n(i);o&&!e.isIgnored(o)&&r.push(o)}return r}function eG(e,t){let n=ER(e),r=[];for(let i of t){let o=n(i.file);o&&!e.isIgnored(o)&&r.push({...i,file:o})}return IR(r)}function ER(e){let t=e.all(`SELECT relative_path FROM documents
|
|
347
|
-
ORDER BY id`).map(r=>r.relative_path),n=new Map(t.map(r=>[r,r]));return r=>{let i=r.replace(/\\/g,"/"),o=n.get(i);return o||(t.find(s=>s.endsWith(i))??null)}}function bR(e){let t=[],n=null;for(let r of e.split(`
|
|
348
|
-
`)){if(r.startsWith("+++ ")){n=tG(r.slice(4).trim());continue}if(!n||!r.startsWith("@@ "))continue;let i=/@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(r);if(!i)continue;let o=Math.max(0,Number(i[1])-1),s=i[2]===void 0?1:Number(i[2]);t.push({file:n,startLine:o,endLine:Math.max(o,o+Math.max(s,1)-1)})}return t}function tG(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function IR(e){let t=new Set,n=[];for(let r of e){let i=`${r.file}:${r.startLine}:${r.endLine}`;t.has(i)||(t.add(i),n.push(r))}return n}function nG(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(r=>Tm(e.startLine,e.endLine,r.startLine,r.endLine))}function rG(e,t,n){let r=new Map,i=[],o=wR(e),s=cG(n);for(let a of t){let c=o.get(a.file)??[];if(c.some(d=>Tm(d.startLine,d.endLine,a.startLine,a.endLine)))continue;let l=s.get(a.file)??[],u=lG(l,a);if(u){let d=c.find(m=>m.startLine>=u.startLine&&m.startLine<=u.endLine);if(d){r.set(d.symbolId,d),i.push(Em(a,"ast-widened"));continue}}if(l.length===0){let d=[...c].filter(m=>m.startLine<=a.startLine).sort((m,p)=>p.startLine-m.startLine||m.endLine-p.endLine)[0];if(d){r.set(d.symbolId,d),i.push(Em(a,"nearest-preceding"));continue}}i.push(Em(a,"unattributed"))}return{definitions:[...r.values()],notes:i}}function iG(e,t,n,r){let i=wR(n),o=[],s=[],a=[...new Set(t.map(c=>c.relativePath))];for(let c of a){let l=r.get(c)??[];if(l.length===0)continue;let u=i.get(c)??[];for(let d of l)u.some(m=>Tm(m.startLine,m.endLine,d.startLine,d.endLine))||o.push(d);o.some(d=>d.file===c)&&s.push(...oG(e,c))}return rG(t,o,s)}function oG(e,t){let n=J(e,t);return n?n.rootNode.namedChildren.filter(sG).map(r=>({file:t,startLine:r.startPosition.row,endLine:r.endPosition.row})).filter(r=>r.endLine>=r.startLine):[]}function sG(e){return e.endPosition.row<e.startPosition.row?!1:!new Set(["import_statement","comment"]).has(e.type)}function aG(e){let t=new Map;for(let n of e)t.set(n.symbolId,n);return[...t.values()]}function wR(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath)??[];r.push(n),t.set(n.relativePath,r)}return t}function cG(e){let t=new Map;for(let n of e){let r=t.get(n.file)??[];r.push(n),t.set(n.file,r)}return t}function lG(e,t){return e.filter(n=>n.startLine<=t.startLine&&n.endLine>=t.endLine).sort((n,r)=>n.endLine-n.startLine-(r.endLine-r.startLine))[0]}function Em(e,t){return{file:e.file,startLine:e.startLine,endLine:e.endLine,method:t}}function Tm(e,t,n,r){return e<=r&&n<=t}function uG(e,t,n,r,i,o,s,a,c){let l=Math.max(a,o.size,s.size);if(!yG(t,l))return;let u=T(t.symbol);r.push({symbol:t.symbol,shortName:u,file:t.relativePath,startLine:t.startLine,endLine:t.endLine,fanIn:l});for(let d of c)Im(e,n,i,d,u);for(let d of o)Im(e,n,i,d,u);for(let d of s)Im(e,n,i,d,u)}function SR(e,t,n){try{return{values:n(),status:{tier:e,state:"complete",attemptedSymbols:t}}}catch(r){return{values:new Map,status:{tier:e,state:"failed",attemptedSymbols:t,reason:mG(r)}}}}function dG(e){return["semantic-consumers","source-fallback-consumers"].map(t=>{let n=e.map(o=>o.evidenceTiers?.find(s=>s.tier===t)??{tier:t,state:"failed",attemptedSymbols:0,reason:"isolated diff-impact batch omitted its evidence-tier status"}),r=n.reduce((o,s)=>o+s.attemptedSymbols,0),i=[...new Set(n.filter(o=>o.state==="failed").map(o=>o.reason))];return i.length===0?{tier:t,state:"complete",attemptedSymbols:r}:{tier:t,state:"failed",attemptedSymbols:r,reason:i.join("; ").slice(0,500)}})}function LR(){return[{tier:"semantic-consumers",state:"complete",attemptedSymbols:0},{tier:"source-fallback-consumers",state:"complete",attemptedSymbols:0}]}function mG(e){let n=(e instanceof Error?e.message:String(e)).replaceAll(/\s+/g," ").trim().slice(0,500);return n===""?"evidence provider failed without a reason":n}function pG(e,t){if(t.length===0)return new Map;let n=e.all(`SELECT m.symbol_id, COUNT(DISTINCT c.document_id) AS fan_in
|
|
349
|
-
FROM mentions m
|
|
350
|
-
JOIN chunks c ON m.chunk_id = c.id
|
|
351
|
-
WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
|
|
352
|
-
AND m.role != 1
|
|
353
|
-
GROUP BY m.symbol_id`,...t);return new Map(n.map(r=>[r.symbol_id,r.fan_in]))}function fG(e,t,n){if(t.length===0||n.length===0)return new Map;let r=e.all(`SELECT DISTINCT m.symbol_id, ref_d.relative_path
|
|
354
|
-
FROM mentions m
|
|
355
|
-
JOIN chunks c ON m.chunk_id = c.id
|
|
356
|
-
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
357
|
-
WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
|
|
358
|
-
AND m.role != 1
|
|
359
|
-
AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
|
|
360
|
-
${e.pathExclusionsFor("ref_d")}`,...t,...n),i=new Map;for(let o of r){let s=i.get(o.symbol_id);s||(s=new Set,i.set(o.symbol_id,s)),s.add(o.relative_path)}return i}function Im(e,t,n,r,i){if(e.isIgnored(r)||t.has(r))return;let o=n.get(r);o||(o=new Set,n.set(r,o)),o.add(i)}function gG(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function hG(e){return!(me(e.symbol)||e.parentTypeName!==null&&!Xe(e.symbol))}function yG(e,t){return Xe(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}var bG=5;function SG(e,t={}){let{base:n="HEAD",minContainment:r=.7,minCallees:i=3,minSiteCoverage:o=.4,maxHelpers:s=Number.POSITIVE_INFINITY,limit:a=20,scanLimit:c}=t,l=t.semantic!==!1,u=t.diffPlan??qi(e,{base:n}),d={available:u.note!==wm,base:n,changedFiles:u.changedFiles,helpersChecked:0,skipped:[],findings:[],...u.note?{note:u.note}:{}};if(!d.available||u.changedFiles.length===0)return d;let m=new H(e),p=new Set(u.changedFiles),f=new Map(u.renamedFiles.map(R=>[R.to,R.from]));if(t.baseContentAt&&t.baseContentResultAt)throw new Error("Specify only one of baseContentAt or baseContentResultAt.");let g=t.baseContentResultAt?t.baseContentResultAt:t.baseContentAt?wG(t.baseContentAt):Mm({projectRoot:e.config.projectRoot,base:n,preloadPaths:CR(u)}),h=IG(m,p,f,g);if(h.unavailable)return d.available=!1,d.note=`Base content unavailable: ${h.unavailable.reason}`,d;if(h.definitions.length===0)return d;let b=h.definitions.slice(0,s);h.definitions.length>s&&(d.note=`helper scoring capped at ${s} of ${h.definitions.length} new symbols`);let S=m.calleeMap(b,{semantic:l}),y=b.map(R=>({def:R,callees:Lc((S.get(R.symbolId)??[]).map(E=>E.symbol))})),x=ji(e),v,C=()=>(v??=x.calleeIndex({minCallees:Math.min(3,i),scanLimit:c,semantic:l}),v);for(let{def:R,callees:E}of y){let w=T(R.symbol);if(E.size<i){d.skipped.push({helperShortName:w,helperFile:R.relativePath,reason:`fewer than ${i} meaningful callees \u2014 too small to score`});continue}let I=C(),k=EG(E,I);if(k===0){d.skipped.push({helperShortName:w,helperFile:R.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let D=LG(e,R.symbolId);if(D.length===0){d.skipped.push({helperShortName:w,helperFile:R.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}d.helpersChecked+=1;let F=vG({candidateIndex:I,changed:p,helperCallees:E,helperFile:R.relativePath,helperSymbol:R.symbol,minContainment:r,minSiteCoverage:o,migratedFiles:D});F.length!==0&&(F.sort((L,A)=>PR(A.migrationScope)-PR(L.migrationScope)||A.containment-L.containment||A.siteCoverage-L.siteCoverage||L.file.localeCompare(A.file)),d.findings.push({helperSymbol:R.symbol,helperShortName:w,helperFile:R.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:E.size,specificHelperCalleeCount:k,migratedFiles:D.sort(),leftovers:F.slice(0,bG)}))}return d.findings.sort((R,E)=>(E.leftovers[0]?.containment??0)-(R.leftovers[0]?.containment??0)||R.helperFile.localeCompare(E.helperFile)),d.findings=d.findings.slice(0,a),d}function vG(e){let t=[],n=CG(e.helperSymbol,e.helperFile,e.migratedFiles),r=new Set;for(let i of e.helperCallees)for(let o of e.candidateIndex.candidateIndexesByCallee.get(i)??[])r.add(o);for(let i of r){let o=e.candidateIndex.corpus[i];if(o.symbol===e.helperSymbol||e.changed.has(o.file)||o.callees.has(e.helperSymbol))continue;let s=Sx(e.helperCallees,o.callees);if(s<e.minContainment)continue;let a=[...e.helperCallees].filter(u=>o.callees.has(u)),c=o.callees.size===0?0:a.length/o.callees.size;if(c<e.minSiteCoverage||!a.some(u=>(e.candidateIndex.docFreq.get(u)??0)<=e.candidateIndex.ubiquityThreshold))continue;let l=xG(n,o.symbol,o.file);t.push({symbol:o.symbol,shortName:T(o.symbol),file:o.file,...l,containment:s,siteCoverage:c,uniqueSiteCalleeCount:Math.max(0,o.callees.size-a.length),sharedCallees:a.map(T).sort()})}return t}function PR(e){return e==="same-scope"?2:e==="unknown"?1:0}function CG(e,t,n){let r=new Set([...km(t),...Am(z(e))]);for(let i of n)for(let o of km(i))r.add(o);return r}function xG(e,t,n){let r=new Set([...km(n),...Am(z(t))]);if(e.size===0||r.size===0)return{migrationScope:"unknown",migrationScopeReasons:["insufficient path/name tokens to infer migration scope"]};let i=[...r].filter(o=>e.has(o)).sort();return i.length>0?{migrationScope:"same-scope",migrationScopeReasons:[`shares migration-scope token(s): ${i.slice(0,5).join(", ")}`]}:{migrationScope:"possible-subtype",migrationScopeReasons:["no path/name tokens shared with the helper or already migrated files"]}}var RG=new Set(["app","apps","common","component","components","helper","helpers","index","lib","package","packages","page","pages","route","routes","service","services","shared","spec","src","test","tests","util","utils"]);function km(e){return Am(e.replace(/\.[^.]+$/,""))}function Am(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!RG.has(t))}function EG(e,t){let n=0;for(let r of e)(t.docFreq.get(r)??0)<=t.ubiquityThreshold&&(n+=1);return n}function IG(e,t,n,r){let i=[];for(let o of e.productionCallableDefinitions({files:[...t],requireFunctionLikeSymbol:!0})){if(!t.has(o.relativePath))continue;let s=n.get(o.relativePath)??o.relativePath,a=r(s);if(a.state==="unavailable")return{definitions:[],unavailable:a};(a.state==="absent"||!new RegExp(`\\b${Ce(o.leaf)}\\b`).test(a.content))&&i.push(o)}return{definitions:i}}function wG(e){return t=>{let n=e(t);return n===null?{state:"absent"}:{state:"present",content:n}}}function LG(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
|
|
361
|
-
FROM mentions m
|
|
362
|
-
JOIN chunks c ON m.chunk_id = c.id
|
|
363
|
-
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
364
|
-
WHERE m.symbol_id = ?
|
|
365
|
-
AND m.role != 1
|
|
366
|
-
${e.pathExclusionsFor("ref_d")}`,t).map(r=>r.relative_path)}import{execFileSync as PG}from"child_process";var AR=2e3,Nc=50,DG=64,MG=8,TG=3,kG=2160*60*60,AG=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,FG=3,NG=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,_G=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function OG(e){let t=ge(e,{clearGroups:["whole-project"]});return(n,r,i)=>{let o=i??Fm(n.config.projectRoot);if(!o)return null;let s=t.has(n)?t.get(n,()=>({head:"",value:null})):null;return s&&s.head===o?s.value:(t.invalidate(n),t.get(n,()=>({head:o,value:r(n.config.projectRoot,o)})).value)}}function _c(e){let t=ge(e,{clearGroups:["whole-project"]});return(n,r,i,o)=>{let s=o??Fm(n.config.projectRoot);if(!s)return null;let a=t.has(n)?t.get(n,()=>({head:"",values:new Map})):null;(!a||a.head!==s)&&t.invalidate(n);let c=t.get(n,()=>({head:s,values:new Map}));if(c.values.has(r))return c.values.get(r)??null;let l=i(n.config.projectRoot,s);return c.values.set(r,l),l}}var BG=_c("git-commit-history");function jt(e,t={}){let n=t.historyMode??"bounded",r=t.head;return{capability:i=>$G(e,i,r),commitHistory:()=>ds(e,n,r),fileChurn:()=>UG(e,n,r),changeAmplification:()=>qG(e,n,r),trackedFiles:()=>zG(e,r),fileAddRecords:()=>WG(e,n,r),coChangePairs:(i={})=>ez(e,i,n,r),coChangePairsForFiles:(i,o={})=>_R(e,i,o,n,r),directionalCoChangePairsForFiles:(i,o={})=>tz(e,i,o,n,r)}}function ds(e,t="bounded",n){return BG(e,Gi(t),(r,i)=>jG(r,i,t),n)}function $G(e,t,n){let r=n??Fm(e.config.projectRoot);return r?{slot:t,available:!0,head:r}:{slot:t,available:!1,head:null,reason:"git history is unavailable for this project"}}function Fm(e){try{return sn(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function sn(e,t){return PG("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"})}function jG(e,t,n){let r;try{r=sn(e,["log","--no-merges","--name-only",...Oc(n),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}return{head:t,...Om(r,Nc)}}function HG(e){return AG.test(e.subject)}function UG(e,t,n){let r=ds(e,t,n);if(!r)return null;let i=new Map;for(let o of r.commits){let s=HG(o);for(let a of o.files){let c=i.get(a)??{changes:0,fixChanges:0,lastChangedAt:0};c.changes+=1,s&&(c.fixChanges+=1),o.timestamp>c.lastChangedAt&&(c.lastChangedAt=o.timestamp),i.set(a,c)}}return i}function qG(e,t,n){let r=ds(e,t,n);if(!r||r.commits.length===0)return null;let i=r.commits.map(o=>o.files.length).filter(o=>o>0).sort((o,s)=>o-s);return i.length===0?null:{medianFilesPerCommit:DR(i,.5),p90FilesPerCommit:DR(i,.9),commitsAnalyzed:i.length}}function DR(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var GG=OG("git-tracked-files");function zG(e,t){return GG(e,n=>{try{let r=sn(n,["ls-files"]);return new Set(r.split(`
|
|
367
|
-
`).map(i=>i.trim()).filter(i=>i!==""))}catch{return null}},t)}var KG=_c("git-file-adds"),MR="__git__/file-adds",TR=dt({kind:"git-file-adds",invalidation:$e("git-file-adds"),serialize:YG,deserialize:JG});function FR(e){return jt(e).fileAddRecords()}function WG(e,t,n){let r=Gi(t);return KG(e,r,(i,o)=>VG(e,i,o,t),n)}function VG(e,t,n,r){let i=TR.read(e,kR(r),n);if(i)return i;let o=XG(t,r);return o&&TR.write(e,kR(r),n,o),o}function YG(e){return JSON.stringify([...e.entries()])}function JG(e){if(!e)return null;try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=new Map;for(let r of t){if(!Array.isArray(r)||r.length!==2||typeof r[0]!="string")return null;let i=r[1];if(!i||typeof i.commitsAgo!="number"||!Number.isFinite(i.commitsAgo)||typeof i.addedAt!="number"||!Number.isFinite(i.addedAt))return null;n.set(r[0],{commitsAgo:i.commitsAgo,addedAt:i.addedAt})}return n}catch{return null}}function XG(e,t){let n;try{n=sn(e,["log","--no-merges","--find-renames","--name-status",...Oc(t),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let r=new Map,i=new Map,o=-1;for(let s of n.split("")){if(s.trim()==="")continue;o+=1;let a=s.indexOf(`
|
|
368
|
-
`),c=a>=0?s.slice(0,a):s,[,l]=c.split("\0"),u=Number(l)||0;if(!(a<0))for(let d of s.slice(a+1).split(`
|
|
369
|
-
`)){let m=QG(d);if(!m)continue;if(m.status==="R"&&m.from&&m.to){let f=i.get(m.to)??new Set([m.to]);i.set(m.from,f);continue}if(m.status!=="A"||!m.to)continue;let p={commitsAgo:o,addedAt:u};r.set(m.to,p);for(let f of i.get(m.to)??[])r.set(f,p)}}return r}function QG(e){let t=e.trim().split(" "),n=t[0]??"";if(!n)return null;let r=n[0]??"";if(r==="R"){let o=t[1],s=t[2];return o&&s?{status:r,from:o,to:s}:null}let i=t[1];return i?{status:r,to:i}:null}var NR=_c("git-co-change-pairs"),ZG=_c("git-directional-co-change-pairs");function ez(e,t,n,r){let i=`all\0${Gi(n)}\0${Nm(t)}`,o=NR(e,i,()=>{let s=ds(e,n,r);return s?_m(s,t):null},r);return o&&[...o]}function _R(e,t,n,r,i){if(t.size===0)return[];let o=`files\0${Gi(r)}\0${OR(t)}\0${Nm(n)}`,s=NR(e,o,()=>{let a=ds(e,r,i);return a?_m(a,n,t):null},i);return s&&[...s]}function tz(e,t,n,r,i){if(t.size===0)return[];let o=n.maxFilesPerCommit??Nc;if(t.size>DG)return _R(e,t,n,r,i);let s=`directional\0${Gi(r)}\0${OR(t)}\0${Nm({...n,maxFilesPerCommit:o})}`,a=ZG(e,s,(c,l)=>{let u=nz(c,l,t,o,r);return u?_m(u,n,t):null},i);return a&&[...a]}function Nm(e){let t=e.minTogether??4,n=e.minConfidence??.6,r=e.maxFilesPerCommit??Nc;return`${t}\0${n}\0${r}`}function OR(e){return[...e].sort().join("\0")}function _m(e,t,n){let{minTogether:r=4,minConfidence:i=.6,maxFilesPerCommit:o=Nc}=t,s=new Map,a=new Map,c=e.newestAnalyzedAt??0;for(let d of e.commits){let m=[...new Set(d.files)].sort();if(m.length>o)continue;e.newestAnalyzedAt===void 0&&d.timestamp>c&&(c=d.timestamp);let p=oz(m),f=n===void 0||m.some(g=>n.has(g));for(let g of m)s.set(g,(s.get(g)??0)+1);if(f)for(let g=0;g<m.length;g++)for(let h=g+1;h<m.length;h++){if(n&&!n.has(m[g])&&!n.has(m[h]))continue;let b=`${m[g]}\0${m[h]}`,S=a.get(b)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};S.together+=1,p?S.broadTogether+=1:S.focusedTogether+=1,d.timestamp>S.lastTogetherAt&&(S.lastTogetherAt=d.timestamp),S.timestamps.push(d.timestamp),S.subjects.push(d.subject),a.set(b,S)}}let l=[],u=c-kG;for(let[d,m]of a){let p=m.together;if(p<r)continue;let[f,g]=d.split("\0"),h=s.get(f)??p,b=s.get(g)??p,S=Math.max(p/h,p/b);if(S<i)continue;let y=m.broadTogether/p,x=m.timestamps.filter(v=>v>=u).length;l.push({fileA:f,fileB:g,together:p,confidence:S,changesA:h,changesB:b,focusedTogether:m.focusedTogether,broadTogether:m.broadTogether,broadCommitRatio:y,lastTogetherAt:m.lastTogetherAt,recentTogether:x,commitScope:az(m.broadTogether,p),recency:x>0?"recent":"stale",subjectContext:cz(m.subjects)})}return l.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),l}function nz(e,t,n,r,i){let o;try{o=rz(e,i)}catch{return null}if(o.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:0};let s;try{s=sn(e,["log","--no-merges","--format=%H",...Oc(i),"--",...[...n].sort()])}catch{return null}let a=new Set(o.map(m=>m.hash)),c=s.split(`
|
|
370
|
-
`).map(m=>m.trim()).filter(m=>m!==""&&a.has(m)),l=iz(e,o,r);if(c.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:l};let u;try{u=sn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...c])}catch{return null}let d=Om(u,r);return{head:t,...d,newestAnalyzedAt:l}}function rz(e,t){return sn(e,["log","--no-merges","--format=%H%x00%ct",...Oc(t)]).split(`
|
|
371
|
-
`).map(r=>r.trim()).filter(r=>r!=="").map(r=>{let[i,o]=r.split("\0");return{hash:i??"",timestamp:Number(o)||0}}).filter(r=>r.hash!=="")}function Oc(e){return e==="full"?[]:["-n",String(BR())]}function BR(){return Vn(process.env.SCIP_QUERY_GIT_HISTORY_MAX_COMMITS)??AR}function Gi(e){return e==="full"?"full":`bounded:${BR()}`}function kR(e){let t=Gi(e);return t===`bounded:${AR}`?MR:`${MR}:${t}`}function iz(e,t,n){for(let i=0;i<t.length;i+=20){let o=t.slice(i,i+20),s;try{s=sn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...o.map(c=>c.hash)])}catch{return t[0]?.timestamp??0}let a=Om(s,n);if(a.commits.length>0)return a.commits[0].timestamp}return 0}function Om(e,t){let n=[],r=0;for(let i of e.split("")){if(i.trim()==="")continue;let o=i.indexOf(`
|
|
372
|
-
`),s=o>=0?i.slice(0,o):i,[a,c,l]=s.split("\0");if(!a||!c)continue;let u=o>=0?i.slice(o+1).split(`
|
|
373
|
-
`).map(d=>d.trim()).filter(d=>d!==""):[];if(u.length>t){r+=1;continue}n.push({hash:a,timestamp:Number(c)||0,subject:l??"",files:u})}return{commits:n,skippedBulkCommits:r}}function oz(e){return e.length>=MG?!0:sz(e).size>=TG}function sz(e){let t=new Set;for(let n of e){let r=n.indexOf("/");t.add(r>=0?n.slice(0,r):".")}return t}function az(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function cz(e){let t=new Set,n=[],r=[];for(let i of e){!r.includes(i)&&r.length<FG&&r.push(i);for(let o of lz(i))t.add(o);for(let o of i.match(NG)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:r,externalIssueLabelStatus:"unavailable"}}function lz(e){let t=new Set,n=_G.exec(e)?.[1]?.toLowerCase();return n&&t.add(uz(n)),/\b(?:feat|feature)\b/i.test(e)&&t.add("feature"),/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i.test(e)&&t.add("fix"),/\b(?:docs?|documentation|guide|readme)\b/i.test(e)&&t.add("docs"),/\brefactor(?:ing|ed)?\b/i.test(e)&&t.add("refactor"),/\btests?\b/i.test(e)&&t.add("test"),/\b(?:release|version|v\d+\.\d+)\b/i.test(e)&&t.add("release"),/\bchore\b/i.test(e)&&t.add("chore"),/\bbuild\b/i.test(e)&&t.add("build"),/\bci\b/i.test(e)&&t.add("ci"),/\bperf(?:ormance)?\b/i.test(e)&&t.add("perf"),[...t]}function uz(e){return e==="feat"?"feature":e}var $R=/(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|uv\.lock|poetry\.lock|Pipfile\.lock|bun\.lockb?|\.SRCINFO|CHANGELOG(?:\.[a-z]+)?|.*\.(?:map|tsbuildinfo))$|(?:^|\/)(?:dist|build|out|node_modules|docs\/plans)\//i;function ms(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=jt(e,{historyMode:n.historyMode,...n.head?{head:n.head}:{}}),c=a.commitHistory(),l=t!==void 0,u=a.coChangePairs({minTogether:l?Math.min(r,2):r,minConfidence:l?0:i,maxFilesPerCommit:s});if(!c||!u)return{available:!1,commitsAnalyzed:0,findings:[]};let d=typeof n.scanLimit=="number"?u.slice(0,n.scanLimit):u,m=Me(e),p=GR(e),f=pz(e,m,p),g=n.includeLinked===!0||l,h=[];for(let b of d){if($R.test(b.fileA)||$R.test(b.fileB)||!jR(e,b.fileA)||!jR(e,b.fileB)||l&&!b.fileA.includes(t)&&!b.fileB.includes(t)||!l&&(q(b.fileA)==="test"||q(b.fileB)==="test"||yz(b.fileA,b.fileB)||gz(b.fileA,b.fileB)))continue;let S=f(b.fileA,b.fileB);if(!g&&S)continue;let y=dz(b.fileA,b.fileB),x=mz(b,y,S);if(h.push({...b,structurallyLinked:S,partnerClass:y.partnerClass,partnerClassReasons:y.reasons,...x?{declaredCouplingSuggestion:x}:{}}),h.length>=o)break}return{available:!0,commitsAnalyzed:c.commits.length,findings:h}}function jR(e,t){return Ct(e.config.projectRoot,t)}function dz(e,t){let n=UR(e),r=UR(t),i=[],o=c=>{i.includes(c)||i.push(c)},s=(c,l)=>n.tags.has(c)&&r.tags.has(l)||n.tags.has(l)&&r.tags.has(c);if(s("doc","code"))return o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:i};if(n.tags.has("test")||r.tags.has("test"))return o("one side is classified as a test file"),{partnerClass:"test-code",reasons:i};if(s("schema","script"))return o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:i};if(s("model","view"))return o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:i};if(s("config","code"))return o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:i};let a=Pz(n.tokens,r.tokens).filter(c=>!wz.has(c));return qR(e,t)||a.length>=2?(o(qR(e,t)?"both files live in the same directory":`files share feature tokens: ${a.slice(0,4).join(", ")}`),{partnerClass:"same-feature",reasons:i}):(o("no specific relationship pattern matched"),{partnerClass:"unknown",reasons:i})}function mz(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!Iz.has(t.partnerClass))return;let r=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${Dz(r)}`,files:r,reason:`${t.partnerClass} pair changed together ${e.together}x with ${Math.round(e.confidence*100)}% confidence; declare it if future edits should require both sides.`}}function pz(e,t=Me(e),n=GR(e)){return(r,i)=>bz(t,n,r,i)}var fz=/(?:^|\/)(?:locales|i18n)\//i;function HR(e){return fz.test(e)}function gz(e,t){return HR(e)&&HR(t)?!0:hz(e,t)}function hz(e,t){if(!e.endsWith(".json")||!t.endsWith(".json"))return!1;let n=e.lastIndexOf("/"),r=t.lastIndexOf("/");if(n<0||r<0)return!1;let i=e.slice(0,n),o=t.slice(0,r);if(i===o)return!1;let s=e.slice(n+1),a=t.slice(r+1);if(s!==a)return!1;let c=i.lastIndexOf("/"),l=o.lastIndexOf("/"),u=c>=0?i.slice(0,c):"",d=l>=0?o.slice(0,l):"";return u===d}function yz(e,t){let n=e.lastIndexOf("/"),r=t.lastIndexOf("/");if(e.slice(0,n)!==t.slice(0,r))return!1;let i=e.slice(n+1).split(".")[0],o=t.slice(r+1).split(".")[0];return i!==""&&i===o}function GR(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function bz(e,t,n,r){return e.get(n)?.has(r)===!0||e.get(r)?.has(n)===!0?!0:t.some(i=>i.has(n)&&i.has(r))}var Sz=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,vz=/(?:^|\/)(?:\.[a-z0-9-]+rc|config|configs|settings|\.github)(?:\/|$)|(?:^|\/)(?:package\.json|tsconfig(?:\.[^.]+)?\.json|vite\.config\.[cm]?[jt]s|rollup\.config\.[cm]?[jt]s|eslint\.config\.[cm]?[jt]s)$|\.(?:json|ya?ml|toml|ini|env)$/i,Cz=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,xz=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,Rz=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,Ez=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,Iz=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),wz=new Set(["src","lib","app","apps","packages","frontend","backend","examples","python","typescript","javascript","test","tests","spec","index","main","utils","util","types","type","config","docs","doc","package","requirements","ts","tsx","js","jsx","mjs","cjs","vue","py","md","mdx","json","yaml","yml","toml","txt"]);function UR(e){let t=e.replace(/\\/g,"/"),n=new Set;return Sz.test(t)&&n.add("doc"),vz.test(t)&&n.add("config"),Cz.test(t)&&n.add("schema"),xz.test(t)&&n.add("script"),Rz.test(t)&&n.add("model"),Ez.test(t)&&n.add("view"),q(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:Lz(t)}}function qR(e,t){let n=e.lastIndexOf("/"),r=t.lastIndexOf("/"),i=n>=0?e.slice(0,n):"",o=r>=0?t.slice(0,r):"";return i!==""&&i===o}function Lz(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).map(t=>t.toLowerCase()).filter(t=>t.length>=2)}function Pz(e,t){let n=new Set(t);return[...new Set(e.filter(r=>n.has(r)))].sort()}function Dz(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}function jc(e,t){let n=Mz(e,t)??Tz(e,t)??kz(e,t)??Az(e,t);return Fz(e,n,t)}function Mz(e,t){let n=-1,r=null;for(let i=0;i<=t;i+=1){let o=Bm(e[i]??"");o&&(r===null?(r=o,n=i):o===r&&(r=null,n=-1))}if(r===null||n<0)return null;for(let i=t+1;i<e.length;i+=1)if(Bm(e[i]??"")===r)return{start:n,end:i+1};return{start:n,end:e.length}}function Bm(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function Tz(e,t){if(!Bc(e[t]??""))return null;let n=t;for(;n>0&&Bc(e[n-1]??"");)n-=1;let r=t+1;for(;r<e.length&&Bc(e[r]??"");)r+=1;return{start:n,end:r}}function Bc(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function kz(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if($c(o)!==null)break;if($m(o)!==null)return null;n-=1}if(n<0)return null;let r=$c(e[n]??"");if(r===null)return null;let i=n+1;for(;i<e.length;){let o=e[i]??"",s=$c(o);if(s!==null){if(s<=r)break;i+=1;continue}if($m(o)!==null)break;i+=1}return{start:n,end:i}}function $c(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function Az(e,t){let n=e[t]??"";if(KR(n)||n.trim().length===0)return{start:t,end:t+1};let r=t;for(;r>0&&zR(e[r-1]??"");)r-=1;let i=t+1;for(;i<e.length&&zR(e[i]??"");)i+=1;return{start:r,end:i}}function zR(e){return $m(e)===null}function $m(e){return e.trim().length===0?"blank":KR(e)?"heading":Bm(e)?"fence":Bc(e)?"table":$c(e)!==null?"list":null}function KR(e){return/^#{1,6}\s+/.test(e.trim())}function Fz(e,t,n){let{start:r,end:i}=t;if(i-r>40){let s=Math.floor(20);r=Math.max(r,n-s),i=Math.min(i,r+40),r=Math.max(t.start,i-40)}let o=e.slice(r,i).join(`
|
|
374
|
-
`).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function Wr(e,t){return t.filter(n=>e.includes(n))}var Nz=/<!--\s*scip-query:\s*snapshot\s*-->/i;function WR(e,t){if((e.config.docs?.snapshotPaths??[]).some(i=>lr(i,t)))return!0;let r=W(e,t);return r.length>0&&Nz.test(r)}var VR={classifyCitation:Oz,citationContexts:Bz,citationKindLabel:jz,citationRemediation:Hz,referenceTargets:Uz,hasLineAnchoredCitation:_z};function _z(e){return e.some(t=>(t.lineReferences?.length??0)>0)}function Oz(e){let t=e.join(`
|
|
375
|
-
`).toLowerCase(),n=[],r=Wr(t,[".scipquery","declaredcouplings","suppression","suppressions","config","configuration","json"]);if(r.length>0)return n.push(`configuration/example terms near citation: ${r.join(", ")}`),{citationKind:"configuration-example",actionTier:"support",reasons:n};let i=Wr(t,["accepted","intentional","intentionally","retained","historical"]);if(i.length>0)return n.push(`intentional-record terms near citation: ${i.join(", ")}`),{citationKind:"intentional-record",actionTier:"support",reasons:n};let o=Wr(t,["command","cli","usage","example","run","workflow"]);return o.length>0?(n.push(`guide/reference terms near citation: ${o.join(", ")}`),{citationKind:"guide-reference",actionTier:"signal",reasons:n}):(n.push(e.length>0?"citation appears in prose without config or guide markers":"citation context unavailable"),{citationKind:"behavioral-claim",actionTier:"direct",reasons:n})}function Bz(e,t,n){let r=W(e,t);if(!r&&!Ct(e.config.projectRoot,t))return[];let i=r.split(/\r?\n/),o=n.flatMap($z),s=[];for(let a=0;a<i.length;a+=1){let c=i[a]??"";o.some(l=>c.includes(l))&&s.push(jc(i,a))}return s}function $z(e){let t=e.split("/");return[e,`./${e}`,t.slice(-3).join("/"),t.slice(-2).join("/")].filter((n,r,i)=>n.length>0&&i.indexOf(n)===r)}function jz(e){switch(e){case"behavioral-claim":return"a behavioral doc claim";case"configuration-example":return"a configuration example";case"guide-reference":return"a guide reference";case"intentional-record":return"an intentional record"}}function Hz(e,t){switch(e){case"behavioral-claim":return`Re-read ${t} and update the behavioral claim or citation.`;case"configuration-example":return`Verify the configuration example in ${t} still points at the intended file; update only if the example target changed.`;case"guide-reference":return`Verify the guide reference in ${t} still sends readers to the right implementation or command surface.`;case"intentional-record":return`Verify the intentional citation in ${t} is still meant to name this file.`}}function Uz(e,t,n){let r=kc(n),i=new Set;for(let o of t)qz(e,o,r.get(o)??[])&&i.add(o);return i}function qz(e,t,n){if(!Gz.test(t)||!Ct(e.config.projectRoot,t))return!0;if(n.length===0)return!1;let r=Ye(e.config.projectRoot,t,{inputKind:"changed source file"}).split(/\r?\n/),i=zz(r);for(let o of n)for(let s=o.startLine;s<=o.endLine;s+=1)if((r[s]??"").trim()!==""&&!i.has(s))return!0;return!1}var Gz=/\.(?:[cm]?[jt]sx?)$/i;function zz(e){let t=new Set,n=!1;for(let r=0;r<e.length;r+=1){let i=e[r].trim();!n&&Kz(i)&&(n=!0),n&&(t.add(r),i.endsWith(";")&&(n=!1))}return t}function Kz(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}var YR=dt({kind:"doc-path-evidence",invalidation:$e("doc-path-evidence"),serialize:sK,deserialize:aK}),ps=/\.(?:md|mdx|rst|txt)$/i;function Wz(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var Vz=3,Yz=/([A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6})(?::([1-9][0-9]*))?\b/g;function Jz(e,t={}){let{doc:n,limit:r=20,minCoupling:i=Vz,includeSnapshotExcluded:o=!1}=t,s=eK(e,t.historyMode??"bounded");if(!s)return{available:!1,commitsAnalyzed:0,docsScanned:0,findings:[]};let a=[];for(let c of s.docFiles){if(n!==void 0&&!c.includes(n)||n===void 0&&!tK(e,c)||n!==void 0&&!Ct(e.config.projectRoot,c))continue;let l=WR(e,c);if(l&&!o)continue;let{value:u,estimated:d}=Xz(e,c,s.changeTimes.get(c)),m=Qz(e,c),p=new Map,{resolved:f,broken:g,citations:h}=rK(e,c,s.tracked,s.trackedBySuffix,s.everSeenInHistory),b=new Map(h.map(y=>[y.file,y]));for(let y of f){if(y===c||ps.test(y))continue;let x=(s.changeTimes.get(y)??[]).filter(C=>C>u).length;if(x===0)continue;let v=b.get(y);p.set(y,{file:y,evidence:"reference",coChanges:0,changesSinceDocUpdate:x,...jm("reference",m,v?.contexts),citationContexts:v?.contexts,citedLines:v?.lineReferences})}for(let[y,x]of s.coupling.get(c)??[]){if(x<i||!s.tracked.has(y))continue;let v=(s.changeTimes.get(y)??[]).filter(R=>R>u).length;if(v===0)continue;let C=p.get(y);C?(C.evidence="both",C.coChanges=x,Object.assign(C,jm("both",m,C.citationContexts))):p.set(y,{file:y,evidence:"co-change",coChanges:x,changesSinceDocUpdate:v,...jm("co-change",m)})}if(p.size===0&&g.length===0)continue;let S=[...p.values()].sort((y,x)=>x.changesSinceDocUpdate-y.changesSinceDocUpdate);a.push({doc:c,docLastChangedAt:u,staleness:S.reduce((y,x)=>y+x.changesSinceDocUpdate,0)+g.length*10,subjects:S.slice(0,8),brokenReferences:g,...l?{snapshotExcluded:!0}:{},...d?{docLastChangedAtEstimated:!0}:{}})}return a.sort((c,l)=>l.staleness-c.staleness),{available:!0,commitsAnalyzed:s.historyCommitCount,docsScanned:s.docFiles.length,findings:a.slice(0,r)}}function Xz(e,t,n){if(n&&n.length>0)return{value:Math.max(...n),estimated:!1};try{return{value:Math.floor(Ps(e.config.projectRoot,t).mtimeMs/1e3),estimated:!0}}catch(r){if(Ct(e.config.projectRoot,t))throw r;return{value:0,estimated:!1}}}function Qz(e,t){let n=W(e,t).slice(0,6e3);if(!n)return{docIntent:"unknown",reasons:["doc text unavailable"]};let r=`${t}
|
|
376
|
-
${n}`.toLowerCase(),i=Wr(r,["historical note","historical record","history note","retrospective","postmortem","post-mortem","archived","archive","previously","legacy","recorded","record of","snapshot","as of","migration note","decision record"]);if(i.length>0)return{docIntent:"historical-note",reasons:[`historical-note terms: ${i.join(", ")}`]};let o=Wr(r,["current","standard","standards","must","should","policy","guide","guidance","workflow","contract","invariant","source of truth"]);return o.length>0?{docIntent:"current-guidance",reasons:[`current-guidance terms: ${o.join(", ")}`]}:{docIntent:"unknown",reasons:["no current-guidance or historical-note markers found"]}}function jm(e,t,n=[]){let r=e==="co-change"||n.length===0?null:VR.classifyCitation(n);return{actionTier:Zz(e,t.docIntent,r?.actionTier),docIntent:t.docIntent,docIntentReasons:t.reasons,...r?{citationKind:r.citationKind,citationKindReasons:r.reasons}:{}}}function Zz(e,t,n){return t==="historical-note"?"support":n||(e==="co-change"?"signal":"direct")}function eK(e,t){let n=jt(e,{historyMode:t}),r=n.commitHistory();if(!r)return null;let i=n.trackedFiles()??new Set,o=new Map,s=new Map,a=new Set;for(let c of r.commits){let l=[...new Set(c.files)],u=l.filter(m=>ps.test(m)),d=l.filter(m=>!ps.test(m));for(let m of l){a.add(m);let p=o.get(m)??[];p.push(c.timestamp),o.set(m,p)}for(let m of u){let p=s.get(m);p||(p=new Map,s.set(m,p));for(let f of d)p.set(f,(p.get(f)??0)+1)}}return{changeTimes:o,coupling:s,docFiles:[...i].filter(c=>ps.test(c)),everSeenInHistory:a,historyCommitCount:r.commits.length,tracked:i,trackedBySuffix:nK(i)}}function tK(e,t){return ps.test(t)&&!Wz(t)&&Ct(e.config.projectRoot,t)}function nK(e){let t=new Map;for(let n of e){let r=n.split("/");for(let i of[2,3]){if(r.length<i)continue;let o=r.slice(-i).join("/"),s=t.get(o)??[];s.push(n),t.set(o,s)}}return t}function rK(e,t,n,r,i){let o=new Set,s=new Set,a=iK(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let c=a.candidates,l=a.contextsByCandidate,u=a.lineReferencesByCandidate,d=new Map,m=new Map,p=(f,g)=>{let h=l.get(g);if(h&&h.length>0){let S=d.get(f)??[];S.push(...h),d.set(f,JR(S).slice(0,3))}let b=u.get(g);b&&b.length>0&&m.set(f,Hm([...m.get(f)??[],...b]))};for(let f of c){if(n.has(f)){o.add(f),p(f,f);continue}let g=r.get(f);if(g&&g.length===1){o.add(g[0]),p(g[0],f);continue}g&&g.length>1||i.has(f)&&s.add(f)}return{resolved:o,broken:[...s],citations:[...d].map(([f,g])=>({file:f,contexts:g,lineReferences:m.get(f)}))}}function iK(e,t,n){let r=n;if(r===void 0&&(r=W(e,t),!r&&!Ct(e.config.projectRoot,t)))return null;let i=Rt(e,t,r),o=YR.read(e,t,i);if(o)return o;let s=oK(r);return YR.write(e,t,i,s),s}function oK(e){let t=e.split(/\r?\n/),n=new Set,r=new Map,i=new Map;for(let o=0;o<t.length;o+=1){let s=t[o]??"";for(let a of s.matchAll(Yz)){let c=(a[1]??"").replace(/^\.?\//,"");if(c.length===0)continue;n.add(c);let l=a[2]?Number(a[2]):null;l!==null&&Number.isSafeInteger(l)&&i.set(c,Hm([...i.get(c)??[],l]));let u=jc(t,o);if(u.length===0)continue;let d=r.get(c)??[];d.push(u),r.set(c,JR(d).slice(0,3))}}return{candidates:[...n],contextsByCandidate:r,lineReferencesByCandidate:i}}function sK(e){let t={candidates:e.candidates,contextsByCandidate:[...e.contextsByCandidate.entries()],lineReferencesByCandidate:[...e.lineReferencesByCandidate.entries()]};return JSON.stringify(t)}function aK(e){try{let t=JSON.parse(e);if(!of(t))return null;let n=Yi(t.candidates),r=lK(t.contextsByCandidate),i=cK(t.lineReferencesByCandidate);return!n||!r?null:{candidates:n,contextsByCandidate:new Map(r),lineReferencesByCandidate:new Map(i??[])}}catch{return null}}function cK(e){if(e===void 0)return[];if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||!Array.isArray(n[1]))return null;let r=[];for(let i of n[1]){if(typeof i!="number"||!Number.isSafeInteger(i))return null;r.push(i)}t.push([n[0],Hm(r)])}return t}function lK(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string")return null;let r=Yi(n[1]);if(!r)return null;t.push([n[0],r])}return t}function JR(e){let t=[];for(let n of new Set(e))t.some(r=>uK(r,n))||t.push(n);return t}function Hm(e){return[...new Set(e)].sort((t,n)=>t-n)}function uK(e,t){if(e===t)return!0;let n=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),r=t.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),i=Math.min(n.length,r.length);if(i===0)return!1;if(i<3)return e.includes(t)||t.includes(e);let o=new Set(r),s=n.filter(a=>o.has(a)).length;return s>=3&&s/i>=.6}import{createHash as dK}from"crypto";var mK=3;function fs(e,t={}){let{scope:n,maxLoc:r=15,minLoc:i=mK,limit:o,scanLimit:s}=t,a=FR(e),c=pK(e,{scope:n,maxLoc:r,scanLimit:s}).map(u=>fK(e,u,a,i)).filter(u=>u!==null),l=ZR(c);return o?l.slice(0,o):l}function QR(e){let t=an(e);return pn(t).replace(/\s+/g,"")}function ZR(e){let t=new Map;for(let r of e){if(r.normalizedBody.length<8)continue;let i=hK(r.normalizedBody),o=t.get(i)??[];o.push(r),t.set(i,o)}let n=[];for(let[r,i]of t){let o=new Set(i.map(a=>a.file));if(i.length<2||o.size<2)continue;let s=[...i].sort(yK).map(({normalizedBody:a,...c})=>c);n.push({hash:r,canonical:s[0],functions:s})}return n.sort((r,i)=>{let o=i.functions.length-r.functions.length;if(o!==0)return o;let s=XR(i)-XR(r);return s!==0?s:r.canonical.file.localeCompare(i.canonical.file)}),n}function pK(e,t){let n=Le(e,{scope:t.scope}).filter(r=>r.isFunctionLike&&!e.isIgnored(r.relativePath)).filter(r=>!Fs(e,r.relativePath,r.startLine,"similar")).filter(r=>ee(r)<=t.maxLoc);return n.sort((r,i)=>ee(i)-ee(r)||r.relativePath.localeCompare(i.relativePath)),he(n,t.scanLimit)}function fK(e,t,n,r){let i=Ht(e,t);if(!i||gK(i)<r)return null;let o=Um(e,t);return o?{symbol:t.symbol,shortName:T(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:ee(t),ageCommits:n?.get(t.relativePath)?.commitsAgo??null,normalizedBody:o}:null}function Um(e,t){let n=Ht(e,t);return n&&QR(n)||null}function Ht(e,t){let n=V(e,t.relativePath);return n.length===0?null:n.slice(t.startLine,t.endLine+1).join(`
|
|
377
|
-
`)}function an(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(t>=0&&n>t)return e.slice(t+1,n);let r=e.indexOf("=>");return r>=0?e.slice(r+2).replace(/;+\s*$/,""):e}function gK(e){return an(e).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0).length}function hK(e){return dK("sha256").update(e).digest("hex").slice(0,16)}function yK(e,t){let n=e.ageCommits??-1;return(t.ageCommits??-1)-n||e.file.localeCompare(t.file)||e.startLine-t.startLine}function XR(e){return e.functions.reduce((t,n)=>t+n.loc,0)}var bK=new Set(Kt());function SK(e,t={}){let{includeHomonyms:n=!1,limit:r}=t,i=Hc(e,t).filter(o=>o.relationship==="divergent"||n&&o.relationship==="homonym");return r?i.slice(0,r):i}function Hc(e,t={}){let{scope:n,minSimilarity:r=.3,scanLimit:i}=t,o=xK(e,{scope:n,scanLimit:i});return nE(o,{minSimilarity:r,isDelegatePair:GK(e)}).filter(s=>!s.members.some(a=>Fs(e,a.file,a.startLine,"twin")))}function nE(e,t={}){let n=t.minSimilarity??.3,r=t.isDelegatePair,i=e.filter(l=>!lE(l.leaf)&&!AK(l.leaf)&&q(l.file)!=="test"&&!je(l.symbol)&&!iE(l.symbol)&&!oE(l.symbol,l.leaf)),{recordsByLeaf:o,recordOrder:s}=N("twin-drift.group-by-leaf",()=>vK(i),()=>({records:i.length})),a=N("twin-drift.cluster-leaf-names",()=>rE([...o.keys()]),()=>({leaves:o.size}));return N("twin-drift.compare-clusters",()=>{let l=[];for(let u of a){let d=CK(u,o,s);if(d.length<2||new Set(d.map(S=>S.file)).size<2)continue;let m=null,p=!1,f=!1,g=new Set;for(let S=0;S<d.length;S+=1)for(let y=S+1;y<d.length;y+=1){let x=d[S],v=d[y];if(x.file===v.file||!OK(x,v)||r?.(x,v,d)||r?.(v,x,d))continue;if(p=!0,g.add(x.symbol),g.add(v.symbol),x.normalizedBody===v.normalizedBody){f=!0;continue}let C=DK(x.tokens,v.tokens);(!m||C>m.similarity)&&(m={a:x,b:v,similarity:C})}if(!p)continue;let h=d.filter(S=>g.has(S.symbol)).sort((S,y)=>S.file.localeCompare(y.file)||S.startLine-y.startLine).map(PK);if(!m){l.push({leaf:tE(u),relationship:f?"identical":"homonym",maxDivergence:0,members:h});continue}let b=m.similarity>=n?"divergent":"homonym";l.push({leaf:tE(u),relationship:b,maxDivergence:Math.round((1-m.similarity)*1e3)/1e3,members:h,...b==="divergent"?{firstDivergentTokens:MK(m.a.tokens,m.b.tokens)}:{}})}return l},()=>({clusters:a.length,records:i.length})).sort((l,u)=>u.members.length-l.members.length||u.maxDivergence-l.maxDivergence||l.leaf.localeCompare(u.leaf))}function vK(e){let t=new Map,n=new Map;for(let[r,i]of e.entries()){let o=t.get(i.leaf)??[];o.push(i),t.set(i.leaf,o),n.set(i,r)}return{recordsByLeaf:t,recordOrder:n}}function CK(e,t,n){let r=[...e].flatMap(i=>t.get(i)??[]);return e.size>1&&r.sort((i,o)=>(n.get(i)??0)-(n.get(o)??0)),r}function xK(e,t){let n=N("twin-drift.load-definitions",()=>Le(e,{scope:t.scope}).filter(o=>RK(o)&&!e.isIgnored(o.relativePath)).filter(o=>!Ei(o.relativePath)));N("twin-drift.sort-definitions",()=>n.sort((o,s)=>o.relativePath.localeCompare(s.relativePath)||o.startLine-s.startLine),()=>({definitions:n.length}));let r=he(n,t.scanLimit),i=N("twin-drift.select-candidates",()=>EK(r),()=>({scanned:r.length}));return N("twin-drift.build-records",()=>{let o=[];for(let s of i){let a=IK(e,s);a&&o.push(a)}return o},()=>({candidates:i.length,scanned:r.length}))}function RK(e){return e.isFunctionLike?e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&bK.has(e.kind):!0:!1}function EK(e){let t=e.filter(o=>o.leaf&&!lE(o.leaf)&&!je(o.symbol)&&!iE(o.symbol)&&!oE(o.symbol,o.leaf)),n=new Map;for(let o of t){let s=n.get(o.leaf)??[];s.push(o),n.set(o.leaf,s)}let r=rE([...n.keys()]),i=new Set;for(let o of r){let s=[...o].flatMap(a=>n.get(a)??[]);if(!(s.length<2)&&!(new Set(s.map(a=>a.relativePath)).size<2)&&!s.every(a=>q(a.relativePath)==="test"))for(let a of s)i.add(a)}return e.filter(o=>i.has(o))}function IK(e,t){if(!t.leaf)return null;let n=Ht(e,t);if(!n||!Xe(t.symbol)&&!wK(n,t.leaf))return null;let r=pn(an(n)),i=r.replace(/\s+/g,"");if(!i||i.length<8)return null;let o=r.match(LK)??[];return o.length===0?null:{leaf:t.leaf,symbol:t.symbol,shortName:T(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:ee(t),normalizedBody:i,tokens:o,isThinForwarder:aE(r)}}function wK(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\b(?:const|let|var)\\s+${n}(?:\\s*:[^=]+)?\\s*=\\s*(?:async\\s*)?(?:\\([^)]*\\)|[A-Za-z_$][\\w$]*)\\s*=>`,"s").test(e)}var LK=/[A-Za-z_$][A-Za-z0-9_$]*|\d+(?:\.\d+)?|[^\sA-Za-z0-9_$]/g;function PK(e){return{symbol:e.symbol,shortName:e.shortName,file:e.file,startLine:e.startLine,endLine:e.endLine,loc:e.loc}}function DK(e,t){let n=new Set(e),r=new Set(t);if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let i=0;for(let s of n)r.has(s)&&(i+=1);let o=n.size+r.size-i;return o===0?0:i/o}function MK(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;let i=e.slice(r,r+6).join(" "),o=t.slice(r,r+6).join(" ");return!i&&!o?"(bodies differ only in trailing length)":`A: ${i||"(end)"} | B: ${o||"(end)"}`}function rE(e){let t=new Map;for(let s of e)t.set(s,s);let n=s=>{let a=s;for(;t.get(a)!==a;)a=t.get(a);let c=s;for(;t.get(c)!==a;){let l=t.get(c);t.set(c,a),c=l}return a},r=(s,a)=>{let c=n(s),l=n(a);c!==l&&t.set(c,l)},i=new Map;for(let s of e){let a=s.slice(0,2).toLowerCase(),c=i.get(a)??[];c.push(s),i.set(a,c)}for(let s of i.values())for(let a=0;a<s.length;a+=1)for(let c=a+1;c<s.length;c+=1)TK(s[a],s[c])&&r(s[a],s[c]);let o=new Map;for(let s of e){let a=n(s),c=o.get(a)??new Set;c.add(s),o.set(a,c)}return[...o.values()]}function TK(e,t){return e===t||e.toLowerCase()===t.toLowerCase()?!0:e.length<8||t.length<8||Math.abs(e.length-t.length)>2||kK(e.toLowerCase(),t.toLowerCase())/Math.max(e.length,t.length)<.8?!1:BK(e.toLowerCase(),t.toLowerCase(),2)}function kK(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;return r}function AK(e){return/^[A-Z][A-Z0-9_]*$/.test(e)||/^__[^_].*__$/.test(e)||FK.has(e.toLowerCase())}var FK=new Set(["main","row"]),NK=new Set(["app","component","components","feature","features","impl","index","lib","route","routes","shared","src","tsx","typescript","ui"]);function iE(e){return e.startsWith("rust-analyzer ")&&/\/(?:tests?|benches?)\//.test(e)}var _K=new Set(["default","new","reset"]);function oE(e,t){return e.startsWith("rust-analyzer ")&&_K.has(t.toLowerCase())}function OK(e,t){if(e.leaf.toLowerCase()!==t.leaf.toLowerCase()||e.leaf.length>4)return!0;let n=eE(e);return[...eE(t)].some(r=>n.has(r))}function eE(e){let t=e.leaf.toLowerCase();return new Set(`${e.file}/${e.shortName}`.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(n=>n.length>2&&n!==t&&!NK.has(n)))}function BK(e,t,n){if(Math.abs(e.length-t.length)>n)return!1;let r=Array.from({length:t.length+1},(i,o)=>o);for(let i=1;i<=e.length;i+=1){let o=[i],s=o[0];for(let a=1;a<=t.length;a+=1){let c=e[i-1]===t[a-1]?0:1,l=Math.min(r[a]+1,o[a-1]+1,r[a-1]+c);o.push(l),s=Math.min(s,l)}if(s>n)return!1;r=o}return r[t.length]<=n}function sE(e){return aE(pn(an(e)))}function aE(e){let t=e.trim();if(!t||$K.test(t))return!1;let n=UK(t);return n.length===0||n.length>2?!1:HK(n[n.length-1])}var $K=/\b(?:if|else|for|while|switch|try|catch|do)\b/,jK=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^[\]]*\])*\((?:[^()]|\([^()]*\))*\)$/;function HK(e){let t=e.trim().replace(/^return\s+/,"").replace(/^await\s+/,"").replace(/;\s*$/,"").trim();return jK.test(t)}function UK(e){let t=[],n=0,r="";for(let i of e){if(i==="("||i==="["||i==="{"?n+=1:(i===")"||i==="]"||i==="}")&&(n=Math.max(0,n-1)),i===";"&&n===0){t.push(r),r="";continue}r+=i}return r.trim()&&t.push(r),t.map(i=>i.trim()).filter(i=>i.length>0)}var qK=3;function GK(e){let t=new Map;return(n,r,i)=>{if(!n.isThinForwarder)return!1;let o=`${n.symbol}\0${r.symbol}`,s=t.get(o);if(s!==void 0)return s;let a=cE(e,n,r,i,qK,new Set);return t.set(o,a),a}}function cE(e,t,n,r,i,o){if(i<=0||o.has(t.symbol)||(o.add(t.symbol),(Gt(e,t.file)??[]).filter(c=>c.line>=t.startLine&&c.line<=t.endLine&&c.calleeLeaf===n.leaf).length===0))return!1;let a=new Set(ae(e,t.file).filter(c=>c.sourcePath&&(c.kind!=="namespace"||c.usedMembers.includes(n.leaf))).map(c=>c.sourcePath));if([...a].some(c=>Fe(c,n.file)))return!0;for(let c of r)if(!(c.symbol===t.symbol||c.symbol===n.symbol||!c.isThinForwarder)&&[...a].some(l=>Fe(l,c.file))&&cE(e,c,n,r,i-1,o))return!0;return!1}function lE(e){return e.startsWith("<")&&e.endsWith(">")}function tE(e){return[...e].sort()[0]}import{dirname as oW,isAbsolute as sW,relative as aW,resolve as cW}from"path";import{basename as uE,extname as dE}from"path";function Uc(e,t,n,r,i,o){let s=new Set;KK(e,t,n,r)&&s.add(i);for(let a of o)a.value&&zK(s,a.label,a.value);return[...s].slice(0,6)}function zK(e,t,n){let r=WK(n);t.endsWith("name")&&VK(r)&&e.add(`${t} has type-guard boundary shape`);for(let i of r){let o=YK.get(i);o&&e.add(`${t} has ${o} term: ${i}`)}}function KK(e,t,n,r){if(n<=0)return!1;let i=V(e,t);if(i.length===0)return!1;for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(i[o]??"").trim();if(s!==""){if(ks(s)===r)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function WK(e){return e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function VK(e){return e.some(t=>JK.has(t))&&e.some(t=>XK.has(t))}var YK=new Map([["access","access policy"],["accessible","access policy"],["adapter","adapter"],["adapters","adapter"],["allow","access policy"],["allowed","access policy"],["animation","animation calculation"],["api","api surface"],["apply","settings/application"],["audit","side-effect boundary"],["auth","authorization"],["authorize","authorization"],["audio","audio side-effect"],["can","access policy"],["capabilities","capability boundary"],["capability","capability boundary"],["boundary","boundary"],["begin","lifecycle"],["bridge","bridge"],["bridges","bridge"],["cache","state cache"],["chase","gameplay action"],["command","command boundary"],["context","context policy"],["cooldown","temporal state"],["cooldowns","temporal state"],["controller","controller"],["controllers","controller"],["diagnostic","diagnostics"],["diagnostics","diagnostics"],["effect","side-effect boundary"],["effects","side-effect boundary"],["energy","gameplay calculation"],["expired","temporal state"],["facade","facade"],["facades","facade"],["fire","gameplay action"],["gateway","gateway"],["gateways","gateway"],["guard","guard"],["guards","guard"],["haptic","haptic side-effect"],["haptics","haptic side-effect"],["head","sequence boundary"],["history","state history"],["input","input boundary"],["jump","gameplay action"],["keyboard","input boundary"],["log","side-effect boundary"],["logger","side-effect boundary"],["lock","coordination boundary"],["middleware","middleware"],["multiplier","gameplay calculation"],["mute","audio side-effect"],["normalize","normalization"],["normalise","normalization"],["normalizer","normalization"],["oscillate","animation calculation"],["oscillation","animation calculation"],["overlap","collision predicate"],["performance","diagnostics"],["permission","access policy"],["permissions","access policy"],["policy","policy"],["pool","state pool"],["pooled","state pool"],["pools","state pool"],["predict","prediction"],["presenter","presenter"],["presenters","presenter"],["projectile","gameplay entity"],["provider","provider boundary"],["providers","provider boundary"],["public","public surface"],["quality","settings/application"],["rate","calculation"],["register","registry"],["registry","registry"],["relay","relay"],["relays","relay"],["reseed","state lifecycle"],["reset","state lifecycle"],["respond","response boundary"],["response","response boundary"],["resolve","resolution"],["resolver","resolution"],["route","route boundary"],["routes","route boundary"],["run","lifecycle"],["sample","diagnostics"],["score","gameplay calculation"],["scope","scope policy"],["scroll","position state"],["scrolled","position state"],["seed","state lifecycle"],["seeded","state lifecycle"],["segment","segment boundary"],["segments","segment boundary"],["setting","settings/application"],["settings","settings/application"],["spawn","gameplay lifecycle"],["spawning","gameplay lifecycle"],["speed","gameplay calculation"],["surface","public surface"],["tail","sequence boundary"],["tick","temporal state"],["transaction","transaction"],["transactional","transaction"],["transform","transformation"],["transformer","transformation"],["translate","translation"],["translator","translation"],["try","fallible action"],["validate","validation"],["validation","validation"],["validator","validation"],["visual","diagnostics"],["window","settings/application"],["socket","transport boundary"],["websocket","transport boundary"]]),JK=new Set(["can","has","is","should"]),XK=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function gs(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new H(e);return At({candidates:()=>iW(e,s,n,r),orderCandidates:za,scanLimit:o,profile:{name:"passthrough-candidates"},prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>QK(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:i})}function QK(e,t,n){let r=rW(n);if(r.size!==1||!uf(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0],o=ZK(e,t,i),s=tW(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:T(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:ee(t),forwardsTo:i.symbol,forwardsToShort:T(i.symbol),forwardsToFile:i.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:eW(a,o,s)}}function ZK(e,t,n){return Uc(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:T(t.symbol)},{label:"callee name",value:T(n.symbol)},{label:"passthrough module",value:uE(t.relativePath,dE(t.relativePath))},{label:"callee module",value:uE(n.file,dE(n.file))}])}function eW(e,t,n){if(e==="signal"){if(n.length>0)return`Review the public API before inlining; public-facade evidence: ${n.slice(0,2).join("; ")}.`;let r=t.filter(nW);return r.length>0?`Review the public API before inlining; public-surface evidence: ${r.slice(0,2).join("; ")}.`:`Review the boundary before inlining; boundary evidence: ${t.slice(0,2).join("; ")}.`}return"Inline or remove this passthrough unless an external API or runtime registration depends on the forwarding name."}function tW(e,t){return pt(e,t)?Cn(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:Te(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function nW(e){return e.includes("public surface")}function rW(e){let t=e.some(r=>Se(r.symbol))?e.filter(r=>Se(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function iW(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:3,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0}).filter(i=>!Ns(e,i))}var lW=new Set(Kt());function uW(e,t){return`tests/generated/twin-ab/${mE(e)}-vs-${mE(t)}.test.ts`}function mE(e){return(e.split(/[/#]/).pop()||e).replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"symbol"}function dW(e,t,n,r){let{refA:i,refB:o,outFile:s}=typeof t=="string"?{refA:t,refB:n,outFile:r}:t;if(typeof i!="string"||typeof o!="string"||typeof s!="string")throw new TypeError("twinAb requires refA, refB, and outFile.");if(!sW(s))throw new TypeError("twinAb outFile must be an absolute path.");let a=pE(e,i);if(!a.ok)return a;let c=pE(e,o);if(!c.ok)return c;let l=a.symbol.paramCount===null||c.symbol.paramCount===null?null:a.symbol.paramCount===c.symbol.paramCount,u=pW(a.symbol,c.symbol,e.config.projectRoot,s,l);return{ok:!0,a:a.symbol,b:c.symbol,signatureCompatible:l,testSource:u}}function pE(e,t){let r=Qe(e,t).match;if(!r)return{ok:!1,reason:`${t} does not resolve to an indexed symbol.`};let o=e.get("SELECT kind FROM global_symbols WHERE id = ?",r.symbolId)?.kind??null;if(!(o!==null?lW.has(o):Se(r.symbol)))return{ok:!1,reason:`${t} resolves to ${T(r.symbol)}${o!==null?` with SCIP kind ${ro(o)}`:""} \u2014 twin-ab compares call outputs, so both referents must be functions or methods.`};if(!pt(e,r))return{ok:!1,reason:`${t} (${T(r.symbol)} at ${r.relativePath}:${r.startLine+1}) is not exported \u2014 twin-ab needs an importable named binding for both twins.`};let a=e.get("SELECT documentation FROM global_symbols WHERE id = ?",r.symbolId),c=oi(si(a?.documentation??null));return{ok:!0,symbol:{ref:t,symbol:r.symbol,shortName:z(r.symbol)||T(r.symbol),file:r.relativePath,startLine:r.startLine,signature:c,paramCount:c?mW(c):null}}}function mW(e){let t=e.indexOf("(");if(t===-1)return null;let n=0,r=-1;for(let a=t;a<e.length;a+=1){let c=e[a];if(c==="(")n+=1;else if(c===")"&&(n-=1,n===0)){r=a;break}}if(r===-1)return null;let i=e.slice(t+1,r).trim();if(!i)return 0;let o=1,s=0;for(let a of i)a==="("||a==="["||a==="{"?s+=1:a===")"||a==="]"||a==="}"?s=Math.max(0,s-1):a===","&&s===0&&(o+=1);return o}function fE(e,t,n){let r=oW(t),i=cW(e,n),s=aW(r,i).replace(/\\/g,"/").replace(/\.tsx?$/,".js");return s.startsWith(".")?s:`./${s}`}function pW(e,t,n,r,i){let o=fE(n,r,e.file),s=fE(n,r,t.file),a=i===null?"Signature comparison: unknown (one or both signatures unavailable in the index) \u2014 check by hand.":i?"Signature comparison: param counts match.":"Signature comparison: param counts DIFFER \u2014 twins may not be directly comparable; check by hand.";return`/**
|
|
378
|
-
* Generated by 'scip-query twin-ab'. Cleanup integrity scenario.
|
|
379
|
-
* ("cross-examine same-concept twins"): where one concept is computed in
|
|
380
|
-
* more than one place, feed both the same input and require the same
|
|
381
|
-
* answer. Disagreement between twins means at least one is wrong \u2014
|
|
382
|
-
* determine which before consolidating.
|
|
383
|
-
*
|
|
384
|
-
* Twin A: ${e.shortName} (${e.file}:${e.startLine+1})
|
|
385
|
-
* ${e.signature??"(signature unavailable)"}
|
|
386
|
-
* Twin B: ${t.shortName} (${t.file}:${t.startLine+1})
|
|
387
|
-
* ${t.signature??"(signature unavailable)"}
|
|
388
|
-
* ${a}
|
|
389
|
-
*
|
|
390
|
-
* Fill in the TODO input table below with inputs both twins should agree
|
|
391
|
-
* on, then run this file with vitest.
|
|
392
|
-
*/
|
|
393
|
-
import { describe, expect, it } from 'vitest';
|
|
394
|
-
import { ${e.shortName} as twinA } from '${o}';
|
|
395
|
-
import { ${t.shortName} as twinB } from '${s}';
|
|
396
|
-
|
|
397
|
-
// TODO: fill in shared inputs both twins should agree on \u2014 one arg array per call.
|
|
398
|
-
const inputs: any[][] = [
|
|
399
|
-
// [/* arg1, arg2, ... */],
|
|
400
|
-
];
|
|
401
|
-
|
|
402
|
-
// Cast to a variadic signature so the input table can hold any arg shape \u2014
|
|
403
|
-
// the real twins have fixed, non-rest parameter lists, and TS rejects
|
|
404
|
-
// spreading a generic args array into those (TS2556) even when the array
|
|
405
|
-
// itself is 'any'; casting the callee's signature, not the args, satisfies
|
|
406
|
-
// the checker without weakening the twins' real exported types elsewhere.
|
|
407
|
-
const callA = twinA as (...callArgs: any[]) => any;
|
|
408
|
-
const callB = twinB as (...callArgs: any[]) => any;
|
|
409
|
-
|
|
410
|
-
describe.skipIf(inputs.length === 0)('twin-ab: ${e.shortName} vs ${t.shortName}', () => {
|
|
411
|
-
it.each(inputs)('agrees on input %#', (...args) => {
|
|
412
|
-
expect(callA(...args)).toEqual(callB(...args));
|
|
413
|
-
});
|
|
414
|
-
});
|
|
415
|
-
`}var gE={caller:3,"entry-surface":2,rooted:1},fW=/not\s*yet\s*implement|not\s*implement|unimplement|\bnyi\b|\btodo\b|\bstub\b|not\s*supported|coming\s*soon/i,gW=/^throw\s+new\s+[\w.]*Error\s*\(([\s\S]*)\)\s*;?$/,hW=/^return(\s+(null|undefined|false|0|''|""|``|\[\]|\{\}))?\s*;?$/,yW=/\/\/\s*TODO\b|\/\*\s*TODO\b/i,bW=/(?:=>|\))\s*(?::\s*[^{;=]+)?\s*\{\s*\}\s*;?\s*$/;function SW(e,t={}){let{scope:n,limit:r=30,scanLimit:i,semantic:o=!0}=t,s=new H(e),a=he(s.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),c=[];for(let p of a){let f=CW(e,p);f&&c.push(f)}if(c.length===0)return[];let l=IW(e,c,a),u=c.filter(p=>!l.has(p.def.symbol));if(u.length===0)return[];let d=Dn(e,s).forDefinitions(u.map(p=>p.def),{semantic:o}),m=[];for(let p of u){let g=d.get(p.def.symbolId)?.realConsumers.length??0,h=vW(e,p.def,g);h&&m.push({symbol:p.def.symbol,shortName:T(p.def.symbol),file:p.def.relativePath,startLine:p.def.startLine,endLine:p.def.endLine,loc:ee(p.def),stubKind:p.stubKind,reachability:h,callerFanIn:g,stubText:p.stubText})}return m.sort((p,f)=>gE[f.reachability]-gE[p.reachability]||f.callerFanIn-p.callerFanIn||p.file.localeCompare(f.file)||p.startLine-f.startLine),r?m.slice(0,r):m}function vW(e,t,n){return n>0?"caller":Te(e,t.symbol,t.relativePath)?"rooted":Ue(e,t.relativePath)?"entry-surface":null}function CW(e,t){let n=Ht(e,t);if(!n)return null;let r=an(n),i=r.trim();if(i==="")return!EW(n)||!pt(e,t)?null:{def:t,stubKind:"empty-body",stubText:"(empty body)"};let o=Xi(r),s=pn(r),a=xW(o,s);if(a.length!==1)return null;let c=a[0];return RW(c)?{def:t,stubKind:"throw-stub",stubText:c.trim()}:yW.test(r)&&hW.test(c.trim())?{def:t,stubKind:"todo-return-default",stubText:i}:null}function xW(e,t){let n=[],r=0,i="";for(let o=0;o<t.length;o+=1){let s=t[o];if(s==="("||s==="["||s==="{"?r+=1:(s===")"||s==="]"||s==="}")&&(r=Math.max(0,r-1)),s===";"&&r===0){n.push(i),i="";continue}i+=e[o]??""}return i.trim()&&n.push(i),n.map(o=>o.trim()).filter(o=>o.length>0)}function RW(e){let t=gW.exec(e.trim());return t?fW.test(t[1]??""):!1}function EW(e){return bW.test(e.trimEnd())}function IW(e,t,n){let r=new Set,i=new Set(t.map(a=>a.def.parentTypeName).filter(a=>a!==null));if(i.size===0)return r;let o=LW(e,i),s=new Map;for(let a of n){if(!a.parentTypeName)continue;let c=s.get(a.leaf)??new Set;c.add(a.parentTypeName),s.set(a.leaf,c)}for(let a of t){let c=a.def.parentTypeName;if(!c)continue;let l=o.get(c);if(!l||l.size===0)continue;let u=s.get(a.def.leaf)??new Set;[...l].every(m=>u.has(m))&&r.add(a.def.symbol)}return r}var wW=/\bclass\s+([A-Za-z_$][\w$]*)\s+extends\s+([A-Za-z_$][\w$]*)/g;function LW(e,t){let n=new Map;for(let r of Z(e,{includeIgnored:!1})){let i=W(e,r);if(i)for(let o of i.matchAll(wW)){let s=o[1],a=o[2];if(!s||!a||!t.has(a))continue;let c=n.get(a)??new Set;c.add(s),n.set(a,c)}}return n}var PW=/^(?:validate|verify|check|assert)(?:[A-Z].*)?$/,DW=/^(?:is|has)(?:[A-Z].*)?$/,MW=/[{,]\s*(?:ok|success|valid|isValid)\s*:\s*false\b/,qm=/\breturn\b/g,TW=/\bfunction\b|=>|\)\s*(?::\s*[^{;=]+)?\s*\{/,kW=/\.(?:addIssue|push)\s*\(/;function AW(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new H(e),s=he(o.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),a=[];for(let c of s){let l=NW(e,c);l&&a.push({symbol:c.symbol,shortName:T(c.symbol),file:c.relativePath,startLine:c.startLine,endLine:c.endLine,loc:ee(c),...l})}return a.sort((c,l)=>c.file.localeCompare(l.file)||c.startLine-l.startLine||c.loc-l.loc),r?a.slice(0,r):a}function FW(e){return PW.test(e)?"imperative":DW.test(e)?"predicate":null}function NW(e,t){let n=FW(t.leaf);if(!n||_i(e,t))return null;let r=Ht(e,t);if(!r||!TW.test(r))return null;let i=K(e,t.relativePath)?.callables.find(s=>s.startLine===t.startLine&&s.endLine===t.endLine);if(n==="predicate"&&i?.paramCount===0)return null;if(sE(r)){let s=BW(e,t);return!s||bE(s.body,yE(s.snippet))||hE(s.body)?null:{nameKind:n,resolvedVia:"one-hop-delegate",delegateTarget:s.shortName}}let o=an(r);return bE(o,yE(r))||hE(o)?null:{nameKind:n,resolvedVia:"direct"}}var _W=new Set(["if","for","while","switch","catch","function"]);function hE(e){let t=Xi(e);for(let n of t.matchAll(/\b([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/g))if(!_W.has(n[1]))return!0;return!1}function yE(e){let t=e.indexOf("=>");return t===-1?!1:!/^\s*\{/.test(e.slice(t+2))}function bE(e,t){let n=Xi(e);if(/\bthrow\b/.test(n)||/\.reject\s*\(/.test(n)||MW.test(n)||kW.test(n))return!0;let r=OW(n);if(t&&r.length===0){let i=n.trim();return i!==""&&i!=="true"}for(let i of r)if(i!==""&&i!=="true")return!0;return!1}function OW(e){let t=[];qm.lastIndex=0;let n;for(;n=qm.exec(e);){let r=n.index+n[0].length,i=0,o=e.length;for(let s=r;s<e.length;s+=1){let a=e[s];if(a==="("||a==="["||a==="{")i+=1;else if(a===")"||a==="]"||a==="}"){if(i===0){o=s;break}i-=1}else if(a===";"&&i===0){o=s;break}}t.push(e.slice(r,o).trim()),qm.lastIndex=o}return t}function BW(e,t){let n=Pt(e,t,{callableOnly:!0,limit:3,semanticEvidence:re}),r=[...new Set(n.map(c=>c.symbol))].filter(c=>c!==t.symbol);if(r.length!==1)return null;let o=Qe(e,r[0]).match;if(!o)return null;let s=U(e,o.relativePath).find(c=>c.symbolId===o.symbolId);if(!s)return null;let a=Ht(e,s);return a?{body:an(a),snippet:a,shortName:T(s.symbol)}:null}var $W=60;function jW(e,t={}){let{scope:n,limit:r=30,scanLimit:i,rotDays:o=$W}=t,s=he(ti(e,{extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs"]}).filter(u=>q(u)==="test").filter(u=>!n||u.includes(n)).filter(u=>!e.isIgnored(u)).sort(),i),a=[],c=[],l=[];for(let u of s){let d=W(e,u);if(!d)continue;let m=af(d),p=qW(d);for(let g of WW(m,p))p.add(g);let f=HW(m);for(let g of f){if(g.skip){c.push(eV(e,u,g,o));continue}if(g.kind==="describe")continue;let h=vE(d,g.argsStart),b=m.slice(g.argsStart,g.callEnd),S=d.slice(g.argsStart,g.callEnd);CE(b,p)||a.push({file:u,startLine:hs(d,g.callStart),endLine:hs(d,g.callEnd),title:h,severity:/\bawait\b/.test(b)?"low":"high"});let y=XW(b,S);y&&l.push({file:u,startLine:hs(d,g.callStart),endLine:hs(d,g.callEnd),title:h,echoedValue:y})}}return{assertionFree:r?a.slice(0,r):a,skipped:r?c.slice(0,r):c,mockEcho:r?l.slice(0,r):l}}var Gm=/(?<!\.)\b(?:x(it|test|describe)|(it|test|describe)(?:\.\s*(skip|only|todo|each\s*\([^)]*\)))?)\s*\(/g;function HW(e){let t=[];Gm.lastIndex=0;let n;for(;n=Gm.exec(e);){let r=n[1],i=r??n[2];if(!i)continue;let o=n[3]?.split(/\s*\(/)[0],s=n.index,a=n.index+n[0].length-1,c=ys(e,a);Gm.lastIndex=a+1,o!=="each"&&t.push({kind:i,skip:r!==void 0||o==="skip"||o==="todo",skipKind:o==="todo"?"todo":"skip",callStart:s,argsStart:a+1,callEnd:c+1})}return t}function ys(e,t){let n=0;for(let r=t;r<e.length;r+=1){let i=e[r];if(i==="(")n+=1;else if(i===")"&&(n-=1,n===0))return r}return e.length-1}function hs(e,t){let n=0;for(let r=0;r<t&&r<e.length;r+=1)e[r]===`
|
|
416
|
-
`&&(n+=1);return n}function vE(e,t){let n=e.slice(t,t+400),r=/^\s*(['"`])((?:\\.|(?!\1)[\s\S])*)\1/.exec(n);return r?r[2]:"(anonymous)"}var UW=new Set(["vitest","chai","jest","@jest/globals","assert","node:assert","node:assert/strict","assert/strict","uvu/assert","expect","chai-as-promised"]),SE=/import\s+(?:\*\s+as\s+(\w+)|\{([^}]*)\}|(\w+))\s+from\s+['"]([^'"]+)['"]/g;function qW(e){let t=new Set(["expect","assert"]);SE.lastIndex=0;let n;for(;n=SE.exec(e);){let[,r,i,o,s]=n;if(!(!s||!UW.has(s))&&(r&&t.add(r),o&&t.add(o),i))for(let a of i.split(",")){let c=a.trim().replace(/^type\s+/,"");if(!c)continue;let l=/^(\w+)\s+as\s+(\w+)$/.exec(c);t.add(l?l[2]:c)}}return t}function CE(e,t){if(/\.should\b/.test(e)||/\bawait\s+(?:[\w$.]+\.)?findBy[A-Z]\w*\s*\(/.test(e)||/\bawait\s+\w*waitFor(?:Text|Value|Condition|Result|Event)\s*\(/.test(e)||/\bthrow\b/.test(e))return!0;for(let n of t){let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\b${r}\\s*(?:<[^<>]*>)?\\s*[.(]`).test(e))return!0}return!1}var GW=/\bfunction\s+(\w+)\s*\(/g,zW=/\b(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/g,KW=60;function WW(e,t){let n=new Set;for(let r of[GW,zW]){r.lastIndex=0;let i;for(;i=r.exec(e);){let o=i[1],s=i.index+i[0].length-1,a=ys(e,s),c=e.indexOf("{",a+1);if(c===-1||c-a>KW)continue;let l=VW(e,c),u=e.slice(c+1,l);CE(u,t)&&n.add(o)}}return n}function VW(e,t){let n=0;for(let r=t;r<e.length;r+=1){let i=e[r];if(i==="{")n+=1;else if(i==="}"&&(n-=1,n===0))return r}return e.length-1}var YW=/\bmock(?:ReturnValue|ResolvedValue)(?:Once)?\s*\(/g,zm=/\bexpect\s*\(/g,JW=/^\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(/,xE=/^(?:-?\d+(?:\.\d+)?|(['"`]).+\1)$/;function XW(e,t){let n=QW(e,t,YW);if(n.length===0)return null;let r=ZW(e,t);for(let i of r)if(n.includes(i))return i;return null}function QW(e,t,n){let r=[];n.lastIndex=0;let i;for(;i=n.exec(e);){let o=i.index+i[0].length-1,s=ys(e,o),a=t.slice(o+1,s).trim();xE.test(a)&&r.push(a),n.lastIndex=s+1}return r}function ZW(e,t){let n=[];zm.lastIndex=0;let r;for(;r=zm.exec(e);){let i=r.index+r[0].length-1,o=ys(e,i),s=e.slice(o+1),a=JW.exec(s);if(zm.lastIndex=o+1,!a)continue;let c=o+1+a[0].length-1,l=ys(e,c),u=t.slice(c+1,l).trim();xE.test(u)&&n.push(u)}return n}function eV(e,t,n,r){let i=W(e,t),o=vE(i,n.argsStart),s=hs(i,n.callStart),a=tV(e.config.projectRoot,t,s),c=a===null?"unknown":a>=r?"rot":"workflow";return{file:t,startLine:s,title:o,skipKind:n.skipKind,blockKind:n.kind,ageDays:a,rot:c}}function tV(e,t,n){let r=n+1;try{let i=sn(e,["blame","-L",`${r},${r}`,"--porcelain","--",t]),o=/^author-time (\d+)$/m.exec(i);if(!o)return null;let s=Number(o[1]);return Number.isFinite(s)?Math.max(0,Math.round((Date.now()/1e3-s)/86400)):null}catch{return null}}var nV=.7,RE=.62,EE=.45;function rV(e,t={}){let{windowCommits:n=100,limit:r=30,scope:i,scanLimit:o}=t,s=jt(e,{historyMode:t.historyMode}).fileAddRecords();if(!s)return{available:!1,windowCommits:n,findings:[]};if(r<=0)return{available:!0,windowCommits:n,findings:[]};let a=mV(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let l=iV(e,{limit:r,minSimilarity:t.minSimilarity,scanLimit:o,scope:i,semantic:t.semantic,focusFiles:Number.isFinite(r)?void 0:a}).map(d=>pV(d,s,n)).filter(d=>d!==null);l.sort((d,m)=>(d.kind===m.kind?0:d.kind==="echo"?-1:1)||m.similarity-d.similarity||d.echoFile.localeCompare(m.echoFile)||d.echoSymbol.localeCompare(m.echoSymbol)||d.domain.localeCompare(m.domain));let u=l.slice(0,r).map(fV);return{available:!0,windowCommits:n,findings:u,rootCauseGroups:gV(u)}}function iV(e,t){let n=yV(t.limit),r=[...oV(e,{scope:t.scope,minSimilarity:t.minSimilarity??nV,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],i=_s(e,{scope:t.scope});return i.react&&r.push(...sV(e,{scope:t.scope,minSimilarity:t.minSimilarity??RE,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...aV(e,{scope:t.scope,minSimilarity:t.minSimilarity??EE,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i.vue&&r.push(...uV(e,{scope:t.scope,minSimilarity:t.minSimilarity??RE,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...dV(e,{scope:t.scope,minSimilarity:t.minSimilarity??EE,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r}function oV(e,t){return os(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles}).filter(n=>!je(n.symbolA)&&!je(n.symbolB)).map(n=>({domain:"callable",basis:n.similarityBasis??"callees",symbolA:n.shortNameA,fileA:n.fileA,symbolB:n.shortNameB,fileB:n.fileB,similarity:n.similarity,sharedEvidence:n.sharedCallees,sharedCallees:n.sharedCallees}))}function sV(e,t){return Gc(e,t,{query:ss,domain:"react-component",basis:"jsx-structure",symbolA:n=>n.componentA,symbolB:n=>n.componentB,evidenceBuckets:n=>[["component",n.sharedComponents],["tag",n.sharedNativeTags],["prop",n.sharedProps],["event",n.sharedEvents],["binding",n.sharedBindings]]})}function Gc(e,t,n){return n.query(e,t).filter(r=>r.fileA!==r.fileB).filter(r=>n.acceptPair?.(r)??!0).map(r=>({domain:n.domain,basis:n.basis,symbolA:n.symbolA(r),fileA:r.fileA,symbolB:n.symbolB(r),fileB:r.fileB,similarity:r.similarity,sharedEvidence:bV(...n.evidenceBuckets(r)),sharedCallees:[]}))}function aV(e,t){return Gc(e,t,{query:as,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,acceptPair:lV,evidenceBuckets:n=>[["hook",n.sharedHooks],["react-hook",n.sharedReactHooks],["effect",n.sharedEffects],["state",n.sharedState],["request",n.sharedRequests],["handler",n.sharedHandlers],["action",n.sharedHandlerVerbs]]})}var cV=new Set(["useCallback","useEffect","useLayoutEffect","useMemo","useMutation","useQueries","useQuery","useQueryClient","useReducer","useRef","useState"]);function lV(e){return e.sharedHooks.some(t=>!cV.has(t))||e.sharedState.length>0||e.sharedHandlers.length>0||e.sharedHandlerVerbs.length>=2}function uV(e,t){return Gc(e,t,{query:cs,domain:"vue-component",basis:"vue-template",symbolA:n=>qc(n.fileA),symbolB:n=>qc(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function dV(e,t){return Gc(e,t,{query:ls,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>qc(n.fileA),symbolB:n=>qc(n.fileB),evidenceBuckets:n=>[["composable",n.sharedComposables],["store",n.sharedStores],["reactivity",n.sharedReactivity],["lifecycle",n.sharedLifecycle],["request",n.sharedRequests],["function",n.sharedFunctions],["action",n.sharedFunctionVerbs],["binding",n.sharedBindings],["template-event",n.sharedTemplateEvents]]})}function mV(e,t){let n=new Set;for(let[r,i]of e)i.commitsAgo<=t&&n.add(r);return n}function pV(e,t,n){let r=t.get(e.fileA)?.commitsAgo??null,i=t.get(e.fileB)?.commitsAgo??null,o=r!==null&&r<=n,s=i!==null&&i<=n;if(!o&&!s)return null;if(o&&s){let a=(r??0)<=(i??0);return{kind:"twin",domain:e.domain,basis:e.basis,echoSymbol:a?e.symbolA:e.symbolB,echoFile:a?e.fileA:e.fileB,echoAgeCommits:(a?r:i)??0,establishedSymbol:a?e.symbolB:e.symbolA,establishedFile:a?e.fileB:e.fileA,establishedAgeCommits:a?i:r,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}return{kind:"echo",domain:e.domain,basis:e.basis,echoSymbol:o?e.symbolA:e.symbolB,echoFile:o?e.fileA:e.fileB,echoAgeCommits:(o?r:i)??0,establishedSymbol:o?e.symbolB:e.symbolA,establishedFile:o?e.fileB:e.fileA,establishedAgeCommits:o?i:r,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}function fV(e){let t=IE(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function IE(e){if(e.kind==="echo")return["echo",e.domain,e.basis,e.establishedSymbol].join(":");let t=e.sharedEvidence.slice().sort().join("|"),n=[e.echoSymbol,e.establishedSymbol].sort().join("|");return["twin",e.domain,e.basis,t||n].join(":")}function gV(e){let t=new Map;for(let[n,r]of e.entries()){let i=r.rootCauseKey??IE(r),o=r.groupKey??`recent-duplicate:${i}`,s=t.get(o);s||(s={groupKey:o,rootCauseKey:i,kind:r.kind,domain:r.domain,basis:r.basis,count:0,maxSimilarity:r.similarity,findingIndexes:[],echoFiles:new Set,establishedFile:r.kind==="echo"?r.establishedFile:void 0,establishedSymbol:r.kind==="echo"?r.establishedSymbol:void 0,relatedFiles:new Set,sharedEvidence:new Set,recommendation:hV(r)},t.set(o,s)),s.count+=1,s.maxSimilarity=Math.max(s.maxSimilarity,r.similarity),s.findingIndexes.push(n),s.echoFiles.add(r.echoFile),s.relatedFiles.add(r.echoFile),s.relatedFiles.add(r.establishedFile);for(let a of r.sharedEvidence)s.sharedEvidence.add(a)}return[...t.values()].map(n=>({...n,echoFiles:[...n.echoFiles].sort(),relatedFiles:[...n.relatedFiles].sort(),sharedEvidence:[...n.sharedEvidence].sort().slice(0,16)})).sort((n,r)=>r.count-n.count||r.maxSimilarity-n.maxSimilarity||n.groupKey.localeCompare(r.groupKey))}function hV(e){return e.kind==="echo"?"Review the established side once, then migrate or delete every echo in this group.":"Pick one owner for the new twins and consolidate the group before the copies diverge."}function yV(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function bV(...e){let t=[],n=new Set;for(let[r,i]of e)for(let o of i){let s=`${r}:${o}`;n.has(s)||(n.add(s),t.push(s))}return t}function qc(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var SV=ge("suppression-inventory",{clearGroups:["whole-project"]});function zc(e){return SV.get(e,()=>vV(e))}function vV(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,twin:0,uncategorized:0},n=new Map,r=0;for(let i of ti(e)){let o=W(e,i);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=ks(s);if(a===null)continue;r+=1,n.set(i,(n.get(i)??0)+1);let c=wE(a);t[c]+=1}}for(let i of e.config.suppressions??[])i.expiresAt&&Date.parse(i.expiresAt)<=Date.now()||(r+=1,i.file&&n.set(i.file,(n.get(i.file)??0)+1),t[wE(i.check)]+=1);return{total:r,byCategory:t,byFile:n}}function wE(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"||t==="new-dead"?"dead":t.includes("twin")?"twin":t.includes("similar")||t.includes("duplicate")?"similar":t.includes("wrapper")?"wrapper":t.includes("passthrough")?"passthrough":t.includes("drift")?"drift":t.includes("extract")?"extract":t.includes("stale")?"stale":"uncategorized"}function Km(e,t,n={}){let r=ne(e,t);if(!r)return null;let i=new H(e),o=CV(e,r),s=r.endLine-r.startLine+1,c=i.calleeMap([r],{additive:!0,semantic:n.semantic}).get(r.symbolId)??[],l=new Set(c.map(u=>u.symbol));return{symbol:r.symbol,shortName:T(r.symbol),relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,loc:s,branches:o.branches,estimateBasis:o.estimateBasis,cyclomaticEstimate:o.branches+1,calleeCount:l.size,fanIn:RV(e,r.symbolId),fanOut:EV(c,r.relativePath)}}function CV(e,t){let n=J(e,t.relativePath);if(n){let r=br(n.rootNode,t.startLine,t.endLine);if(r)return{branches:IV(r),estimateBasis:"ast"}}return{branches:TE(DE(e,t.relativePath,t.startLine,t.endLine),PE(e,t.relativePath)),estimateBasis:"regex-fallback"}}function LE(e,t){let n=new Map,r=new Map;for(let i of t){let o=r.get(i.relativePath)??[];o.push(i),r.set(i.relativePath,o)}for(let[i,o]of r){let s=J(e,i),a=s===null?[]:o.filter(l=>s.rootNode.startPosition.row<=l.startLine&&s.rootNode.endPosition.row>=l.endLine),c=new Set(a.map(l=>l.symbolId));if(s&&a.length>0){for(let l of a)n.set(l.symbolId,{branches:0,estimateBasis:"ast"});wV(s.rootNode,a,n)}for(let l of o)c.has(l.symbolId)||n.set(l.symbolId,xV(e,l))}return n}function xV(e,t){return{branches:TE(DE(e,t.relativePath,t.startLine,t.endLine),PE(e,t.relativePath)),estimateBasis:"regex-fallback"}}function PE(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function DE(e,t,n,r){try{return Ye(e.config.projectRoot,t,{inputKind:"indexed source file"}).split(`
|
|
417
|
-
`).slice(n,r+1).join(`
|
|
418
|
-
`)}catch(i){if(!Je(i))throw i;return""}}function RV(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
|
|
419
|
-
FROM mentions m
|
|
420
|
-
JOIN chunks c ON m.chunk_id = c.id
|
|
421
|
-
JOIN (
|
|
422
|
-
SELECT m2.symbol_id, c2.document_id
|
|
423
|
-
FROM mentions m2
|
|
424
|
-
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
425
|
-
WHERE m2.role = 1
|
|
426
|
-
GROUP BY m2.symbol_id
|
|
427
|
-
) sym_def ON sym_def.symbol_id = m.symbol_id
|
|
428
|
-
WHERE m.symbol_id = ?
|
|
429
|
-
AND m.role != 1
|
|
430
|
-
AND sym_def.document_id != c.document_id`,t)?.c??0}function EV(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function IV(e){let t=0;return Sl(e,n=>{t+=ME(n)}),t}function wV(e,t,n){let r=[...t].sort((i,o)=>i.startLine-o.startLine||o.endLine-i.endLine);Sl(e,i=>{let o=ME(i);if(o===0)return;let s=i.startPosition.row,a=i.endPosition.row;for(let c of r){if(c.startLine>s)break;if(c.endLine<a)continue;let l=n.get(c.symbolId);l&&(l.branches+=o)}})}var LV=new Set(["if_statement","conditional_expression","ternary_expression","for_statement","for_in_statement","for_of_statement","while_statement","do_statement","switch_case","case_statement","catch_clause","except_clause","elif_clause","match_arm"]);function ME(e){return LV.has(e.type)?1:e.type==="binary_expression"&&e.parent?.type!=="binary_expression"&&(e.text.includes("&&")||e.text.includes("||"))?PV(e.text):0}function PV(e){return(e.match(/&&|\|\|/g)??[]).length}function TE(e,t){let n=pn(e),r=0,i=[/\bif\b/g,/\belse\s+if\b/g,/\belse\b/g,/\bfor\b/g,/\bwhile\b/g,/\bswitch\b/g,/\bcase\b/g,/\bcatch\b/g,/\?\s*[^?]/g,/&&/g,/\|\|/g];for(let o of i){let s=n.match(o);s&&(r+=s.length)}if(t==="python"){let o=[/\belif\b/g,/\bexcept\b/g,/\bfinally\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="rust"){let o=[/\bmatch\b/g,/=>/g,/\bloop\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="ruby"){let o=[/\belsif\b/g,/\bunless\b/g,/\brescue\b/g,/\bwhen\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="go"){let o=[/\bselect\b/g,/\bdefer\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}return r}function kE(e,t,n={}){let r=ne(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],o=jn(e,r,{semantic:n.semantic,semanticEvidence:re}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?T(c.enclosingSymbol):"(top-level)"})),{outgoingCalls:s,incomingCalls:a}=DV(e,r,o,{semantic:n.semantic!==!1});return{symbol:r.symbol,shortName:T(r.symbol),relativePath:r.relativePath,definitionSites:i.filter(c=>!e.isIgnored(c.file)),referenceSites:o,outgoingCalls:s.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:T(c.symbol),file:c.file})),incomingCalls:a.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:c.symbol===c.file?"(top-level)":T(c.symbol),file:c.file}))}}function Wm(e,t,n={}){let r=kE(e,t,n);return r?{symbol:r.symbol,shortName:r.shortName,relativePath:r.relativePath,definitionSites:r.definitionSites,usageSites:r.referenceSites,producers:r.outgoingCalls,consumers:r.incomingCalls}:null}function DV(e,t,n,r){let i=wi(Pt(e,t,{limit:30,semantic:r.semantic,semanticEvidence:re}).map(a=>({symbol:a.symbol,file:a.file}))),o=wi(Gn(e,t,{limit:30,semantic:r.semantic,semanticEvidence:re})),s=o.length>0?o:wi(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{outgoingCalls:i,incomingCalls:s}}function AE(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=ne(e,t);return o?r==="backward"?MV(e,o,i,{semantic:n.semantic!==!1}):TV(e,o,{semantic:n.semantic!==!1}):null}function Kc(e,t,n={}){return AE(e,t,n)}function MV(e,t,n,r){let i=[],o=new Set([t.symbol]),s=[t];for(let a=1;a<=n&&s.length!==0;a++){let c=[];for(let l of s){let u=Pt(e,l,{semantic:r.semantic,semanticEvidence:re});for(let d of u){if(o.has(d.symbol))continue;o.add(d.symbol),i.push({symbol:d.symbol,shortName:T(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=Sr(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&c.push(m)}}s=c}return{symbol:t.symbol,shortName:T(t.symbol),direction:"backward",connectedSymbols:i}}function TV(e,t,n){let r=new Set,i=[],o=new H(e);for(let s of jn(e,t,{semantic:n.semantic,semanticEvidence:re})){if(i.length>=30)break;let a=s.enclosingSymbol??Ne(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=Sr(e,a);!c||e.isIgnored(c.relativePath)||r.has(c.symbol)||(r.add(c.symbol),i.push({symbol:c.symbol,shortName:T(c.symbol),file:c.relativePath,relationship:`references target at ${s.file}:${s.line+1}`}))}return i.sort((s,a)=>s.file.localeCompare(a.file)),{symbol:t.symbol,shortName:T(t.symbol),direction:"forward",connectedSymbols:i}}function FE(e){let t=new Set(e.filter(n=>n.definition?.isFunctionLike).map(n=>`${n.role}:${n.definition.relativePath}`));return e.flatMap(n=>n.definition?!n.definition.isFunctionLike&&t.has(`${n.role}:${n.definition.relativePath}`)?[]:[{definition:n.definition,role:n.role}]:[])}var jE=6,Vc=10,Ym=3,Jm=8,kV=.7,NE=24,Vm=200,HE=12,_E=80,OE=600;function AV(e,t,n={}){let r=n.impactDepth??3,i=n.sliceDepth??3,o=n.semantic,s=GV(t)?_V(e,t):null,a=s?s.primary?.symbol??null:t,{traceResult:c,callGraphResult:l,complexityResult:u,dataflowResult:d,backwardSliceResult:m,forwardSliceResult:p,affectedResults:f,reuseCandidates:g,targetSymbol:h,affectedConsumerReuse:b}=FV(e,a,n,r,i),S=Oe("change-surface",t,()=>vm(e,t,{semantic:o}),D=>({symbols:D?.symbols.length??0,externalConsumers:D?.totalExternalConsumers??0})),y=Oe("system",t,()=>Yd(e,t),D=>({files:D.files.length,symbols:D.symbols.length})),x=y.files.length===1,v=Oe("deps",t,()=>x?y.dependsOn.map(D=>({relativePath:D,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):$o(e,t),D=>({files:D.length,reusedSystem:x})),C=Oe("rdeps",t,()=>x?y.dependedOnBy.map(D=>({relativePath:D,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):jo(e,t),D=>({files:D.length,reusedSystem:x})),R=Oe("surface",t,()=>Jd(e,t),D=>({consumers:D.length})),E={symbol:c.definitions.length>0||c.referencedBy.length>0||l!==null||u!==null||d!==null||m!==null||p!==null||f.length>0,file:S!==null||v.length>0||C.length>0,module:y.files.length>0||y.symbols.length>0||R.length>0},w=[];s&&!s.primary&&s.callableCount>1&&w.push(`File target has ${s.callableCount} callable symbols; use one callable name for compiler-resolved flow.`);let I=[...new Set(c.referencedBy.map(D=>D.relativePath))];I.length>0&&I.every(D=>q(D)==="test")&&w.push("Only test references were found for this target. For replacement or retirement work, map the currently wired owner or one production entry point before planning; this target does not describe the live affected surface."),!E.symbol&&!E.file&&!E.module&&w.push("No symbol, file, or module matched target.");let k=S?.file??c.definitions[0]?.relativePath??null;return{target:t,...s?.primary?{primaryCallable:{symbol:s.primary.symbol,shortName:z(s.primary.symbol),file:s.primary.relativePath}}:{},matched:E,history:Oe("history",k??t,()=>qV(e,k,n.gitHead)),trace:NV(c),callGraph:l,complexity:u,dataflow:d,backwardSlice:m,forwardSlice:p,affected:f,changeSurface:S,deps:v,rdeps:C,system:y,surface:R,reuseCandidates:g,affectedConsumerReuse:b,sourcePacket:OV(e,h,c,b,g),warnings:w}}function FV(e,t,n,r,i){let o=n.semantic,s=t?Oe("trace",t,()=>Sd(e,t,{semantic:o,referenceContext:HE}),h=>({definitions:h.definitions.length,references:h.referencedBy.length})):{definitions:[],referencedBy:[],claimSupport:null},a=t?Oe("call-graph",t,()=>Bo(e,t,{semantic:o}),h=>({callers:h?.callers.length??0,callees:h?.callees.length??0})):null,c=t?Oe("complexity",t,()=>Km(e,t,{semantic:o}),h=>({callees:h?.calleeCount??0})):null,l=t?Oe("dataflow",t,()=>Wm(e,t,{semantic:o}),h=>({references:h?.usageSites.length??0,producers:h?.producers.length??0,consumers:h?.consumers.length??0})):null,u=t?Oe("backward-slice",t,()=>Kc(e,t,{direction:"backward",maxDepth:i,semantic:o}),h=>({maxDepth:i,connectedSymbols:h?.connectedSymbols.length??0})):null,d=t?Oe("forward-slice",t,()=>Kc(e,t,{direction:"forward",maxDepth:i,semantic:o}),h=>({maxDepth:i,connectedSymbols:h?.connectedSymbols.length??0})):null,m=t?Oe("affected",t,()=>Sm(e,t,{maxDepth:r,scope:n.scope}),h=>({maxDepth:r,affectedSymbols:h.length})):[],p=t?Oe("reuse-candidates",t,()=>is(e,t,{minSimilarity:.4,limit:5,semantic:o,sourceCandidateMode:"target-pruned"}),h=>({candidates:h.length,direct:h.filter(b=>b.actionTier==="direct").length})):[],f=t?ne(e,t)?.symbol??null:null,g=t?Oe("affected-consumer-reuse",t,()=>BV(s,f,h=>is(e,h,{minSimilarity:.4,limit:Vc,semantic:o,sourceCandidateMode:"target-pruned"}),{consumerLimit:jE,perConsumerSearchLimit:Vc,perConsumerCandidateLimit:Ym,candidateLimit:Jm}),h=>({totalConsumers:h.coverage.totalConsumers,analyzedConsumers:h.coverage.analyzedConsumers,candidates:h.candidates.length})):UV();return{traceResult:s,callGraphResult:a,complexityResult:c,dataflowResult:l,backwardSliceResult:u,forwardSliceResult:d,affectedResults:m,reuseCandidates:p,targetSymbol:f,affectedConsumerReuse:g}}function NV(e){return{definitions:e.definitions,referencedBy:e.referencedBy.map(t=>({relativePath:t.relativePath,line:t.line,enclosingSymbol:t.enclosingSymbol,enclosingShort:t.enclosingShort}))}}function _V(e,t){let n=Rr(e,t);if(n.length!==1)return{primary:null,callableCount:0};let r=U(e,n[0]).filter(s=>s.isFunctionLike),i=r.filter(s=>s.enclosingSymbol===null),o=i.length>0?i:r;return{primary:o.length===1?o[0]:null,callableCount:o.length}}function OV(e,t,n,r,i){let o=[...t?[{definition:BE(e,t),role:"target"}]:[],...[...r.candidates.map(d=>d.candidate),...i].map(d=>({definition:BE(e,d.symbolB),role:"reuse-candidate"}))],s=new Map;for(let d of FE(o)){if(s.has(d.definition.symbol))continue;let m=d.role==="target"?Vm:_E,p=d.definition.endLine<=d.definition.startLine?Kn(e,d.definition.relativePath,d.definition.startLine,m):null,f=p?.unitType?p.source:Ht(e,d.definition);if(!f)continue;let g=f.split(`
|
|
431
|
-
`),h=Math.min(g.length,m),b=p?.unitType?p.startLine:d.definition.startLine;s.set(d.definition.symbol,{role:d.role,symbol:d.definition.symbol,shortName:z(d.definition.symbol),file:d.definition.relativePath,startLine:b,endLine:b+h-1,source:g.slice(0,h).join(`
|
|
432
|
-
`),omittedLines:(p?.unitType?p.omittedLines:0)+Math.max(0,g.length-h)})}let a=new Map;for(let d of n.referencedBy){if(d.source===void 0||d.source===null||d.sourceStartLine===void 0||d.sourceStartLine===null||d.sourceEndLine===void 0||d.sourceEndLine===null)continue;let m=`${d.relativePath}:${d.sourceStartLine}-${d.sourceEndLine}`,p=a.get(m);if(p){p.focusLines=[...new Set([...p.focusLines??[],d.line])].sort((f,g)=>f-g);continue}a.set(m,{role:"consumer",symbol:d.enclosingSymbol??`${d.relativePath}:${d.line}`,shortName:d.enclosingShort,file:d.relativePath,startLine:d.sourceStartLine,endLine:d.sourceEndLine,source:d.source,omittedLines:0,focusLines:[d.line]})}let c=[...[...s.values()].filter(d=>d.role==="target"),...a.values(),...[...s.values()].filter(d=>d.role==="reuse-candidate")],l=[],u=OE;for(let d of c){if(l.length>=NE||u<=0)break;let m=d.source.split(`
|
|
433
|
-
`),p=Math.min(m.length,u);l.push({...d,endLine:d.startLine+p-1,source:m.slice(0,p).join(`
|
|
434
|
-
`),omittedLines:d.omittedLines+Math.max(0,m.length-p),...d.focusLines?{focusLines:d.focusLines.filter(f=>f<=d.startLine+p-1)}:{}}),u-=p}return{slices:l,candidateSlices:c.length,omittedSlices:Math.max(0,c.length-l.length),maxSlices:NE,maxLinesPerSlice:Vm,maxTotalLines:OE,targetLineLimit:Vm,consumerContextLines:HE,reuseLineLimit:_E}}function BE(e,t){let n=Sr(e,t);return n?U(e,n.relativePath).find(r=>r.symbol===t)??null:null}function BV(e,t,n,r={}){let i=Wc(r.consumerLimit,jE),o=Wc(r.perConsumerSearchLimit,Vc),s=Wc(r.perConsumerCandidateLimit,Ym),a=Wc(r.candidateLimit,Jm),c=$V(e),l=c.slice(0,i),u=new Set(c.map(p=>p.symbol));t&&u.add(t);let d=new Map;for(let p of l){let f=n(p.symbol).slice(0,o),g=0;for(let h of f){let b=jV(h,p.symbol);if(!b||u.has(b.symbolB))continue;let S=d.get(b.symbolB);if(S?(S.consumers.some(y=>y.symbol===p.symbol)||S.consumers.push(p),b.similarity>S.candidate.similarity&&(S.candidate=b)):d.set(b.symbolB,{candidate:b,consumers:[p]}),g+=1,g>=s)break}}let m=[...d.values()].filter(p=>p.candidate.actionTier==="direct"||p.candidate.similarity>=kV||p.consumers.length>1).sort(HV).slice(0,a);return{candidates:m,coverage:{totalConsumers:c.length,analyzedConsumers:l.length,omittedConsumers:Math.max(0,c.length-l.length),perConsumerSearchLimit:o,perConsumerCandidateLimit:s,candidateLimit:a,returnedCandidates:m.length}}}function $V(e){let t=new Map;for(let n of e.referencedBy){if(!n.enclosingSymbol)continue;let r=t.get(n.enclosingSymbol);if(r){r.referenceCount+=1;continue}t.set(n.enclosingSymbol,{symbol:n.enclosingSymbol,shortName:z(n.enclosingSymbol)||n.enclosingShort,file:n.relativePath,referenceCount:1})}return[...t.values()].sort((n,r)=>r.referenceCount-n.referenceCount||n.symbol.localeCompare(r.symbol))}function jV(e,t){return e.symbolA===t?e:e.symbolB!==t?null:{...e,symbolA:e.symbolB,shortNameA:e.shortNameB,fileA:e.fileB,symbolB:e.symbolA,shortNameB:e.shortNameA,fileB:e.fileA,uniqueToA:e.uniqueToB,uniqueToB:e.uniqueToA}}function HV(e,t){let n=$E(t.candidate.actionTier)-$E(e.candidate.actionTier);if(n!==0)return n;let r=t.consumers.length-e.consumers.length;if(r!==0)return r;let i=t.candidate.similarity-e.candidate.similarity;return i!==0?i:e.candidate.symbolB.localeCompare(t.candidate.symbolB)}function $E(e){return e==="direct"?1:0}function Wc(e,t){return typeof e=="number"&&Number.isFinite(e)?Math.max(1,Math.floor(e)):t}function UV(){return{candidates:[],coverage:{totalConsumers:0,analyzedConsumers:0,omittedConsumers:0,perConsumerSearchLimit:Vc,perConsumerCandidateLimit:Ym,candidateLimit:Jm,returnedCandidates:0}}}function Oe(e,t,n,r=()=>({})){let i;return N(`context.${e}`,()=>(i=n(),i),()=>({target:t,...r(i)}))}function qV(e,t,n){let r={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return r;let i=jt(e,n?{head:n}:{}),o=Oe("history.churn",t,()=>i.fileChurn(),c=>({files:c?.size??0}));if(!o)return r;let s=Oe("history.co-change",t,()=>ms(e,t,{limit:5,...n?{head:n}:{}}),c=>({commits:c.commitsAnalyzed,partners:c.findings.length})),a=Oe("history.suppressions",t,()=>zc(e).byFile.get(t)??0,c=>({suppressions:c}));return{available:!0,file:t,churn:o.get(t)??{changes:0,fixChanges:0,lastChangedAt:0},coChangePartners:s.findings.map(c=>({file:c.fileA===t?c.fileB:c.fileA,together:c.together,confidence:c.confidence,subjectContext:c.subjectContext})),suppressionsInFile:a}}function GV(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}var Ee={dead:{minLoc:1,skipBarrels:!1,deadCodeOnly:!1},isolated:{minLoc:3},similar:{minSimilarity:.6,limit:50,minCallees:4},duplicateBodies:{maxLoc:15,limit:50},extract:{minLoc:15,minCallees:5,limit:50},wrappers:{maxLoc:15,limit:50},passthroughs:{maxLoc:15,limit:50},stale:{minLoc:3,limit:50},drift:{},twinDrift:{minSimilarity:.3}};import{existsSync as zV}from"fs";import{isAbsolute as KV,join as WV}from"path";var VV=".scipquery-baseline.json";function Xm(e){if(e.startsWith("similar:")){let t=e.slice(8).split("|");return t.length!==2?e:`similar:${t.map(T).sort().join("|")}`}if(e.startsWith("duplicate-bodies:")){let t=e.slice(17),n=t.indexOf(":");if(n<0)return e;let r=t.slice(0,n),i=t.slice(n+1).split("|");return i.length<2?e:`duplicate-bodies:${r}:${i.map(T).sort().join("|")}`}return e}function Qm(e,t){return t&&KV(t)?t:WV(e.config.projectRoot,t??VV)}function UE(e,t,n={}){let r=Qm(e,n.path);if(!zV(r))throw new Error(`No baseline found at ${r}. Create one with: scip-query health --write-baseline`);let o=(JSON.parse(Ve(r,"health baseline")).findings??[]).map(Xm),s=new Set(n.accept?o.filter(n.accept):o),a=new Set(t);return{baselinePath:r,baselineCount:s.size,current:[...t],newFindings:t.filter(c=>!s.has(c)),fixedFindings:[...s].filter(c=>!a.has(c))}}import bs from"path";function vs(e,t){let{scope:n,minDeviation:r=5,limit:i=50}=t??{},o=t?.semantic!==!1,s=t?.includePatternDeviations===!0,c=new H(e).fileDependencyGraph(n),l=ts(e,{scope:n}),u=ZV([...YV(e,c,{scope:n,semantic:o}),...XV(l.forbiddenEdges),...s?QV(c,r):[]]);return t?.includeArchitecture===!0&&(u.architecture=l),i<=0||u.results.length<=i?u:{...u,results:u.results.slice(0,i),totalResults:u.results.length}}function YV(e,t,n){let r=n2(e,n.scope),i=[],o=new Set;for(let[a,c]of t){if(Ss(a))continue;let l=r.get(a)??new Set;for(let u of c)Ss(u)||l.has(u)||JV(e,a,u,n)||(i.push({file:a,dep:u}),o.add(a))}o.size>0&&o2(e,r,{paths:[...o]});let s=[];for(let{file:a,dep:c}of i)(r.get(a)??new Set).has(c)||s.push({file:a,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c,actionTier:"direct",evidenceReasons:[`dependency edge exists from ${a} to ${c}`,"no semantic, source, type-only, side-effect, or Vue-template usage survived the conservative skip gates"],recommendation:"Remove the unused import or dependency edge after running the project checks."});return s}function JV(e,t,n,r){return c2(e,t,n)||l2(e,t,n)||s2(n)||d2(e,t,n)||u2(n)?!0:r.semantic&&a2(e,t,n)}function XV(e){return e.flatMap(t=>{let n=t.examples[0];return n?[{file:n.fromFile,kind:"architecture-violation",description:`${t.from} depends on forbidden boundary ${t.to} through ${t.fileEdgeCount} file edge(s)`,dep:n.toFile,detail:`${t.from} may not depend on ${t.to}`,actionTier:"direct",policyBasis:"explicit",architecture:{fromBoundary:t.from,toBoundary:t.to,fileEdgeCount:t.fileEdgeCount,importerCount:t.importerCount,importedFileCount:t.importedFileCount,examples:t.examples},evidenceReasons:[`configured dependency row for ${t.from} does not allow ${t.to}`,`${t.fileEdgeCount} file edge(s) connect ${t.importerCount} importer(s) to ${t.importedFileCount} imported file(s)`,...t.examples.map(r=>`${r.fromFile} imports ${r.toFile}`)],recommendation:"Move the dependency behind an allowed boundary, reverse the dependency through an owned interface, or deliberately update the project architecture rule."}]:[]})}function QV(e,t){let n=[];for(let[r,i]of e2(e)){let o=i.filter(a=>!Ss(a));if(o.length<t)continue;let s=t2(e,o);for(let a of o)for(let c of e.get(a)??[])Ss(c)||(s.get(c)??0)===1&&bs.dirname(c)!==r&&bs.dirname(c)!==bs.dirname(r)&&n.push({file:a,kind:"pattern-deviation",description:`Only file in ${r}/ that depends on ${c}`,dep:c,actionTier:"signal",evidenceReasons:[`${o.length} sibling file(s) in ${r}/ were compared`,`${a} is the only non-skipped sibling depending on ${c}`],recommendation:"Review sibling ownership before changing this import; unique dependency shape can be intentional specialization."})}return n}function ZV(e){let t=e.filter(n=>n.kind==="architecture-violation").length;return{results:e,unusedImports:e.filter(n=>n.kind==="unused-import").length,architectureViolations:t,layerViolations:t,patternDeviations:e.filter(n=>n.kind==="pattern-deviation").length}}function e2(e){let t=new Map;for(let n of e.keys()){let r=bs.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function t2(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])Ss(i)||n.set(i,(n.get(i)??0)+1);return n}function n2(e,t){let n=new Map;return r2(e,n,t),n}function r2(e,t,n){for(let r of i2(e,n))qE(e,t,r.from_file,r.to_file)}function i2(e,t){let n=t?"AND d1.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
|
|
435
|
-
FROM mentions m
|
|
436
|
-
JOIN chunks c ON m.chunk_id = c.id
|
|
437
|
-
JOIN documents d1 ON c.document_id = d1.id
|
|
438
|
-
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
439
|
-
JOIN (
|
|
440
|
-
SELECT m2.symbol_id, c2.document_id
|
|
441
|
-
FROM mentions m2
|
|
442
|
-
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
443
|
-
WHERE m2.role = 1
|
|
444
|
-
GROUP BY m2.symbol_id
|
|
445
|
-
) sym_def ON sym_def.symbol_id = gs.id
|
|
446
|
-
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
447
|
-
WHERE d1.id != d2.id
|
|
448
|
-
AND m.role != 1
|
|
449
|
-
${e.pathExclusionsFor("d1","d2")}
|
|
450
|
-
${n}`,...r)}function o2(e,t,n={}){new H(e).scanSourceReferences({paths:n.paths??Z(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},i=>{i.target.relativePath!==i.sourceFile&&(e.isIgnored(i.target.relativePath)||qE(e,t,i.sourceFile,i.target.relativePath))})}function qE(e,t,n,r){if(e.isIgnored(n)||e.isIgnored(r))return;let i=t.get(n);i||(i=new Set,t.set(n,i)),i.add(r)}function s2(e){return e.includes("types")||e.endsWith(".d.ts")}function a2(e,t,n){return Po(e,t).filter(i=>i.sourcePath===n).some(i=>i.isUsed)}function c2(e,t,n){return ae(e,t).filter(i=>i.sourcePath===n).some(i=>i.used)}function l2(e,t,n){let r=ae(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function u2(e){return e.endsWith(".vue")}function d2(e,t,n){let r=ae(e,t).filter(i=>i.sourcePath===n);return r.length===0?!1:r.every(i=>i.kind==="side-effect"||i.kind==="namespace"&&i.usedMembers.length===0&&!i.used)}function Ss(e){let t=q(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||m2(bs.basename(e)))}function m2(e){return!!(e==="index.ts"||e==="index.js"||e==="cli.ts"||e==="main.ts"||e==="main.rs"||e.includes("worker.")||e.includes("postinstall.")||e==="health.ts"||e==="health.js")}function Cs(e,t){let{scope:n,minLoc:r=3,maxLoc:i=80,limit:o=30,includeLowConfidence:s=!1,scanLimit:a}=t??{},c=t?.semantic!==!1,l=new H(e),u=l.scopedDefinitions(n),d=E2(l,n),m={high:0,medium:1,low:2};return At({candidates:()=>p2(e,l,u,{minLoc:r,maxLoc:i}),orderCandidates:(p,f)=>ee(f)-ee(p)||p.relativePath.localeCompare(f.relativePath),scanLimit:a,profile:{name:"stale-abstractions"},prepare:p=>{let f=g2(p),g=f2(e,l,p,f,{semantic:c}),h=p.filter(b=>{if(l.hasSuppressionComment(b))return!1;let S=Yc(e,b,g,f);return S.realConsumers.length<=1&&!S.transitivelyReachable&&GE(b,S.realConsumers.length,d)});return{consumerFileMap:g,singletonBackedClassIds:b2(e,l,u,h,{semantic:c}),candidateIndex:f}},evaluate:(p,f)=>{if(l.hasSuppressionComment(p)||f.singletonBackedClassIds.has(p.symbolId))return null;let g=Yc(e,p,f.consumerFileMap,f.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!GE(g.definition,g.realConsumers.length,d))return null;let h=h2(e,g);return!s&&h.confidence==="low"?null:h},orderResults:(p,f)=>m[p.confidence]-m[f.confidence]||f.loc-p.loc||p.file.localeCompare(f.file)||p.startLine-f.startLine,limit:o})}function p2(e,t,n,r){return n.filter(i=>i.isTypeLike&&ee(i)>=r.minLoc).filter(i=>ee(i)<=r.maxLoc).filter(i=>!e.isIgnored(i.relativePath)).filter(i=>!i.relativePath.endsWith(".d.ts")).filter(i=>q(i.relativePath)!=="test").filter(i=>!Te(e,i.symbol,i.relativePath)).filter(i=>!I2(i.symbol))}function Zm(e,t,n,r){return Mn(Dn(e,t).forDefinitions(n,{semantic:r.semantic,sourceFallback:r.sourceFallback}))}function f2(e,t,n,r,i){let o=Zm(e,t,n,{semantic:!1,sourceFallback:!1}),s=n.filter(l=>{let u=Yc(e,l,o,r);return u.realConsumers.length<=1&&!(u.realConsumers.length>0&&ep(l.relativePath))}),a=i.semantic&&s.length>0?xn(o,Zm(e,t,s,{semantic:!0,sourceFallback:!1})):o,c=s.filter(l=>Yc(e,l,a,r).realConsumers.length<=1);return xn(a,Zm(e,t,c,{semantic:!1,sourceFallback:!0}))}function g2(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);r||(r=new Map,t.set(n.relativePath,r));let i=z(n.symbol);i&&r.set(i,n)}return t}function Yc(e,t,n,r){let o=[...n.get(t.symbolId)??new Set].filter(u=>u!==t.relativePath&&!e.isIgnored(u)),{realConsumers:s,barrelConsumers:a,importOnlyConsumers:c}=Tc(e,t,o),l=w2(e,t,n,r);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function h2(e,t){let n=KE(e,t.definition.relativePath,t.definition.startLine),r=ep(t.definition.relativePath)?!0:L2(e,t.definition),{confidence:i,reason:o}=P2(t.realConsumers.length,n,r),s=y2(t.realConsumers.length,n,r);return{symbol:t.definition.symbol,shortName:T(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:ee(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:r,confidence:i,reason:o,actionTier:s.actionTier,stalenessKind:s.stalenessKind,recommendation:s.recommendation}}function y2(e,t,n){return e===0?{actionTier:"direct",stalenessKind:"unused-abstraction",recommendation:"Delete the abstraction or wire the missing consumer after checking public/package surfaces."}:t==="class"?{actionTier:"signal",stalenessKind:"one-to-one-class-encapsulation",recommendation:"Treat as weak signal: a one-consumer class may be intentional encapsulation, so inline only after reviewing ownership and state boundaries."}:n?{actionTier:"signal",stalenessKind:"single-consumer-abstraction",recommendation:"Review whether this single-consumer abstraction earns its name or should be folded into the owning feature."}:{actionTier:"signal",stalenessKind:"misplaced-single-consumer-type",recommendation:"Review moving or co-locating the type with its only real consumer; keep it here only if this file owns the public contract."}}function b2(e,t,n,r,i){let o=v2(e,S2(n),r),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=Mn(Dn(e,t).forDefinitions(s,{semantic:i.semantic,sourceFallback:!0})),c=new Set;for(let{singleton:l,classId:u}of o)x2(e,l,a)&&c.add(u);return c}function S2(e){let t=new Map;for(let n of e){let r=z(n.symbol);r&&t.set(zE(n.relativePath,r),n)}return t}function v2(e,t,n){let r=[];for(let i of n){let o=C2(e,t,i);o&&r.push({singleton:o,classId:i.symbolId})}return r}function C2(e,t,n){if(KE(e,n.relativePath,n.startLine)!=="class")return null;let r=z(n.symbol);if(!r)return null;let i=R2(e,n.relativePath,r);return i?t.get(zE(n.relativePath,i))??null:null}function x2(e,t,n){let r=z(t.symbol),i=n.get(t.symbolId);return!r||!i?!1:[...i].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!pm(e,o,r))}function zE(e,t){return`${e}\0${t}`}function R2(e,t,n){let r=W(e,t);if(!r)return null;let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\bexport\\s+const\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*new\\s+${i}\\s*\\(`);return r.match(o)?.[1]??null}function E2(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function I2(e){let t=Bn(e);if("kind"in t)return!1;let n=t.descriptors;if(n.length<2)return!1;let r=n[n.length-1],i=n[n.length-2];return r?.suffix==="type"&&i?.suffix==="type"}function ep(e){let n=(e.split("/").pop()??"").replace(/\.[^.]+$/,"");return!!(n==="types"||n.endsWith("-types")||n==="models"||n==="schema"||n==="common"||n==="protocol"||n==="proto"||n==="dto"||n==="mod"||n==="contracts"||/(^|\/)types(\/|\.)/.test(e)||/(^|\/)models?(\/|\.)/.test(e)||/(^|\/)proto(?:col)?(\/|\.)/.test(e)||/(^|\/)schema(\/|\.)/.test(e)||/(^|\/)contracts?(\/|\.)/.test(e))}function GE(e,t,n){return!(ep(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function w2(e,t,n,r){let i=df(e,t.relativePath),o=z(t.symbol);if(!o)return!1;let s=r.get(t.relativePath);if(!s)return!1;let a=[...i.get(o)??[]],c=new Set;for(;a.length>0;){let l=a.pop();if(c.has(l))continue;c.add(l);let u=s.get(l);if(!u)continue;let d=n.get(u.symbolId);if(d){for(let m of d)if(m!==t.relativePath&&!e.isIgnored(m))return!0}for(let m of i.get(l)??[])a.push(m)}return!1}function KE(e,t,n){let r=W(e,t);if(!r)return"other";let i=r.split(`
|
|
451
|
-
`),o=Math.max(0,n-2),s=Math.min(i.length-1,n+2);for(let a=o;a<=s;a++){let l=(i[a]??"").replace(/^\s*\/\/.*$/g,"");if(/\b(?:export\s+)?(?:abstract\s+)?class\s+\w/.test(l))return"class";if(/\b(?:export\s+)?interface\s+\w/.test(l))return"interface";if(/\b(?:export\s+)?type\s+\w/.test(l))return"type";if(/\b(?:export\s+)?(?:const\s+)?enum\s+\w/.test(l))return"enum"}return"other"}function L2(e,t){let n=W(e,t.relativePath);if(!n)return!1;let r=z(t.symbol);if(!r)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${i}\\b`),s=n.split(`
|
|
452
|
-
`);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function P2(e,t,n){return e===0?{confidence:"high",reason:"unused \u2014 no consumers and defining file has no real usage"}:e===1&&t==="class"?{confidence:"low",reason:"1 consumer + class kind \u2014 likely 1:1 encapsulation, not over-abstraction"}:e===1&&!n?{confidence:"high",reason:"1 consumer + defining file never uses it \u2014 type belongs with its consumer"}:{confidence:"medium",reason:"1 consumer \u2014 single-use abstraction"}}import{basename as zi,extname as Jc}from"path";function xs(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new H(e),a=F2(s.fileDependencyGraph(n));return At({candidates:()=>T2(e,s,n,r),orderCandidates:za,scanLimit:o,profile:{name:"wrapper-candidates"},prepare:c=>({callerFileMap:D2(e,s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>M2(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:i})}function D2(e,t,n,r){let i=Dn(e,t),o=Mn(i.forDefinitions(n,{semantic:!1,sourceFallback:!1})),s=[];r.semantic&&N("wrapper.semantic-candidates",()=>{s=n.filter(m=>tp(e,t,m,o).length<=1)},()=>({symbols:n.length,semanticCandidates:s.length}));let a=s.length===0?new Map:Mn(i.forDefinitions(s,{semantic:!0,sourceFallback:!1})),c=a.size===0?o:xn(o,a),l=new Map(n.map(m=>[m.symbolId,m])),u=new Map;for(let m of n){let p=tp(e,t,m,c);if(p.length>1||(u.set(m.symbolId,m),p.length!==1))continue;let f=p[0],g=WE(e,m.symbolId,f);if(!g)continue;let h=VE(t,e,f,m.symbol,g);h?.isFunctionLike&&l.has(h.symbolId)&&u.set(h.symbolId,l.get(h.symbolId))}let d=[...u.values()];return d.length===0?c:xn(c,Mn(i.forDefinitions(d,{semantic:!1,sourceFallback:!0})))}function M2(e,t,n,r){let i=tp(e,t,n,r.callerFileMap);if(i.length!==1)return null;let o=i[0],s=WE(e,n.symbolId,o);if(!s)return null;let a=VE(t,e,o,n.symbol,s);if(a&&ii(a.symbol))return null;let{fanIn:c,source:l}=k2(r.callerFileMap,r.reverseFanIn,o,a);if(l==="function"?c<=3:c<=5)return null;let u=_2(e,n,o,a);return{symbol:n.symbol,shortName:T(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:ee(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?T(a.symbol):zi(o),callerFanIn:c,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function T2(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:2,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0}).filter(i=>!Ns(e,i))}function tp(e,t,n,r){let i=zi(n.relativePath,Jc(n.relativePath)),o=[...r.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>zi(s,Jc(s))!==i).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return Tc(e,n,o).realConsumers}function WE(e,t,n){return e.get(`SELECT c.start_line, c.end_line
|
|
453
|
-
FROM mentions m
|
|
454
|
-
JOIN chunks c ON m.chunk_id = c.id
|
|
455
|
-
JOIN documents d ON c.document_id = d.id
|
|
456
|
-
WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
|
|
457
|
-
LIMIT 1`,t,n)}function VE(e,t,n,r,i){let o=e.definitionsForFile(n),s=A2(t,n,r,i.start_line,i.end_line);return Ne(o,s)}function k2(e,t,n,r){if(r?.isFunctionLike){let i=[...e.get(r.symbolId)??[]].filter(o=>o!==r.relativePath);if(i.length>0)return{fanIn:i.length,source:"function"}}return{fanIn:N2(t,n),source:"file"}}function A2(e,t,n,r,i){let o=z(n);if(!o)return r;let s=ai(e,t).get(o);if(!s||s.length===0)return r;for(let a of s)if(a>=r&&a<=i)return a;return r}function F2(e){let t=new Map;for(let[n,r]of e){t.has(n)||t.set(n,t.get(n)??0);for(let i of r)t.set(i,(t.get(i)??0)+1)}return t}function N2(e,t){let n=e.get(t)??0;if(n>0)return n;let r=zi(t,Jc(t)),i=0;for(let[o,s]of e)o!==t&&zi(o,Jc(o))===r&&s>i&&(i=s);return i}function _2(e,t,n,r){return Uc(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:T(t.symbol)},{label:"caller name",value:r?.symbol?T(r.symbol):zi(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var O2=25e3,B2=2500,$2=2500;function j2(e){let t=Ar(e);return t.symbols>=O2||t.documents>=B2?$2:void 0}function np(e,t={}){let{scope:n}=t,r=j2(e),i=[],o=zr(e,{scope:n,...Ee.dead,scanLimit:r});for(let s of o.symbols)Ue(e,s.relativePath)||Te(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&i.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of ns(e,{scope:n,...Ee.isolated,scanLimit:r}))Ue(e,s.relativePath)||Te(e,s.symbol,s.relativePath)||i.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of es(e,{scope:n}))s.kind==="real"&&i.push(`cycle:${H2(s.path)}`);for(let s of os(e,{scope:n,...Ee.similar,scanLimit:r}))i.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of fs(e,{scope:n,...Ee.duplicateBodies,scanLimit:r}))i.push(`duplicate-bodies:${s.hash}:${s.functions.map(a=>a.symbol).sort().join("|")}`);for(let s of us(e,{scope:n,...Ee.extract,scanLimit:r}))i.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of xs(e,{scope:n,...Ee.wrappers,scanLimit:r}))i.push(`wrapper:${s.file}:${s.shortName}`);for(let s of gs(e,{scope:n,...Ee.passthroughs,scanLimit:r}))i.push(`passthrough:${s.file}:${s.shortName}`);for(let s of Cs(e,{scope:n,...Ee.stale,scanLimit:r}))i.push(`stale:${s.file}:${s.shortName}`);for(let s of vs(e,{scope:n,...Ee.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY}).results)s.kind!=="architecture-violation"&&i.push(`drift:${s.kind}:${s.file}:${s.dep}`);return i.push(...nm(ts(e,{scope:n}))),[...new Set(i.map(Xm))].sort()}function H2(e){if(e.length===0)return"";let t=0;for(let n=1;n<e.length;n++)e[n]<e[t]&&(t=n);return[...e.slice(t),...e.slice(0,t)].join(">")}function U2(e,t={}){let n=np(e,{scope:t.scope}),r=Qm(e,t.path);return Nf(r,{version:1,findings:n},{spacing:2,trailingNewline:!0}),{path:r,findingCount:n.length}}function q2(e,t={}){return UE(e,np(e,{scope:t.scope}),{path:t.path})}function G2(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new H(e);return At({candidates:()=>o.productionCallableDefinitions({scope:n,files:t.files,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}),filterCandidate:s=>z2(s.relativePath),scanLimit:i,profile:{name:"unused-params"},evaluate:s=>{let a=K(e,s.relativePath)?.callables.find(u=>u.startLine===s.startLine&&u.endLine===s.endLine);if(!a||a.params.length===0||a.params.some(u=>!u.simple)||a.paramsEndLine>=a.endLine)return null;let c=ai(e,s.relativePath),l=[];for(let u=a.params.length-1;u>=0;u--){let d=a.params[u];if(d.name===""||d.name.startsWith("_")||K2(c.get(d.name),a.paramsEndLine,a.endLine))break;l.unshift(d.name)}return l.length===0?null:{symbol:s.symbol,shortName:T(s.symbol),file:s.relativePath,startLine:s.startLine,endLine:s.endLine,paramCount:a.paramCount,unusedTrailing:l}},orderResults:(s,a)=>a.unusedTrailing.length-s.unusedTrailing.length||s.file.localeCompare(a.file)||s.startLine-a.startLine,limit:r})}function z2(e){let t=se(e);return t==="typescript"||t==="tsx"||t==="javascript"}function K2(e,t,n){return e?e.some(r=>r>t&&r<=n):!1}var W2=new Set(Kt());function rp(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:o}=t??{},s=new H(e);return At({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:r,requireFunctionLikeSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,filterCandidate:V2,profile:{name:"complexity-hotspots"},prepare:a=>{let c=J2(e,a),l=t?.semantic!==!1,u=l?st(e):null;u?.materializeReferences(a,{prefetchCallees:!0});let d=s.crossFileCallerMap(a,{semantic:!1});return{callerMap:u?xn(d,u.callerMap(a)):d,calleeMap:s.calleeMap(a,{semantic:l}),languageByFile:c,clojureCallableIds:X2(e,a,c),branchEstimates:LE(e,a)}},evaluate:(a,c)=>Y2(a,c,r),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:i})}function V2(e){return e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&W2.has(e.kind):!0}function Y2(e,t,n){if(t.languageByFile.get(e.relativePath)==="clojure"&&!t.clojureCallableIds.has(e.symbolId))return null;let r=e.endLine-e.startLine+1;if(r<n)return null;let i=t.callerMap.get(e.symbolId)?.size??0,o=t.calleeMap.get(e.symbolId)??[],s=new Set,a=new Set;for(let m of o){let p=`${m.symbol}|${m.file}`;s.add(p),m.file!==e.relativePath&&a.add(p)}let c=a.size,l=s.size,u=t.branchEstimates.get(e.symbolId)??{branches:0,estimateBasis:"regex-fallback"},d=u.branches+1;return{symbol:e.symbol,shortName:T(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:r,fanIn:i,fanOut:c,calleeCount:l,branches:u.branches,estimateBasis:u.estimateBasis,score:Math.round(r/50*(i/5)*Math.max(c/5,1)*Math.max(d/5,1)*100)/100}}function J2(e,t){let n=[...new Set(t.map(o=>o.relativePath))];if(n.length===0)return new Map;let r=n.map(()=>"?").join(", "),i=e.all(`SELECT relative_path, language
|
|
458
|
-
FROM documents
|
|
459
|
-
WHERE relative_path IN (${r})`,...n);return new Map(i.map(o=>[o.relative_path,o.language?.toLowerCase()??null]))}function X2(e,t,n){let r=new Set,i=new Map;for(let o of t){if(n.get(o.relativePath)!=="clojure")continue;let s=i.get(o.relativePath);s||(s=new Set((K(e,o.relativePath)?.callables??[]).map(a=>`${a.name}:${a.startLine}`)),i.set(o.relativePath,s)),s.has(`${o.leaf}:${o.startLine}`)&&r.add(o.symbolId)}return r}import{readdirSync as Q2}from"fs";import{basename as Z2,join as YE}from"path";function eY(e,t,n={}){let r=new Set(e),i=new Set(t),o=[...i].filter(a=>!r.has(a)).sort(),s=n.allowExtra?[]:[...r].filter(a=>!i.has(a)).sort();return{missing:o,extra:s}}function tY(e,t){let n=nY(e,t.file,t.keys);if(!n.ok)return{name:t.name,file:t.file,status:"unavailable",missing:[],extra:[],unavailableReason:n.reason};let r=cY(e.config.projectRoot,t.mustEqual),i=eY(n.keys,r,{allowExtra:t.allowExtra??!1}),o=i.missing.length>0||i.extra.length>0?"violated":"ok";return{name:t.name,file:t.file,status:o,missing:i.missing,extra:i.extra}}function XE(e,t){return t.map(n=>tY(e,n))}function nY(e,t,n){return n.type==="markdown-list"?aY(e,t,n.marker):rY(e,t,n)}function rY(e,t,n){if(!W(e,t))return{ok:!1,reason:`file not found: ${t}`};let i=se(t);if(!i)return{ok:!1,reason:`unsupported file type for ${n.type} extraction: ${t}`};let o=J(e,t);if(!o)return{ok:!1,reason:`tree-sitter parser unavailable for ${i} (${t}) \u2014 contract skipped, not silently passed`,disclosedUnavailable:{language:i,reason:"parser-unavailable"}};let s=n.type==="object-literal-keys"?iY(o,n.identifier):sY(o,n.identifier);return s===null?{ok:!1,reason:`no ${n.type==="object-literal-keys"?"object literal":"string array"} named "${n.identifier}" found in ${t}`}:{ok:!0,keys:s}}function QE(e){let t=e.childForFieldName("value");return t?t.type==="as_expression"||t.type==="satisfies_expression"?t.namedChild(0):t:null}function iY(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=QE(n);if(i?.type==="object")return oY(i)}return null}function oY(e){let t=new Set;for(let n of e.namedChildren)if(n.type==="pair"){let r=n.childForFieldName("key");r&&t.add(ZE(r.text))}else n.type==="shorthand_property_identifier"&&t.add(n.text);return[...t].sort()}function sY(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=QE(n);if(i?.type!=="array")continue;let o=new Set;for(let s of i.namedChildren)s.type==="string"&&o.add(ZE(s.text));return[...o].sort()}return null}function ZE(e){return e.length>=2&&(e[0]==="'"&&e.endsWith("'")||e[0]==='"'&&e.endsWith('"'))?e.slice(1,-1):e}function aY(e,t,n){let r=W(e,t);if(!r)return{ok:!1,reason:`file not found: ${t}`};let i=eI(r,n);return i===null?{ok:!1,reason:`no <!-- BEGIN GENERATED ${n} --> ... <!-- END GENERATED ${n} --> block in ${t}`}:{ok:!0,keys:tI(i)}}function eI(e,t){let n=Ce(t),i=new RegExp(`<!--\\s*BEGIN GENERATED ${n}\\s*-->([\\s\\S]*?)<!--\\s*END GENERATED ${n}\\s*-->`).exec(e);return i?i[1]:null}function tI(e){let t=new Set;for(let n of e.matchAll(/`([a-z][a-z0-9-]*)`/g))t.add(n[1]);for(let n of e.matchAll(/\[([a-z][a-z0-9-]*)\]\([^)]*\)/g))t.add(n[1]);return[...t].sort()}function cY(e,t){switch(t.type){case"top-level-dirs":return JE(YE(e,t.path));case"file-glob":return[...new Set(wc(e,t.pattern).map(n=>Z2(n)))].sort();case"registered-commands":return lY(e);case"builtin-skills":return JE(YE(e,"skills"))}}function JE(e){let t;try{t=Q2(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort()}function lY(e){let t;try{t=Ye(e,"docs/COMMAND_REFERENCE.md",{maxBytes:8*1024*1024,inputKind:"generated command reference"})}catch(r){if(!Je(r))throw r;return[]}let n=eI(t,"COMMAND REFERENCE");return n?tI(n):[]}function kn(e){return e.scoreCount??e.count}function iI(e){let t=pY(e),{breakdown:n,pressure:r}=fY(e),i=rI(n,"risk"),o=rI(n,"hygiene");return{score:Math.min(i,o),riskScore:i,hygieneScore:o,scoreBreakdown:n,overview:{documents:e.statsResult.documents,symbols:e.statsResult.symbols,indexSizeBytes:e.statsResult.indexSizeBytes},findings:{deadSymbols:e.dead.count,deadLoc:e.dead.loc,isolatedSymbols:e.isolated.count,isolatedLoc:e.isolated.loc,cycles:e.realCycleCount,similarPairs:e.similarCount,duplicateBodyGroups:e.duplicateBodies.count,duplicateBodyLoc:e.duplicateBodies.loc,twinDriftGroups:e.twinDrift.count,twinDriftLoc:e.twinDrift.loc,reactComponentDuplicatePairs:e.reactComponentDuplicates.count,reactHookCandidatePairs:e.reactHookCandidates.count,reactHookCandidateScoreCount:kn(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:kn(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:kn(e.wrappers),passthroughs:e.passthroughs.count,staleTypes:e.stale.count,driftedFiles:e.drift.count,complexityHotspotCount:e.complexity.extremeCount,hiddenCouplingPairs:e.gitEvidence?.hiddenCoupling.pairCount??null,hiddenCouplingScoreCount:e.gitEvidence?.hiddenCoupling.scoreCount??null,coverageContractViolations:e.coverageContracts.count},axes:uY(e),validation:mY(e),suppressions:e.suppressions,actions:t,pressure:r,topComplexity:e.complexity.top,detectorEvidence:e.detectorEvidence,warnings:e.warnings.length>0?e.warnings:void 0}}function uY(e){return{deletable:{loc:e.dead.loc+e.isolated.loc,symbols:e.dead.count+e.isolated.count},cycles:{count:e.realCycleCount},changeAmplification:e.gitEvidence?.amplification??null,hiddenCoupling:e.gitEvidence?.hiddenCoupling??null,churnWeightedComplexity:dY(e),evidenceQuality:{graphFindings:e.dead.count+e.isolated.count+e.realCycleCount,heuristicFindings:e.similarCount+e.duplicateBodies.count+e.twinDrift.count+e.reactComponentDuplicates.count+e.reactHookCandidates.count+e.reactLargeComponentPressure.count+e.vueComponentDuplicates.count+e.vueComposableCandidates.count+e.vueLargeViewPressure.count+e.extractCount+e.wrappers.count+e.passthroughs.count+e.stale.count+e.drift.count,userSuppressed:e.suppressions?.total??0}}}function dY(e){let t=e.gitEvidence?.fileStats;return t?e.complexity.top.map(n=>{let r=n.file?t[n.file]?.changes??0:0;return{...n,changes:r,weighted:cn(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function mY(e){let t=e.gitEvidence?.fileStats;if(!t)return null;let n={dead:e.dead.files??[],isolated:e.isolated.files??[],twinDrift:e.twinDrift.files??[],wrappers:e.wrappers.files??[],passthroughs:e.passthroughs.files??[],stale:e.stale.files??[],reactComponents:e.reactComponentDuplicates.files??[],reactHooks:e.reactHookCandidates.files??[],reactLargeComponents:e.reactLargeComponentPressure.files??[],vueComponents:e.vueComponentDuplicates.files??[],vueComposables:e.vueComposableCandidates.files??[],vueLargeViews:e.vueLargeViewPressure.files??[]},r=new Set(Object.values(n).flat()),i=0,o=0,s=0;for(let[u,d]of Object.entries(t))r.has(u)?i+=d.fixChanges:(o+=d.fixChanges,s+=1);let a=r.size>0?cn(i/r.size):0,c=s>0?cn(o/s):0,l={};for(let[u,d]of Object.entries(n)){let m=new Set(d);if(m.size===0)continue;let p=0;for(let g of m)p+=t[g]?.fixChanges??0;let f=cn(p/m.size);l[u]={flaggedFiles:m.size,fixDensity:f,lift:c>0?cn(f/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?cn(a/c):null,byCategory:l,validationBasis:{method:"subject-regex",commitsScanned:e.gitEvidence?.commitsScanned??0}}}function cn(e){return Math.round(e*100)/100}function oI(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function Xc(e,t="existing shared infrastructure discount"){let n=kn(e);return Math.abs(n-e.count)<.01?"":` (${oI(n)} score-weighted after ${t})`}function Rs(e,t){let n=kn(e),r=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?r:`${r} (${oI(n)} score-weighted)`}function pY(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",evidence:"graph-fact",evidenceContractId:"dead-visible-references",description:`${e.dead.count} indexed symbols with no visible repository references \u2014 review runtime/framework roots and the capability disclosure, then verify any deletion with cleanup-plan --verify`,effort:"low",impact:"high",count:e.dead.count,locRecoverable:e.dead.loc}),e.isolated.count>0&&t.push({category:"Isolated symbols",evidence:"graph-fact",evidenceContractId:"isolated-visible-connectivity",description:`${e.isolated.count} symbols with no visible indexed or source-supported caller/callee after root exclusions \u2014 runtime reflection and generated dispatch remain disclosed blind spots`,effort:"low",impact:"medium",count:e.isolated.count,locRecoverable:e.isolated.loc}),e.realCycleCount>0&&t.push({category:"Circular dependencies",evidence:"graph-fact",description:`${e.realCycleCount} indexed dependency cycle(s) \u2014 inspect ownership and runtime order before choosing whether or how to break them`,effort:"medium",impact:"high",count:e.realCycleCount,locRecoverable:0}),e.similarCount>0&&t.push({category:"Similar functions",evidence:"heuristic",evidenceContractId:"duplicate-structural-candidate",description:`${e.similarCount} pairs share disclosed call or source-token evidence beyond imports \u2014 review domain identity before considering consolidation`,effort:"medium",impact:"medium",count:e.similarCount,locRecoverable:0}),e.duplicateBodies.count>0&&t.push({category:"Duplicate function bodies",evidence:"heuristic",evidenceContractId:"duplicate-structural-candidate",description:`${e.duplicateBodies.count} exact small-body group(s) across files \u2014 consolidate only when the domain concept matches`,effort:"low",impact:"medium",count:e.duplicateBodies.count,locRecoverable:e.duplicateBodies.loc}),e.twinDrift.count>0&&t.push({category:"Drifted twin implementations",evidence:"heuristic",description:`${e.twinDrift.count} same-name (or near-name) function group(s) across files with diverged or identical bodies \u2014 determine whether they represent the same concept before acting`,effort:"medium",impact:"medium",count:e.twinDrift.count,locRecoverable:0}),e.reactComponentDuplicates.count>0&&t.push({category:"Duplicated React components",evidence:"heuristic",description:`${e.reactComponentDuplicates.count} React component pair(s) share JSX structure \u2014 review whether local product intent justifies reuse`,effort:"medium",impact:"medium",count:e.reactComponentDuplicates.count,locRecoverable:e.reactComponentDuplicates.loc}),e.reactHookCandidates.count>0&&t.push({category:"Duplicated React hook behavior",evidence:"heuristic",description:`${e.reactHookCandidates.count} React component pair(s) share state/effect/request behavior${Xc(e.reactHookCandidates)} \u2014 review whether a common hook would preserve ownership and lifecycle semantics`,effort:"medium",impact:"medium",count:e.reactHookCandidates.count,locRecoverable:e.reactHookCandidates.loc}),e.reactLargeComponentPressure.count>0&&t.push({category:"Large React components",evidence:"heuristic",description:`${e.reactLargeComponentPressure.count} React component(s) concentrate JSX/behavior pressure \u2014 split by reason to change`,effort:"medium",impact:"medium",count:e.reactLargeComponentPressure.count,locRecoverable:0}),e.vueComponentDuplicates.count>0&&t.push({category:"Duplicated Vue components",evidence:"heuristic",description:`${e.vueComponentDuplicates.count} Vue component pair(s) share template structure \u2014 review whether local product intent justifies reuse`,effort:"medium",impact:"medium",count:e.vueComponentDuplicates.count,locRecoverable:e.vueComponentDuplicates.loc}),e.vueComposableCandidates.count>0&&t.push({category:"Duplicated Vue behavior",evidence:"heuristic",description:`${e.vueComposableCandidates.count} Vue component pair(s) share state/effect/request behavior${Xc(e.vueComposableCandidates)} \u2014 review whether a common composable would preserve ownership and lifecycle semantics`,effort:"medium",impact:"medium",count:e.vueComposableCandidates.count,locRecoverable:e.vueComposableCandidates.loc}),e.vueLargeViewPressure.count>0&&t.push({category:"Large Vue views",evidence:"heuristic",description:`${e.vueLargeViewPressure.count} Vue file(s) concentrate template/script/style pressure \u2014 split by reason to change`,effort:"medium",impact:"medium",count:e.vueLargeViewPressure.count,locRecoverable:0}),e.extractCount>0&&t.push({category:"Extraction candidates",evidence:"heuristic",description:`${e.extractCount} large functions with isolated callee clusters \u2014 review same-file or feature-local extraction seams`,effort:"medium",impact:"medium",count:e.extractCount,locRecoverable:0}),e.wrappers.count>0&&t.push({category:"Wrapper functions",evidence:"heuristic",evidenceContractId:"wrapper-indirection-candidate",description:`${e.wrappers.count} single-consumer symbols${Xc(e.wrappers,"boundary-evidence discount")} \u2014 inspect whether each is indirection or an intentional API, framework, or ownership boundary`,effort:"low",impact:"low",count:e.wrappers.count,locRecoverable:e.wrappers.loc}),e.passthroughs.count>0&&t.push({category:"Passthrough functions",evidence:"heuristic",evidenceContractId:"passthrough-forwarding-candidate",description:`${e.passthroughs.count} functions that literally forward to one callee \u2014 inspect whether each is unnecessary indirection or an intentional boundary`,effort:"low",impact:"low",count:e.passthroughs.count,locRecoverable:e.passthroughs.loc}),e.stale.count>0){let i=[];e.stale.unused>0&&i.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&i.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",evidence:"heuristic",evidenceContractId:"stale-abstraction-candidate",description:`${i.join(", ")} \u2014 review public, runtime-registration, and ownership evidence before removing, moving, or inlining`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let i=[];e.drift.unusedImports>0&&i.push(`${e.drift.unusedImports} unused imports`),e.drift.architectureViolations>0&&i.push(`${e.drift.architectureViolations} declared architecture violations`),t.push({category:"Structural drift",evidence:"heuristic",description:`${i.join(", ")} \u2014 repair direct dependency-rule breaks; inspect boundary signals with \`drift --architecture\``,effort:e.drift.architectureViolations>0?"medium":"low",impact:e.drift.architectureViolations>0?"medium":"low",count:e.drift.count,locRecoverable:0})}if(e.coverageContracts.count>0&&t.push({category:"Coverage contract drift",evidence:"graph-fact",description:`${e.coverageContracts.count} configured coverage contract(s) drifted from their ground-truth source (enumeration rot) \u2014 run \`scip-query health --json\` for the missing/extra keys`,effort:"low",impact:"medium",count:e.coverageContracts.count,locRecoverable:0}),e.gitEvidence&&e.gitEvidence.hiddenCoupling.pairCount>0){let i=e.gitEvidence.hiddenCoupling.top[0];t.push({category:"Hidden coupling",evidence:"change-graph",description:`${e.gitEvidence.hiddenCoupling.pairCount} file pair(s) co-change without a structural link`+Xc({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:e.gitEvidence.hiddenCoupling.scoreCount},"broad/stale-history discount")+(i?` (e.g. ${i.fileA} \u2194 ${i.fileB})`:"")+" \u2014 inspect whether a shared concept, generated artifact, or coordinated contract explains the history",effort:"medium",impact:"high",count:e.gitEvidence.hiddenCoupling.pairCount,locRecoverable:0})}let n={high:3,medium:2,low:1},r={low:3,medium:2,high:1};return t.sort((i,o)=>{let s=n[i.impact]*r[i.effort];return n[o.impact]*r[o.effort]-s}),t}var nI={"dead-code":"risk",isolated:"risk",cycles:"risk",complexity:"risk","hidden-coupling":"risk","cycles-pressure":"risk","complexity-pressure":"risk","hidden-coupling-pressure":"risk",similar:"hygiene","duplicate-bodies":"hygiene","twin-drift":"hygiene","react-component-duplicates":"hygiene","react-hook-candidates":"hygiene","react-large-component-pressure":"hygiene","vue-component-duplicates":"hygiene","vue-composable-candidates":"hygiene","vue-large-view-pressure":"hygiene",extract:"hygiene",wrappers:"hygiene",passthroughs:"hygiene","stale-abstractions":"hygiene",drift:"hygiene","similar-pressure":"hygiene","duplicate-bodies-pressure":"hygiene","twin-drift-pressure":"hygiene","react-component-duplicates-pressure":"hygiene","react-hook-candidates-pressure":"hygiene","react-large-component-pressure-pressure":"hygiene","vue-component-duplicates-pressure":"hygiene","vue-composable-candidates-pressure":"hygiene","vue-large-view-pressure-pressure":"hygiene","extract-pressure":"hygiene","wrappers-pressure":"hygiene","passthroughs-pressure":"hygiene","stale-abstractions-pressure":"hygiene","drift-pressure":"hygiene"};function rI(e,t){let n=e.filter(r=>r.kind===t).reduce((r,i)=>r+i.points,0);return Math.max(0,Math.min(100,100-n))}function fY(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=[],i=[],o=(R,E,w)=>{E>0&&r.push({axis:R,points:E,detail:w,kind:nI[R]??"hygiene"})},s=(R,E,w,I,k,D,F)=>{let L=Math.max(I,1);if(w<=L)return;let A=w/L,P=Math.min(k,Math.ceil(Math.log2(A)*D));if(P<=0)return;let j=nI[R]??"hygiene";i.push({axis:R,category:E,kind:j,count:w,threshold:cn(L),ratio:cn(A),extraPenalty:P}),o(R,P,`${w} ${F} exceed pressure threshold ${cn(L)} (${cn(A)}x)`)},a=e.dead.count/n;o("dead-code",Math.min(20,Math.round(a*200)),`${e.dead.count} dead symbols (${e.dead.loc} LOC deletable)`);let c=e.isolated.count/n;o("isolated",Math.min(10,Math.round(c*200)),`${e.isolated.count} isolated symbols (${e.isolated.loc} LOC deletable)`),o("cycles",Math.min(15,e.realCycleCount*5),`${e.realCycleCount} real dependency cycle(s)`);let l=e.similarCount/n*1e3;o("similar",Math.min(10,Math.round(l)),`${e.similarCount} similar function pair(s)`);let u=e.duplicateBodies.count/n*1e3;o("duplicate-bodies",Math.min(10,Math.round(u*2)),`${e.duplicateBodies.count} exact duplicate small-body group(s) (${e.duplicateBodies.loc} duplicate LOC)`);let d=e.twinDrift.count/n*1e3;o("twin-drift",Math.min(10,Math.round(d*2)),`${e.twinDrift.count} drifted twin implementation group(s) (same or near-same name, diverged or identical bodies)`);let m=e.reactComponentDuplicates.count/t*1e3;o("react-component-duplicates",Math.min(10,Math.round(m)),`${e.reactComponentDuplicates.count} duplicated React component pair(s)`);let p=kn(e.reactHookCandidates),f=p/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(f)),Rs(e.reactHookCandidates,"duplicated React behavior pair(s)"));let g=e.reactLargeComponentPressure.count/t*1e3;o("react-large-component-pressure",Math.min(5,Math.round(g/2)),`${e.reactLargeComponentPressure.count} large React component pressure file(s)`);let h=e.vueComponentDuplicates.count/t*1e3;o("vue-component-duplicates",Math.min(10,Math.round(h)),`${e.vueComponentDuplicates.count} duplicated Vue component pair(s)`);let b=kn(e.vueComposableCandidates),S=b/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(S)),Rs(e.vueComposableCandidates,"duplicated Vue behavior pair(s)"));let y=e.vueLargeViewPressure.count/t*1e3;o("vue-large-view-pressure",Math.min(5,Math.round(y/2)),`${e.vueLargeViewPressure.count} large Vue view pressure file(s)`);let x=kn(e.wrappers);o("wrappers",Math.min(3,x),Rs(e.wrappers,"wrapper candidate(s)"));let v=kn(e.passthroughs);o("passthroughs",Math.min(3,v),Rs(e.passthroughs,"passthrough candidate(s)")),o("stale-abstractions",Math.min(8,e.stale.unused),`${e.stale.unused} unused stale abstraction(s); ${e.stale.singleUse} single-consumer signal(s)`);let C=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(C*50)),`${e.drift.direct} direct drift finding(s); ${e.drift.signal} signal drift finding(s)`),o("complexity",Math.min(5,e.complexity.extremeCount*2),`${e.complexity.extremeCount} extreme complexity hotspot(s)`),e.gitEvidence){let R=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(R/10)),Rs({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:R},"co-changing pair(s) without a structural link"))}if(s("cycles-pressure","Circular dependencies",e.realCycleCount,3,10,3,"cycle(s)"),s("complexity-pressure","Extreme complexity",e.complexity.extremeCount,3,5,2,"extreme complexity hotspot(s)"),e.gitEvidence){let R=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",R,50,10,4,"score-weighted co-changing pair(s)")}return s("similar-pressure","Similar functions",e.similarCount,Math.max(50,n*.01),8,4,"similar function pair(s)"),s("duplicate-bodies-pressure","Duplicate function bodies",e.duplicateBodies.count,Math.max(20,n*.005),8,4,"exact duplicate small-body group(s)"),s("twin-drift-pressure","Drifted twin implementations",e.twinDrift.count,Math.max(20,n*.005),8,4,"drifted twin implementation group(s)"),s("react-component-duplicates-pressure","Duplicated React components",e.reactComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated React component pair(s)"),s("react-hook-candidates-pressure","Duplicated React hook behavior",p,Math.max(10,t*.01),8,4,"duplicated React behavior pair(s)"),s("react-large-component-pressure-pressure","Large React components",e.reactLargeComponentPressure.count,Math.max(10,t*.01),4,2,"large React component pressure file(s)"),s("vue-component-duplicates-pressure","Duplicated Vue components",e.vueComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated Vue component pair(s)"),s("vue-composable-candidates-pressure","Duplicated Vue behavior",b,Math.max(10,t*.01),8,4,"duplicated Vue behavior pair(s)"),s("vue-large-view-pressure-pressure","Large Vue views",e.vueLargeViewPressure.count,Math.max(10,t*.01),4,2,"large Vue view pressure file(s)"),s("extract-pressure","Extraction candidates",e.extractCount,Math.max(50,n*.01),4,2,"extraction candidate(s)"),s("wrappers-pressure","Wrapper functions",x,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",v,50,4,2,"passthrough candidate(s)"),s("stale-abstractions-pressure","Single-consumer stale abstraction signals",e.stale.singleUse,Math.max(50,n*.02),4,2,"single-consumer stale abstraction signal(s)"),s("drift-pressure","Structural drift signals",e.drift.signal,Math.max(10,t*.1),4,2,"signal drift finding(s)"),{breakdown:r,pressure:i}}import{getHeapStatistics as gY}from"v8";var hY=64*1024*1024;function ip(){let e=globalThis.gc;if(!e)return;let t=gY();t.heap_size_limit-t.used_heap_size<hY||e()}var yY=[{id:"dead-visible-references",detector:"dead",claim:"The symbol has no visible repository reference after entry, framework, and rooted-symbol exclusions.",relationRequirements:[{family:"identity",subtype:"references",minimumStrength:"exact"},{family:"execution",subtype:"call",minimumStrength:"exact"}],structuralEvidence:["entry-surface exclusions","framework/source fallback references","rooted-symbol exclusions"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Absence of visible references does not prove absence of reflection, generated dispatch, or external use."],recoverWith:"scip-query evidence --symbol <symbol> --edge execution --edge runtime --edge identity --direction both --depth 2 --max-edges 100"},{id:"isolated-visible-connectivity",detector:"isolated",claim:"The callable has no visible non-self caller or callee after entry, framework, and rooted-symbol exclusions.",relationRequirements:[{family:"execution",subtype:"call",minimumStrength:"exact"},{family:"identity",subtype:"references",minimumStrength:"exact"}],structuralEvidence:["entry-surface exclusions","framework contract exclusions","source fallback callers"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Visible graph isolation does not establish runtime unreachability through reflection or generated dispatch."],recoverWith:"scip-query evidence --symbol <symbol> --edge execution --edge runtime --edge identity --direction both --depth 2 --max-edges 100"},{id:"wrapper-indirection-candidate",detector:"wrapper-candidates",claim:"A small callable has one visible consumer and wrapper-shaped delegation, after boundary evidence is disclosed.",relationRequirements:[{family:"execution",subtype:"call",minimumStrength:"exact"},{family:"ownership",subtype:"contains",minimumStrength:"exact"}],structuralEvidence:["callable body shape","public and runtime-boundary signals","consumer fan-in"],calibration:"candidate",providerCoverage:"partial",nonClaims:["Wrapper shape does not prove that an API, ownership, observability, or compatibility boundary is unnecessary."],recoverWith:"scip-query inspect --symbol <symbol> --view behavior"},{id:"passthrough-forwarding-candidate",detector:"passthrough-candidates",claim:"A small callable visibly forwards to one callee, with public-facade and boundary signals disclosed.",relationRequirements:[{family:"execution",subtype:"call",minimumStrength:"exact"},{family:"contract",subtype:"uses-contract-symbol",minimumStrength:"exact"}],structuralEvidence:["statement-complete forwarding shape","public facade evidence","runtime-boundary signals"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Literal forwarding does not prove the callable has no contract, naming, policy, or compatibility role."],recoverWith:"scip-query inspect --symbol <symbol> --view behavior"},{id:"stale-abstraction-candidate",detector:"stale-abstractions",claim:"A type-like abstraction has zero or one visible real consumer after re-export and ownership distinctions.",relationRequirements:[{family:"identity",subtype:"references",minimumStrength:"exact"},{family:"ownership",subtype:"contains",minimumStrength:"exact"}],structuralEvidence:["definition kind","barrel-only consumer distinction","defining-file usage"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Low visible consumer count does not prove a public contract or runtime-registered type is obsolete."],recoverWith:"scip-query evidence --symbol <symbol> --edge identity --edge ownership --edge contract --direction both --depth 2 --max-edges 100"},{id:"complexity-control-pressure",detector:"complexity-hotspots",claim:"A callable concentrates local branch/control pressure and graph fan-in or fan-out.",relationRequirements:[{family:"execution",subtype:"predicate-consequence",minimumStrength:"exact"},{family:"execution",subtype:"call",minimumStrength:"exact"}],structuralEvidence:["AST branch count or disclosed regex fallback","call fan-in","callee count"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Structural complexity does not establish runtime frequency, latency, defect density, or a required refactor."],recoverWith:"scip-query inspect --symbol <symbol> --view behavior"},{id:"decorative-checker-terminal-behavior",detector:"decorative-checkers",claim:"A checker-shaped callable lacks a visible failure terminal directly or through one resolved delegate.",relationRequirements:[{family:"execution",subtype:"returns",minimumStrength:"exact"},{family:"execution",subtype:"throws",minimumStrength:"exact"}],structuralEvidence:["checker naming shape","direct terminal behavior","one-hop delegate body"],calibration:"mixed",providerCoverage:"partial",nonClaims:["No visible terminal does not prove the checker cannot fail through an opaque call, exception, or process exit."],recoverWith:"scip-query inspect --symbol <symbol> --view behavior"},{id:"duplicate-structural-candidate",detector:"duplicate and similarity detectors",claim:"Two source units share the detector-specific structural or token pattern.",relationRequirements:[],structuralEvidence:["normalized source/token/JSX/template similarity"],calibration:"candidate",providerCoverage:"partial",nonClaims:["Structural similarity does not establish shared domain identity or justify consolidation."],recoverWith:"scip-query inspect --symbol <symbol-a> --symbol <symbol-b> --view behavior"}];function sI(e=new Set(["indexed-graph","source-facts"])){return yY.map(t=>{let n=t.relationRequirements.map(i=>{let o=sc(i.family,i.subtype);if(!o)throw new Error(`Detector ${t.id} names an unregistered relation ${i.family}/${i.subtype}`);if(!o.relation.evidenceStrengths.includes(i.minimumStrength))throw new Error(`Detector ${t.id} requires unsupported strength ${i.minimumStrength} for ${i.family}/${i.subtype}`);return o.provider}),r=[...new Set(n.flatMap(i=>i.requirements))].filter(i=>!e.has(i));return{...t,status:r.length>0?"unsupported":t.calibration,providerIds:[...new Set(n.map(i=>i.id))],unavailableRequirements:r}})}var bY=50,SY=25e3,vY=2500,aI=2500,cI=50,CY=10,Qc=["overview","dead","isolated","cycles","similar","duplicate-bodies","twin-drift","react-component-duplicates","react-hook-candidates","react-large-component-pressure","vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure","extract-candidates","wrapper-candidates","passthrough-candidates","stale-abstractions","drift","complexity-hotspots","git-evidence","suppressions","coverage-contracts"],xY={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:wY(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:LY(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:PY(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:DY(e,t,n)}),"duplicate-bodies":(e,t,n)=>({phase:"duplicate-bodies",duplicateBodies:TY(e,t,n)}),"twin-drift":(e,t,n)=>({phase:"twin-drift",twinDrift:kY(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:AY(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:FY(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:NY(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:_Y(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:OY(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:BY(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:MY(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:$Y(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:jY(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:HY(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:zY(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:KY(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:UY(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:qY(e,n)}),"coverage-contracts":(e,t,n)=>({phase:"coverage-contracts",coverageContracts:GY(e,n)})};function op(e,t,n={}){return RY(e,[t],n)[0]}function RY(e,t,n={}){return EY(e,n.full!==!1,(r,i)=>{let o={...i,releaseCachesBetweenPhases:!1};return t.map(s=>xY[s](e,n.scope,o,r))})}function EY(e,t,n){let r=Ar(e),i=WY(r,t);try{return n(r,i)}finally{Zd(e,{semanticProvider:!0}),ip()}}function sp(e){return iI(IY(e))}function IY(e){let t=Pe(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,detectorEvidence:sI(),dead:Pe(e,"dead").dead,isolated:Pe(e,"isolated").isolated,realCycleCount:Pe(e,"cycles").realCycleCount,similarCount:Pe(e,"similar").similarCount,duplicateBodies:Pe(e,"duplicate-bodies").duplicateBodies,twinDrift:Pe(e,"twin-drift").twinDrift,reactComponentDuplicates:Pe(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:Pe(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:Pe(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:Pe(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:Pe(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:Pe(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:Pe(e,"extract-candidates").extractCount,wrappers:Pe(e,"wrapper-candidates").wrappers,passthroughs:Pe(e,"passthrough-candidates").passthroughs,stale:Pe(e,"stale-abstractions").stale,drift:Pe(e,"drift").drift,complexity:Pe(e,"complexity-hotspots").complexity,gitEvidence:lI(e,"git-evidence")?.gitEvidence??null,suppressions:lI(e,"suppressions")?.suppressions??null,coverageContracts:Pe(e,"coverage-contracts").coverageContracts}}function lI(e,t){return e.find(n=>n.phase===t)}function Pe(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function wY(e,t,n){return Ie(e,n,"dead",()=>{let r=zr(e,{scope:t,...Ee.dead,scanLimit:n.candidateScanLimit,semantic:n.semantic});return Zc(JY(e,r.symbols))})}function LY(e,t,n){return Ie(e,n,"isolated",()=>{let r=ns(e,{scope:t,...Ee.isolated,scanLimit:n.candidateScanLimit,semantic:n.semantic});return Zc(XY(e,r))})}function PY(e,t,n){return Ie(e,n,"cycles",()=>es(e,{scope:t}).filter(i=>i.kind==="real").length)}function DY(e,t,n){let r=Ie(e,n,"similar",()=>lm(e,{scope:t,...Ee.similar,scanLimit:n.candidateScanLimit,semantic:n.semantic}));return Math.min(r,n.candidateResultLimit)}function MY(e,t,n){return Ie(e,n,"extract-candidates",()=>us(e,{scope:t,...Ee.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}).length)}function TY(e,t,n){return Ie(e,n,"duplicate-bodies",()=>{let r=fs(e,{scope:t,...Ee.duplicateBodies,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),i=new Set,o=0;for(let s of r)for(let a of s.functions.slice(1))i.add(a.file),o+=a.loc;return{count:r.length,loc:o,files:[...i]}})}function kY(e,t,n){return Ie(e,n,"twin-drift",()=>{let r=Hc(e,{scope:t,...Ee.twinDrift,scanLimit:n.candidateScanLimit}).filter(s=>s.relationship==="divergent"||s.relationship==="identical"),i=new Set,o=0;for(let s of r)for(let a of s.members)i.add(a.file),o+=a.loc;return{count:r.length,loc:o,files:[...i].sort()}})}function AY(e,t,n){return Ie(e,n,"react-component-duplicates",()=>{let r=ss(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return ap(r)})}function FY(e,t,n){return Ie(e,n,"react-hook-candidates",()=>{let r=as(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return mI(r,ZY)})}function NY(e,t,n){return Ie(e,n,"react-large-component-pressure",()=>{let r=um(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return QY(r)})}function _Y(e,t,n){return Ie(e,n,"vue-component-duplicates",()=>{let r=cs(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return ap(r)})}function OY(e,t,n){return Ie(e,n,"vue-composable-candidates",()=>{let r=ls(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return mI(r,eJ)})}function BY(e,t,n){return Ie(e,n,"vue-large-view-pressure",()=>{let r=dm(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Zc(r)})}function $Y(e,t,n){return Ie(e,n,"wrapper-candidates",()=>{let r=xs(e,{scope:t,...Ee.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return dI(r,tJ)})}function jY(e,t,n){return Ie(e,n,"passthrough-candidates",()=>{let r=gs(e,{scope:t,...Ee.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return dI(r,nJ)})}function HY(e,t,n){return Ie(e,n,"stale-abstractions",()=>{let r=Cs(e,{scope:t,...Ee.stale,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}),i=r.filter(o=>o.consumers===0).length;return{count:r.length,loc:r.reduce((o,s)=>o+s.loc,0),files:[...new Set(r.map(o=>o.file))],unused:i,singleUse:r.length-i}})}function UY(e,t){return Ie(e,t,"git-evidence",()=>{let n=jt(e,{historyMode:t.gitHistoryMode}),r=n.fileChurn();if(!r)return null;let i=n.commitHistory(),o=ms(e,void 0,{limit:t.candidateResultLimit,historyMode:t.gitHistoryMode}),s={};for(let[a,c]of r)s[a]={changes:c.changes,fixChanges:c.fixChanges};return{amplification:n.changeAmplification(),hiddenCoupling:{pairCount:o.findings.length,scoreCount:cp(o.findings.reduce((a,c)=>a+uI(c),0)),top:o.findings.slice(0,5).map(a=>({fileA:a.fileA,fileB:a.fileB,together:a.together,confidence:a.confidence,focusedTogether:a.focusedTogether,broadTogether:a.broadTogether,broadCommitRatio:a.broadCommitRatio,lastTogetherAt:a.lastTogetherAt,recentTogether:a.recentTogether,commitScope:a.commitScope,recency:a.recency,scoreWeight:uI(a),subjectContext:a.subjectContext}))},fileStats:s,commitsScanned:i?.commits.length??0}})}function qY(e,t){return Ie(e,t,"suppressions",()=>{let n=zc(e);return{total:n.total,byCategory:{...n.byCategory}}})}function GY(e,t){return Ie(e,t,"coverage-contracts",()=>{let n=e.config.coverageContracts??[],i=XE(e,n).filter(o=>o.status!=="ok");return{count:i.length,loc:0,files:[...new Set(i.map(o=>o.file))].sort()}})}function zY(e,t,n){return Ie(e,n,"drift",()=>{let r=vs(e,{scope:t,...Ee.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY,semantic:n.semantic}),i=r.results.filter(a=>a.kind!=="pattern-deviation"),o=i.filter(a=>a.actionTier==="direct").length,s=i.length-o;return{count:i.length,unusedImports:r.unusedImports,architectureViolations:r.architectureViolations,layerViolations:r.layerViolations,direct:o,signal:s}})}function KY(e,t,n){return Ie(e,n,"complexity-hotspots",()=>{let r=rp(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return{top:r.slice(0,5).map(i=>({symbol:i.shortName,score:i.score,file:i.file})),extremeCount:r.filter(i=>i.score>bY).length}})}function WY(e,t){let n=e.symbols>=SY||e.documents>=vY,r=t?Number.POSITIVE_INFINITY:cI,i=t?Number.POSITIVE_INFINITY:CY;return!n||t?{candidateScanLimit:void 0,candidateResultLimit:r,complexityResultLimit:i,semantic:!0,gitHistoryMode:t?"full":"bounded",releaseCachesBetweenPhases:!0,warnings:t&&n?["Large index detected; running health without candidate scan or result caps because full mode is enabled."]:[]}:{candidateScanLimit:aI,candidateResultLimit:r,complexityResultLimit:i,semantic:!1,gitHistoryMode:"bounded",releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${aI} symbols and reported their top ${cI} findings. Enable full mode for unbounded candidate counts.`]}}function VY(e,t){t.releaseCachesBetweenPhases&&(Zd(e),ip())}function Ie(e,t,n,r){YY(n);try{return r()}finally{VY(e,t)}}function YY(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function JY(e,t){return t.filter(n=>!Ue(e,n.relativePath)&&!Te(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function XY(e,t){return t.filter(n=>!Ue(e,n.relativePath)&&!Te(e,n.symbol,n.relativePath))}function Zc(e){let t=new Set;for(let n of e){let r=n.relativePath??n.file;r&&t.add(r)}return{count:e.length,loc:e.reduce((n,r)=>n+r.loc,0),files:[...t]}}function dI(e,t){return{...Zc(e),scoreCount:cp(e.reduce((r,i)=>r+t(i),0))}}function QY(e){let t=new Map;for(let n of e)t.set(n.file,Math.max(t.get(n.file)??0,n.loc));return{count:t.size,loc:[...t.values()].reduce((n,r)=>n+r,0),files:[...t.keys()]}}function ap(e){let t=new Map;for(let n of e)t.set(n.fileA,Math.max(t.get(n.fileA)??0,n.locA)),t.set(n.fileB,Math.max(t.get(n.fileB)??0,n.locB));return{count:e.length,loc:[...t.values()].reduce((n,r)=>n+r,0),files:[...t.keys()]}}function mI(e,t){return{...ap(e),scoreCount:cp(e.reduce((r,i)=>r+t(i),0))}}function ZY(e){let t=e.sharedHooks.length>0,n=pI({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:fI(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function eJ(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=pI({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:fI(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function pI(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!hI.has(gI(t))).length+Math.min(e.functions.length,3)}function fI(e,t,n){let r=[...e,...t,...n].map(gI);return r.length>0&&r.every(i=>hI.has(i))}function gI(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function tJ(e){return e.actionTier==="signal"?.25:1}function nJ(e){return e.actionTier==="signal"?.25:1}function uI(e){return e.commitScope==="broad-sweep"?e.recency==="recent"?.25:0:e.commitScope==="mixed"?e.recency==="recent"?.5:.25:e.recency==="recent"?1:.5}function cp(e){return Math.round(e*100)/100}var hI=new Set(["add","apply","cancel","change","clear","close","create","delete","draft","edit","error","filter","form","load","loading","name","open","refresh","remove","reset","save","saving","search","select","selected","submit","toggle","update","value"]);function rJ(e,t,n,r={}){let i=cm(e,t,n,r);return i?{symbolA:i.symbolA,symbolB:i.symbolB,similarity:i.similarity,sharedCallees:i.sharedEvidence,uniqueToA:i.uniqueToA,uniqueToB:i.uniqueToB,consolidationStrategy:i.consolidationStrategy}:null}function iJ(e,t,n={}){let r=Qo(e,t,{families:["dataflow"],...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.maxEdges!==void 0?{maxEdges:n.maxEdges}:{}});return{kind:"value-flow",targets:r.targets,edges:r.edges,coverage:{status:r.coverage.status,basis:"proved-bounded-static-value-flow",analysisBasis:"partial-system-definition-use",providers:["bounded-static-value-flow","typescript-local-dependence"],supportedRelations:["compiler-identified local definitions reaching local reads through a TypeScript control-flow graph","right-hand-side local reads supplying assignments and declarations","candidate closure captures and bounded same-owner field flow with explicit evidence strength","direct argument-to-parameter forwarding at compiler-resolved calls","bounded mechanically derived static arguments","callee return value to a consumed compiler-resolved call result"],unsupportedRelations:["general heap alias and cross-instance field points-to flow","exceptional control and value flow","closure invocation order","downstream local definition-use after a call result","dynamic calls not resolved by the semantic provider"],graph:r.coverage}}}var oJ=/:\d+(?:-\d+)?$/u;function sJ(e,t,n={}){let r=n.direction??"backward",i=n.maxDepth??3;if(!Number.isSafeInteger(i)||i<0)throw new RangeError(`Dependence-slice depth must be a non-negative safe integer; received ${i}.`);let o=oJ.test(t),s=Qo(e,o?{locations:[t]}:{symbols:[t]},{families:["execution","runtime","dataflow","ownership"],maxDepth:i+1,maxEdges:n.maxEdges??200}),a=new Set(s.targets.flatMap(d=>d.nodeIds)),c=new Set(a),l=new Map;yI(s.edges,c,l,0);for(let d=1;d<=i;d+=1){let m=[];for(let p of s.edges)if(r==="backward"?c.has(p.to.id):c.has(p.from.id)){let f=r==="backward"?p.from.id:p.to.id;if(c.has(f))continue;m.push(f),l.set(p.id,d)}if(m.length===0)break;for(let p of m)c.add(p);yI(s.edges,c,l,d)}let u=s.edges.filter(d=>c.has(d.from.id)&&c.has(d.to.id)).filter(d=>l.has(d.id)||d.family==="ownership").map(d=>({...d,traversalDepth:l.get(d.id)??0,supporting:d.family!=="dataflow"&&!aJ(d)})).sort((d,m)=>d.traversalDepth-m.traversalDepth||d.family.localeCompare(m.family)||d.from.label.localeCompare(m.from.label)||d.to.label.localeCompare(m.to.label));return{kind:"dependence-slice",direction:r,criterion:t,targets:s.targets,nodeIds:[...c].sort(),edges:u,coverage:{status:s.coverage.status,criterionKind:o?"source-location-summary":"symbol-summary",basis:"partial-system-dependence-graph",analysisBasis:"typescript-cfg-reaching-definitions-plus-system-edges",providers:["typescript-local-dependence","bounded-static-value-flow"],graph:s.coverage,unsupportedRelations:["general heap alias and cross-instance field points-to flow","exceptional control and value flow","closure invocation order","downstream local definition-use after a call result","unresolved dynamic dispatch"]}}}function yI(e,t,n,r){let i=!0;for(;i;){i=!1;for(let o of e)o.family!=="ownership"||!t.has(o.from.id)||t.has(o.to.id)||(t.add(o.to.id),n.set(o.id,r),i=!0)}}function aJ(e){return e.semanticFamily==="control"&&e.sourceKind==="control-dependence"}function cJ(e,t={}){let{scope:n,limit:r}=t,i=new H(e),o=yJ([...lJ(e,n),...mJ(e,i,n)]);return bJ(o),r?o.slice(0,r):o}function lJ(e,t){let n=[];for(let r of uJ(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||ed(e,r.barrel_path)||W(e,r.barrel_path)&&Os(e,r.barrel_path).length===0)continue;let i=dJ(e,r),o=i?.barrel_consumers??0,s=i?.direct_consumers??0;o!==0||s!==0||n.push({barrelFile:r.barrel_path,symbol:r.symbol,shortName:T(r.symbol),originalFile:r.original_path,barrelConsumers:o,directConsumers:s,...SI(e,r.barrel_path)})}return n}function uJ(e,t){let n=t?"AND barrel_d.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`WITH barrel_refs AS MATERIALIZED (
|
|
460
|
-
SELECT DISTINCT
|
|
461
|
-
barrel_d.id AS barrel_doc_id,
|
|
462
|
-
barrel_d.relative_path AS barrel_path,
|
|
463
|
-
m.symbol_id
|
|
464
|
-
FROM documents barrel_d
|
|
465
|
-
JOIN chunks c ON c.document_id = barrel_d.id
|
|
466
|
-
JOIN mentions m ON m.chunk_id = c.id
|
|
467
|
-
WHERE m.role != 1
|
|
468
|
-
AND (barrel_d.relative_path LIKE '%/index.ts'
|
|
469
|
-
OR barrel_d.relative_path LIKE '%/index.js'
|
|
470
|
-
OR barrel_d.relative_path = 'index.ts'
|
|
471
|
-
OR barrel_d.relative_path = 'index.js')
|
|
472
|
-
${e.pathExclusionsFor("barrel_d")}
|
|
473
|
-
${n}
|
|
474
|
-
),
|
|
475
|
-
sym_def AS MATERIALIZED (
|
|
476
|
-
SELECT m2.symbol_id, c2.document_id
|
|
477
|
-
FROM barrel_refs br
|
|
478
|
-
-- Keep the bounded barrel-symbol set on the outer side. An ordinary
|
|
479
|
-
-- JOIN lets SQLite scan every definition mention before applying the
|
|
480
|
-
-- barrel-symbol bloom filter on large indexes.
|
|
481
|
-
CROSS JOIN mentions m2 ON m2.symbol_id = br.symbol_id
|
|
482
|
-
AND m2.role = 1
|
|
483
|
-
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
484
|
-
GROUP BY m2.symbol_id
|
|
485
|
-
)
|
|
486
|
-
SELECT DISTINCT
|
|
487
|
-
br.barrel_doc_id,
|
|
488
|
-
br.barrel_path,
|
|
489
|
-
gs.id AS symbol_id,
|
|
490
|
-
gs.symbol AS symbol,
|
|
491
|
-
orig_d.id AS original_doc_id,
|
|
492
|
-
orig_d.relative_path AS original_path
|
|
493
|
-
FROM barrel_refs br
|
|
494
|
-
JOIN global_symbols gs ON br.symbol_id = gs.id
|
|
495
|
-
JOIN sym_def ON sym_def.symbol_id = gs.id
|
|
496
|
-
JOIN documents orig_d ON sym_def.document_id = orig_d.id
|
|
497
|
-
WHERE orig_d.id != br.barrel_doc_id
|
|
498
|
-
${e.pathExclusionsFor("orig_d")}
|
|
499
|
-
${e.symbolNoiseFor("gs")}
|
|
500
|
-
-- Only function-level symbols (ending with ().), not module-level
|
|
501
|
-
AND gs.symbol LIKE '%().'
|
|
502
|
-
ORDER BY br.barrel_path, gs.symbol`,...r)}function dJ(e,t){return e.get(`SELECT
|
|
503
|
-
SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
|
|
504
|
-
SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
|
|
505
|
-
FROM (
|
|
506
|
-
SELECT
|
|
507
|
-
consumer_d.id AS consumer_doc_id,
|
|
508
|
-
MAX(CASE WHEN EXISTS (
|
|
509
|
-
SELECT 1
|
|
510
|
-
FROM mentions barrel_m
|
|
511
|
-
JOIN chunks barrel_c ON barrel_m.chunk_id = barrel_c.id
|
|
512
|
-
WHERE barrel_c.document_id = consumer_d.id
|
|
513
|
-
AND barrel_m.role != 1
|
|
514
|
-
AND barrel_m.symbol_id IN (
|
|
515
|
-
SELECT m2.symbol_id
|
|
516
|
-
FROM mentions m2
|
|
517
|
-
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
518
|
-
WHERE c2.document_id = ?
|
|
519
|
-
AND m2.role != 1
|
|
520
|
-
)
|
|
521
|
-
) THEN 1 ELSE 0 END) AS uses_barrel
|
|
522
|
-
FROM mentions ref_m
|
|
523
|
-
JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
|
|
524
|
-
JOIN documents consumer_d ON ref_c.document_id = consumer_d.id
|
|
525
|
-
WHERE ref_m.symbol_id = ?
|
|
526
|
-
AND ref_m.role != 1
|
|
527
|
-
AND consumer_d.id != ?
|
|
528
|
-
AND consumer_d.id != ?
|
|
529
|
-
${e.pathExclusionsFor("consumer_d")}
|
|
530
|
-
GROUP BY consumer_d.id
|
|
531
|
-
)`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function mJ(e,t,n){let r=[],i=hJ(e);for(let o of pJ(e,n))vI(i,o,o)>0||r.push(...fJ(e,t,o,i));return r}function pJ(e,t){return Z(e,{scope:t,includeIgnored:!1}).filter(n=>Os(e,n).length>0||Qi(e,n).length>0)}function fJ(e,t,n,r){let i=Os(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>bI(e,t,n,s.sourcePath,r,[gJ(s.specifier)])),o=Qi(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>bI(e,t,n,s.sourcePath,r,s.kind==="named"&&s.names.length>0?s.names:[s.kind==="star"?`* from ${s.sourcePath}`:`* namespace from ${s.sourcePath}`]));return[...i,...o]}function bI(e,t,n,r,i,o){let s=t.definitionsForFile(r);return o.map(a=>{let c=s.find(l=>l.leaf===a);return{barrelFile:n,symbol:c?.symbol??`source-reexport:${n}:${a}`,shortName:c?T(c.symbol):a,originalFile:r,barrelConsumers:0,directConsumers:vI(i,r,n),...SI(e,n)}})}function gJ(e){return e.split("::").at(-1)?.split("/").at(-1)?.replace(/\.[^.]+$/,"")??e}function SI(e,t){return Cn(e,t)?{actionTier:"signal",surfaceEvidence:["barrel file is declared on the package public surface"],recommendation:"Review the package API before removing this re-export; local consumers are zero, but external consumers may import through the public barrel."}:{actionTier:"direct",surfaceEvidence:[],recommendation:"Remove this unused re-export when the barrel is not part of an external API surface."}}function hJ(e){let t=new Map;for(let n of Z(e,{includeIgnored:!1}))for(let r of ae(e,n)){if(!r.sourcePath)continue;let i=t.get(r.sourcePath)??new Set;i.add(n),t.set(r.sourcePath,i)}return t}function vI(e,t,n){let r=e.get(t);return r?r.size-(r.has(n)?1:0):0}function yJ(e){let t=new Set,n=[];for(let r of e){let i=`${r.barrelFile}|${r.symbol}|${r.originalFile}`;t.has(i)||(t.add(i),n.push(r))}return n}function bJ(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function SJ(e,t={}){let{samples:n=50,scope:r,maxDisagreements:i=5}=t,o=new H(e),s=vJ(o.productionCallableDefinitions({scope:r,minLoc:2,requireFunctionLikeSymbol:!0}),n),a=CJ(e,s);if(s.length===0||!a)return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let c={references:CI(),callees:CI()},l=[],u=0,d=a==="semantic"?Ia(e,s):new Map,m=a==="source"?EJ(e,o,s):null;for(let p of s){let f=el(p,a==="semantic"?Ea(e,p).map(x=>x.file):[...m?.referencesBySymbolId.get(p.symbolId)??[]]),g=el(p,a==="semantic"?(d.get(p.symbolId)??[]).map(x=>x.file):[...m?.calleesBySymbolId.get(p.symbolId)??[]]);u+=1;let h=el(p,jn(e,p,{semanticEvidence:re}).map(x=>x.file)),b=el(p,(o.calleeMap([p],{semantic:!1}).get(p.symbolId)??[]).map(x=>x.file)),S=lp(a,"references"),y=lp(a,"callees");xI(c.references,p,"references",h,f,S,l),xI(c.callees,p,"callees",b,g,y,l)}return l.sort((p,f)=>f.cheapOnly.length+f.oracleOnly.length-(p.cheapOnly.length+p.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?dp(u/s.length):0,oracleKind:a,scores:["references","callees"].map(p=>RJ(p,c[p],a)),topDisagreements:l.slice(0,i)}}function CI(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0,skippedOraclePartial:0}}function vJ(e,t){let n=[...e].sort((o,s)=>o.symbolId-s.symbolId);if(n.length<=t)return n;let r=n.length/t,i=[];for(let o=0;o<t;o++)i.push(n[Math.floor(o*r)]);return i}function CJ(e,t){let n=t[0];if(!n)return null;if(up(e,n))return"source";try{if(st(e).capability("semantic-references",n.relativePath).available)return"semantic"}catch{}return t.some(r=>up(e,r))?"source":null}function el(e,t){let n=new Set;for(let r of t)r!==e.relativePath&&n.add(r);return n}function xI(e,t,n,r,i,o,s){if(!o&&i.size===0){e.skippedOraclePartial+=1;return}e.comparedSymbols+=1,e.cheapTotal+=r.size,e.oracleTotal+=i.size;let a=[],c=[];for(let l of r)i.has(l)?e.agreed+=1:a.push(l);for(let l of i)r.has(l)||c.push(l);(a.length>0||c.length>0)&&s.push({symbol:T(t.symbol),question:n,cheapOnly:a,oracleOnly:c})}var xJ={references:!0,callees:!1};function RJ(e,t,n){let r=t.oracleTotal>0?t.agreed/t.oracleTotal:1,i=t.cheapTotal-t.agreed,o=lp(n,e);return{question:e,comparedSymbols:t.comparedSymbols,precision:o&&t.cheapTotal>0?dp(t.agreed/t.cheapTotal):null,recall:dp(r),unverified:i,skippedOraclePartial:t.skippedOraclePartial}}function lp(e,t){return e==="semantic"?xJ[t]:!1}function up(e,t){return se(t.relativePath)==="clojure"&&K(e,t.relativePath)!==null}function EJ(e,t,n){let r=new Map,i=new Map,o=n.filter(c=>up(e,c)),s=new Map;for(let c of o){let l=s.get(c.leaf)??[];l.push(c),s.set(c.leaf,l)}for(let c of t.sourceFiles()){if(se(c)!=="clojure")continue;let l=K(e,c);if(l)for(let u of l.fileIdentifiers)for(let d of s.get(u)??[])RI(r,d.symbolId,c)}let a=new Map;for(let c of t.scopedDefinitions()){if(se(c.relativePath)!=="clojure")continue;let l=a.get(c.leaf)??[];l.push(c),a.set(c.leaf,l)}for(let c of o){let l=K(e,c.relativePath);if(l){for(let u of l.callSites)if(!(u.line<c.startLine||u.line>c.endLine))for(let d of a.get(u.calleeLeaf)??[])RI(i,c.symbolId,d.relativePath)}}return{referencesBySymbolId:r,calleesBySymbolId:i}}function RI(e,t,n){let r=e.get(t);if(r){r.add(n);return}e.set(t,new Set([n]))}function dp(e){return Math.round(e*1e3)/1e3}var IJ=new Set(Kt());function wJ(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o,maxShapeFrequency:s=12}=t,a=t.semantic!==!1,c=DJ(e,LJ(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:a,maxShapeFrequency:s}),l=TJ(c);return i?l.slice(0,i):l}function LJ(e,t){let n=Le(e,{scope:t.scope}).filter(r=>PJ(r)&&!e.isIgnored(r.relativePath)).filter(r=>ee(r)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((r,i)=>ee(i)-ee(r)||r.relativePath.localeCompare(i.relativePath)),he(n,t.scanLimit)}function PJ(e){return!e.isFunctionLike||je(e.symbol)?!1:e.kind===null||IJ.has(e.kind)}function DJ(e,t,n){let r=[];for(let s of t){let a=AJ(e,s,n);a&&r.push({signature:a,definition:s,fn:MJ(s)})}let i=new Map;for(let s of r)i.set(s.signature,(i.get(s.signature)??0)+1);let o=new Map;for(let s of r){let a=kJ(s.fn.loc),c=(i.get(s.signature)??0)>n.maxShapeFrequency,l=c?Um(e,s.definition):null;if(c&&!l)continue;let u=c?`${s.signature}\0body\0${l}`:`${s.signature}\0band\0${a}`,d=o.get(u)??{signature:s.signature,locBand:a,exactBody:c,functions:[]};d.functions.push(s.fn),o.set(u,d)}return[...o.values()]}function MJ(e){return{symbol:e.symbol,shortName:T(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:ee(e)}}function TJ(e){let t=[];for(let n of e)n.functions.length>=2&&t.push(n);return t.sort((n,r)=>{let i=r.functions.length-n.functions.length;if(i!==0)return i;let o=n.functions.reduce((a,c)=>a+c.loc,0);return r.functions.reduce((a,c)=>a+c.loc,0)-o}),t}function kJ(e){return e<=5?"<=5":e<=20?"6-20":">20"}function AJ(e,t,n){if(n.semantic){let o=Iy(e,t);if(o)return o}let r=FJ(t.documentation),i=r?OJ(r):null;return i||BJ(NJ(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function FJ(e){return oi(si(e))}function NJ(e,t,n,r,i){let o=W(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=jJ(s,n,r,i);for(let c of a){let l=Math.min(s.length-1,Math.max(c,c+4)),u="";for(let d=c;d<=l;d+=1){let m=s[d]?.trim();if(m&&(u=u?`${u} ${m}`:m,_J(u)))return u}if(u&&u.includes("("))return u}return null}function _J(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||cf(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function OJ(e){if(!e||!e.trim())return null;let t=e.replace(/^```\w*\s*/,"").replace(/\s*```$/,"").replace(/^\(method\)\s*/,"").replace(/^\(property\)\s*/,"").replace(/^\(function\)\s*/,"").replace(/^\(class\)\s*/,"").replace(/^\(interface\)\s*/,"").replace(/^\(enum\)\s*/,"").replace(/^\(type alias\)\s*/,"").replace(/^\(const\)\s*/,"").replace(/^\(var\)\s*/,"").trim(),n=t.indexOf("(");return n===-1||(t=t.slice(n),t=t.replace(/\s+/g,"").toLowerCase(),t.length<3)?null:t}function BJ(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),r=n.indexOf("(");if(r===-1)return null;let i=n.slice(0,r),s=new RegExp(`\\b${Ce(t)}\\b`,"i").exec(i);s&&typeof s.index=="number"&&(i=i.slice(0,s.index)),i=i.replace(/\b(public|private|protected|internal|final|static|abstract|sealed|virtual|override|async|suspend|inline|constexpr|consteval|constinit|const|pub|fn|function|def|sub|friend|shared|readonly|new|open|partial|export)\b/gi," ").replace(/\s+/g," ").trim();let a=$J(n.slice(r)).replace(/\)\s*=\s*[\s\S]*$/,")").replace(/\s+throws\s+[^={]+$/i,"").replace(/\s+where\s+.+$/i,"").replace(/\s+/g," ").trim();if(!a.startsWith("("))return null;let c=`${i?`${i} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return c.length>=3?c:null}function $J(e){let t=0,n=0,r=0,i=0,o=null,s=!1;for(let a=0;a<e.length;a+=1){let c=e[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c===o&&(o=null);continue}if(c==='"'||c==="'"||c==="`"){o=c;continue}if(c==="(")t+=1;else if(c===")")t=Math.max(0,t-1);else if(c==="[")r+=1;else if(c==="]")r=Math.max(0,r-1);else if(c==="<")i+=1;else if(c===">")i=Math.max(0,i-1);else if(c==="{"){if(t===0&&r===0&&i===0)return e.slice(0,a);n+=1}else if(c==="}")n=Math.max(0,n-1);else if(c==="="&&e[a+1]===">"&&t===0&&n===0&&r===0&&i===0)return e.slice(0,a)}return e}function jJ(e,t,n,r){let i=Ce(r),o=new RegExp(`\\b${i}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${i}\\b`,"i"),a=[],c=new Set,l=Math.max(0,Math.min(t,e.length-1)),u=Math.max(l,Math.min(e.length-1,Math.max(n,t+4)));for(let d=l;d<=u;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}for(let d=0;d<e.length;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}return a}import{spawnSync as Che}from"child_process";import{execFileSync as Kge}from"child_process";import{createHash as Vge}from"crypto";import{lstatSync as Jge,readlinkSync as Xge,readdirSync as Qge,realpathSync as Zge,statSync as ehe}from"fs";import{dirname as nhe,isAbsolute as rhe,join as ihe,posix as ohe,relative as she,resolve as ahe,sep as che}from"path";var uhe=512*1024*1024;function EI(e){return vr({version:e.version,...e.base?{base:e.base}:{},files:[...e.files].sort((t,n)=>t.path.localeCompare(n.path))})}function mp(e){return JSON.stringify({...e.clojureConfigPath?{clojureConfigPath:e.clojureConfigPath}:{},files:[...e.files].sort((t,n)=>t.path.localeCompare(n.path)).map(t=>({hash:t.hash,path:t.path,size:t.size})),languages:[...e.languages].sort(),pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),version:e.version})}var UJ="scip-query:collaboration-domain",qJ="scip-query:workspace-instance",GJ="scip-query:index-generation",zJ="scip-query:repository-content",II="scip-query:index-inputs",KJ="scip-query:index-inputs";function Vr(e){let t=e.snapshot,n=e.observedSourceKinds?new Set(e.observedSourceKinds):void 0,r=e.gitContext??t?.gitContext??(n?.has("live-workspace")?ml(e.projectRoot):void 0),i=e.collaborationDomainId??e.db?.config.collaborationDomainId,o=i?Tr(UJ,1,i):void 0,s=r?Tr(qJ,1,r.worktreeId):void 0,a=t?Tr(zJ,1,EI(t.repositoryContent)):void 0,c=t?Tr(II,t.indexInputs.version,mp(t.indexInputs)):void 0,l=e.db&&t?VJ(e.db.generation.metadataRaw):void 0,u=e.db?{generation:Tr(GJ,1,e.db.generation.identity),...l?{inputs:l}:{},source:e.db.generation.source}:void 0,d=n??new Set([...u?["index-generation"]:[],...a?["repository-snapshot"]:s?["live-workspace"]:[]]),m=[...u&&d.has("index-generation")?[{kind:"index-generation",identity:u.generation}]:[],...a&&d.has("repository-snapshot")?[{kind:"repository-snapshot",identity:a}]:[],...s&&d.has("live-workspace")?[{kind:"live-workspace",identity:s}]:[],...d.has("process")?[{kind:"process"}]:[]],p=[...u&&d.has("index-generation")?[{source:"index-generation",kind:u.source==="immutable"?"immutable":"not-established"}]:[],...a&&d.has("repository-snapshot")?[{source:"repository-snapshot",kind:"fixed-snapshot"}]:[],...s&&d.has("live-workspace")?[{source:"live-workspace",kind:"not-established"}]:[],...d.has("process")?[{source:"process",kind:"not-established"}]:[]];return m.length===0&&(m.push({kind:"process"}),p.push({source:"process",kind:"not-established"})),{schemaVersion:er,observedAt:(e.observedAt??(t?new Date(t.capturedAt):new Date)).toISOString(),facts:{...o?{collaborationDomain:o}:{},...s?{workspaceInstance:s}:{},...a?{wholeContent:a}:{},...c?{relevantInputs:[{subject:KJ,identity:c}]}:{},...u?{index:u}:{}},observedSources:m,stabilityProofs:p,...r?{diagnostics:{clean:r.clean,...r.headCommit?{headCommit:r.headCommit}:{},...r.treeOid?{treeOid:r.treeOid}:{}}}:{}}}function WJ(e){return Vr({projectRoot:e.projectRoot,db:e.db,...e.gitContext?{gitContext:e.gitContext}:{},...e.observedAt?{observedAt:e.observedAt}:{},observedSourceKinds:["index-generation"]})}function bhe(){let e=$a();if(!e)return Vr({projectRoot:Ba(),observedSourceKinds:["process"]});let t=e.config.projectRoot,n=ml(t);return WJ({projectRoot:t,db:e,...n?{gitContext:n}:{}})}function VJ(e){if(!e)return;let t=yr(e);if(t.kind!=="legacy"&&t.kind!=="supported")return;let n=Wi(t.metadata.fingerprint);return n&&Number.isSafeInteger(n.version)&&n.version>0?Tr(II,n.version,mp(n)):void 0}var fp="scip-query-isolated-analysis",gp=1;function YJ(e){let t=[...e??[]];return t.includes("--json")?t:["--json",...t]}var ln=class extends Error{constructor(n,r,i=!0){super(`${n} timed out after ${r}ms.`);this.label=n;this.timeoutMs=r;this.reaped=i;this.name="IsolatedProcessTimeoutError"}label;timeoutMs;reaped;timedOut=!0};function Dhe(e,t){let n=$a(),r={protocol:fp,schemaVersion:gp,producer:{name:"scip-query",version:hr},command:e,result:t,...n?{observationReceipt:Vr({projectRoot:n.config.projectRoot,db:n,observedSourceKinds:["index-generation"]})}:{}};Vu(JSON.stringify(r))}function wI(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function Es(e){let t=e.timeoutMs??Xf.analysis,n=e.maxBuffer??10*1024*1024;return Zf({command:process.execPath,args:[...process.execArgv,e.cliPath,e.command,...YJ(e.args)],cwd:process.cwd(),env:e.env??process.env,label:e.label,timeoutMs:t,maxStdoutBytes:n,maxStderrBytes:n}).catch(r=>{throw r instanceof Qf&&r.kind==="timeout"?new ln(e.label,t,r.reaped):r}).then(r=>{let i=r.stderr.trim();if(r.status!==0)throw new Error(`${e.label} failed${i?`:
|
|
532
|
-
${i}`:""}`);return JJ(r.stdout,e)})}function JJ(e,t){let n;try{n=JSON.parse(e)}catch(i){throw new Error(`${t.label} returned invalid JSON: ${i instanceof Error?i.message:i}`,{cause:i})}if(!Q(n))throw new Error(`${t.label} returned a non-object isolated-analysis message.`);if(n.protocol!==fp)throw new Error(`${t.label} returned protocol ${pp(n.protocol)}; expected ${fp}.`);if(n.schemaVersion!==gp)throw new Error(`${t.label} returned unsupported isolated-analysis schemaVersion ${pp(n.schemaVersion)}; expected ${gp}.`);if(!XJ(n.producer))throw new Error(`${t.label} did not identify a scip-query producer version.`);if(n.command!==t.command)throw new Error(`${t.label} returned result for command ${pp(n.command)}; expected ${t.command}.`);if(!Object.hasOwn(n,"result"))throw new Error(`${t.label} omitted the isolated-analysis result.`);let r=n.observationReceipt;if(r!==void 0&&(!La(r)||r.schemaVersion!==2))throw new Error(`${t.label} returned an invalid observation receipt.`);return{result:n.result,...r?{observationReceipt:r}:{}}}function XJ(e){return Q(e)&&e.name==="scip-query"&&typeof e.version=="string"&&e.version.length>0}function pp(e){return typeof e=="string"?JSON.stringify(e):String(e)}async function hp(e,t,n){let r=new Array(e.length),i=0;async function o(){for(;i<e.length;){let s=i++;r[s]=await n(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),r}function LI(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let o=t.find(a=>a.has(i));if(!o){n.add(i),r.push([i]);continue}let s=e.filter(a=>o.has(a));s.forEach(a=>n.add(a)),r.push(s)}return r}import{spawnSync as QJ}from"child_process";import{existsSync as ZJ,mkdirSync as e5,renameSync as t5,writeFileSync as n5}from"fs";import{dirname as PI,join as r5}from"path";var tl=5,i5="health-report-cache.json";function yp(e,t,n,r=c5()){let i=mn(e);return i?{version:tl,projectFingerprint:i,cliVersion:n,scope:t.scope??null,full:t.full===!0,phaseTimeoutMs:t.phaseTimeoutMs??null,gitHead:r.gitHead(e.config.projectRoot)}:null}function DI(e,t,n=AI()){let r=TI(e),i=kI(t),o=!1;return N("health.report-cache.read",()=>{if(!n.existsSync(r))return null;try{let s=JSON.parse(n.readFile(r));return!o5(s)||s.keyHash!==i?null:(o=!0,s.report)}catch{return null}},()=>({available:!0,hit:o,keyHash:i}))}function MI(e,t,n,r=AI()){let i=TI(e),o={version:tl,keyHash:kI(t),key:t,writtenAt:r.nowIso(),report:n};r.mkdirSync(PI(i),{recursive:!0});let s=`${i}.${process.pid}.${Date.now()}.tmp`;r.writeFileSync(s,JSON.stringify(o)),r.renameSync(s,i)}function TI(e){return r5(PI(e.config.dbPath),i5)}function kI(e){return qt(JSON.stringify(e))}function o5(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===tl&&typeof t.keyHash=="string"&&s5(t.key)&&typeof t.writtenAt=="string"&&a5(t.report)}function s5(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===tl&&typeof t.projectFingerprint=="string"&&typeof t.cliVersion=="string"&&(t.scope===null||typeof t.scope=="string")&&typeof t.full=="boolean"&&(t.phaseTimeoutMs===null||typeof t.phaseTimeoutMs=="number")&&(t.gitHead===null||typeof t.gitHead=="string")}function a5(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.score=="number"&&typeof t.riskScore=="number"&&typeof t.hygieneScore=="number"&&typeof t.overview=="object"&&typeof t.findings=="object"&&Array.isArray(t.scoreBreakdown)&&Array.isArray(t.actions)&&Array.isArray(t.pressure)&&Array.isArray(t.topComplexity)&&Array.isArray(t.detectorEvidence)}function c5(){return{gitHead(e){let t=QJ("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:3e4,killSignal:"SIGKILL"});return t.status===0?t.stdout.trim():null}}}function AI(){return{existsSync:ZJ,mkdirSync:e5,readFile:e=>Ve(e,"health report cache"),renameSync:t5,writeFileSync:n5,nowIso:()=>new Date().toISOString()}}var _I="__health-phase",u5="__health-semantic-prewarm",d5="__diff-impact-batch",m5=128,p5=1,f5=1,g5=25e3,h5=2500,bp=2500,y5=4,b5=12,FI=1,S5=6144,v5=10*6e4,C5=3e4,x5=8192,R5=10*6e4,OI=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),BI=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]),E5=new Set([...BI,"suppressions"]),I5=new Set(["similar","extract-candidates"]),nl=2,NI=Ji({kind:"health-semantic-prewarm",invalidation:$e("health-semantic-prewarm"),serialize:e=>JSON.stringify(e),deserialize:w5});function w5(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return n.version!==nl||typeof n.definitions!="number"||!Number.isFinite(n.definitions)||typeof n.referenceCacheWrites!="number"||!Number.isFinite(n.referenceCacheWrites)||typeof n.referenceIncomplete!="number"||!Number.isFinite(n.referenceIncomplete)||typeof n.calleeRows!="number"||!Number.isFinite(n.calleeRows)||typeof n.warmedAt!="number"||!Number.isFinite(n.warmedAt)?null:{version:nl,definitions:n.definitions,referenceCacheWrites:n.referenceCacheWrites,referenceIncomplete:n.referenceIncomplete,calleeRows:n.calleeRows,warmedAt:n.warmedAt}}catch{return null}}function nye(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
|
|
533
|
-
`)}function L5(e){let t=Ar(e);return t.symbols>=g5||t.documents>=h5}function rye(e,t,n,r={}){if(!L5(e))return{semantic:!0};if(n)return t==="dead"?(r.quiet||console.error("Large index detected; dead is scanning all candidates with semantic enrichment disabled to keep memory bounded."),{semantic:!1}):(r.quiet||console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0});if(!r.quiet){let i=t==="inspect"?"Use --full only when every omitted semantic candidate can change the decision; it does not override source or behavior materialization ceilings.":t==="dead"?'Run "scip-query dead --full" for an unbounded candidate scan; semantic enrichment remains disabled on large indexes to keep memory bounded.':`Run "scip-query ${t} --full" for the unbounded semantic pass.`;console.error(`Large index detected; ${t} is using its bounded default analysis with semantic enrichment disabled. Candidate scans, when this command uses one, are capped at ${bp}. `+i)}return{scanLimit:bp,semantic:!1,analysisBudget:{scanLimit:bp,semanticEnrichment:!1,reason:t==="dead"?"large index default budget; pass --full for an unbounded memory-safe candidate scan":"large index default budget; pass --full for unbounded semantic analysis"}}}var P5={env:process.env,projectFingerprint:mn,semanticEngineFingerprint:T5,readMarker:(e,t,n)=>NI.read(e,t,n),writeMarker:(e,t,n,r)=>NI.write(e,t,n,r),candidateDefinitions:(e,t)=>new H(e).scopedDefinitions(t.scope).filter(n=>He(n.relativePath)!==null),materializeReferences:(e,t,n)=>st(e).materializeReferences(t,n),materializeCallees:Tu,releaseSemanticMemory:e=>Vi(e,{groups:["semantic-provider"]})};function iye(e,t,n=P5){if(t.full!==!0)return fr("default-mode");if((n.env??process.env).SCIP_QUERY_HEALTH_SEMANTIC_PREWARM==="0")return fr("disabled");let r=fr("error");return N("health.semantic-prewarm",()=>{try{r=D5(e,t,n)}catch(i){r=fr("error",{error:i instanceof Error?i.message:String(i)})}return r},()=>k5(r))}function D5(e,t,n){let r=n.projectFingerprint(e);if(!r)return fr("missing-project-fingerprint");let i=M5(t,n.semanticEngineFingerprint(e)),o=n.readMarker(e,i,r);if(o&&o.referenceIncomplete===0)return fr("cache-hit");let s=[];if(s=N("health.semantic-prewarm.candidate-definitions",()=>(s=n.candidateDefinitions(e,t),s),()=>({definitions:s.length})),s.length===0)return fr("no-semantic-definitions");let a=0,c=N("health.semantic-prewarm.references",()=>{let m=n.materializeReferences(e,s,{prefetchCallees:!1});return a=m.cacheHits+m.cacheWrites+m.inMemoryHits,m},()=>({definitions:s.length,rows:a}));if(c.cacheHits+c.cacheWrites+c.inMemoryHits===0&&c.misses+c.unkeyed>0)return fr("provider-unavailable",{definitions:s.length,referenceMisses:c.misses});N("health.semantic-prewarm.release-reference-memory",()=>n.releaseSemanticMemory?.(e));let u=0,d=N("health.semantic-prewarm.callees",()=>{let m=n.materializeCallees(e,s);return u=m.size,m},()=>({definitions:s.length,rows:u}));return c.incomplete>0?{status:"partial",reason:"incomplete-references",definitions:s.length,referenceCacheHits:c.cacheHits,referenceCacheWrites:c.cacheWrites,referenceMisses:c.misses,referenceIncomplete:c.incomplete,calleeRows:d.size}:(N("health.semantic-prewarm.marker-write",()=>n.writeMarker(e,i,r,{version:nl,definitions:s.length,referenceCacheWrites:c.cacheWrites,referenceIncomplete:c.incomplete,calleeRows:d.size,warmedAt:Date.now()})),{status:"warmed",reason:"cache-miss",definitions:s.length,referenceCacheHits:c.cacheHits,referenceCacheWrites:c.cacheWrites,referenceMisses:c.misses,referenceIncomplete:c.incomplete,calleeRows:d.size})}function M5(e,t){return JSON.stringify({version:nl,cliVersion:hr,semanticEngineFingerprint:t,scope:e.scope??null})}function T5(e){return qt(JSON.stringify({kind:"health-semantic-prewarm-engine",rust:wr(e.config.projectRoot)}))}function fr(e,t={}){return{status:"skipped",reason:e,definitions:0,referenceCacheHits:0,referenceCacheWrites:0,referenceMisses:0,referenceIncomplete:0,calleeRows:0,...t}}function k5(e){return{status:e.status,reason:e.reason,definitions:e.definitions,referenceCacheHits:e.referenceCacheHits,referenceCacheWrites:e.referenceCacheWrites,referenceMisses:e.referenceMisses,referenceIncomplete:e.referenceIncomplete,calleeRows:e.calleeRows,error:e.error}}function vp(e){return zu(t=>{let n=Vr({projectRoot:t.config.projectRoot,db:t,observedSourceKinds:["index-generation"]});return{value:e(t),anchor:{database:{config:t.config,generation:t.generation},generationDigest:n.facts.index.generation.digest}}})}function rl(e,t,n){let r=e[0];if(!r)throw new Error("An evidence-bound analysis requires at least one index observation anchor.");let i=r.generationDigest,o=e.every(a=>a.generationDigest===i),s=t.every(a=>a?.facts.index?.generation.digest===i);return Vr({projectRoot:r.database.config.projectRoot,...o&&s?{db:r.database}:{},observedSourceKinds:n})}async function oye(e){return(await A5(e)).result}async function A5(e){let t=U5(e),n={...e,phaseTimeoutMs:t??null},r=vp(b=>{let S=yp(b,n,hr);if(!S)return null;let y=DI(b,S);return y||null});if(r.value)return{result:r.value,observationReceipt:rl([r.anchor],[],["index-generation","live-workspace"])};let i=vp(b=>({applicability:O5(b,e),overview:op(b,"overview",e)})),{applicability:o,overview:s}=i.value,a=[r.anchor,i.anchor],c=new Map;c.set("overview",s);let l=Qc.filter(b=>b==="overview"?!1:B5(b,o)?!0:(c.set(b,Yr(b)),!1)),u=$5(l),d=[],m;if(e.full)try{m=await F5(e)}catch(b){d.push(`Health semantic prewarm omitted: ${Cp(b)}.`)}let p=e.full?G5(u.length):q5(u.length),f=await hp(u,p,b=>j5(b,e,t));if(f.flatMap(b=>b.result).forEach(b=>{b.healthPhaseMeta&&d.push(e.full?`Health phase "${b.phase}" omitted after a bounded worker failure: ${b.healthPhaseMeta.reason}.`:`Health phase "${b.phase}" deferred: ${b.healthPhaseMeta.reason}. Run health --full for exhaustive analysis.`),c.set(b.phase,b)}),d.length>0){let b=c.get("overview");c.set("overview",{...b,warnings:[...b.warnings,...d]})}let h=sp(Qc.map(b=>c.get(b)));return zu(b=>{let S=yp(b,n,hr);S&&MI(b,S,h)}),{result:h,observationReceipt:rl(a,[m?.observationReceipt,...f.map(b=>b.observationReceipt)],["index-generation","live-workspace"])}}function F5(e){let t=process.argv[1]??il(import.meta.url),n=["--full"];return e.scope&&n.push("--scope",e.scope),Es({cliPath:t,command:u5,args:n,env:{...process.env,NODE_OPTIONS:`--max-old-space-size=${N5()}`},label:"Health semantic prewarm",timeoutMs:R5})}function N5(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_HEALTH_SEMANTIC_PREWARM_HEAP_MB??"",10);return Number.isSafeInteger(t)&&t>0?t:x5}function _5(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_HEALTH_FULL_PHASE_HEAP_MB??"",10);return Number.isSafeInteger(t)&&t>0?t:S5}function O5(e,t){return _s(e,{scope:t.scope})}function B5(e,t){return OI.has(e)?t.react:BI.has(e)?t.vue:!0}function $5(e){return LI(e,[OI,E5,I5])}function Yr(e){switch(e){case"react-component-duplicates":return{phase:e,reactComponentDuplicates:{count:0,loc:0,files:[]}};case"react-hook-candidates":return{phase:e,reactHookCandidates:{count:0,loc:0,files:[]}};case"react-large-component-pressure":return{phase:e,reactLargeComponentPressure:{count:0,loc:0,files:[]}};case"vue-component-duplicates":return{phase:e,vueComponentDuplicates:{count:0,loc:0,files:[]}};case"vue-composable-candidates":return{phase:e,vueComposableCandidates:{count:0,loc:0,files:[]}};case"vue-large-view-pressure":return{phase:e,vueLargeViewPressure:{count:0,loc:0,files:[]}};default:throw new Error(`Health phase "${e}" cannot be synthesized.`)}}function j5(e,t,n){if(e.length===1)return H5(e[0],t,n).then(s=>({result:[s.result],...s.observationReceipt?{observationReceipt:s.observationReceipt}:{}}));let r=e.join(","),i=process.argv[1]??il(import.meta.url),o=[r];return t.scope&&o.push("--scope",t.scope),t.full&&o.push("--full"),Es({cliPath:i,command:_I,args:o,...t.full?{env:$I()}:{},label:`Health phases "${r}"`,timeoutMs:n}).catch(s=>{if(!t.full&&!(s instanceof ln))throw s;let a=s instanceof ln?s.timeoutMs:n??0;return{result:e.map(c=>jI(c,a,s instanceof ln?`timed out after ${s.timeoutMs}ms`:Cp(s)))}})}function H5(e,t,n){let r=process.argv[1]??il(import.meta.url),i=[e];return t.scope&&i.push("--scope",t.scope),t.full&&i.push("--full"),Es({cliPath:r,command:_I,args:i,...t.full?{env:$I()}:{},label:`Health phase "${e}"`,timeoutMs:n}).catch(o=>{if(!t.full&&!(o instanceof ln))throw o;let s=o instanceof ln?o.timeoutMs:n??0;return{result:jI(e,s,o instanceof ln?`timed out after ${o.timeoutMs}ms`:Cp(o))}})}function Cp(e){let t=e instanceof Error?e.message:String(e);if(/heap out of memory|reaching memory limit/i.test(t))return"exceeded its isolated memory limit";let n=t.split(/\r?\n/,1)[0]?.trim()||"isolated worker failed";return n.length<=240?n:`${n.slice(0,237)}...`}function $I(e=process.env){return{...e,NODE_OPTIONS:`--max-old-space-size=${_5(e)}`}}function U5(e,t=process.env){let n=e.full?v5:C5,r=t.SCIP_QUERY_HEALTH_PHASE_TIMEOUT_MS;if(!r)return n;let i=parseInt(r,10);return!Number.isFinite(i)||i<0?n:i===0?void 0:i}function jI(e,t,n){let r={healthPhaseMeta:{status:"deferred",reason:n,timeoutMs:t}};switch(e){case"overview":throw new Error("Overview health phase cannot be deferred.");case"dead":return{phase:e,dead:{count:0,loc:0,files:[]},...r};case"isolated":return{phase:e,isolated:{count:0,loc:0,files:[]},...r};case"cycles":return{phase:e,realCycleCount:0,...r};case"similar":return{phase:e,similarCount:0,...r};case"duplicate-bodies":return{phase:e,duplicateBodies:{count:0,loc:0,files:[]},...r};case"twin-drift":return{phase:e,twinDrift:{count:0,loc:0,files:[]},...r};case"react-component-duplicates":return{...Yr(e),...r};case"react-hook-candidates":return{...Yr(e),...r};case"react-large-component-pressure":return{...Yr(e),...r};case"vue-component-duplicates":return{...Yr(e),...r};case"vue-composable-candidates":return{...Yr(e),...r};case"vue-large-view-pressure":return{...Yr(e),...r};case"extract-candidates":return{phase:e,extractCount:0,...r};case"wrapper-candidates":return{phase:e,wrappers:{count:0,loc:0,files:[]},...r};case"passthrough-candidates":return{phase:e,passthroughs:{count:0,loc:0,files:[]},...r};case"stale-abstractions":return{phase:e,stale:{count:0,loc:0,files:[],unused:0,singleUse:0},...r};case"drift":return{phase:e,drift:{count:0,unusedImports:0,architectureViolations:0,layerViolations:0,direct:0,signal:0},...r};case"complexity-hotspots":return{phase:e,complexity:{top:[],extremeCount:0},...r};case"git-evidence":return{phase:e,gitEvidence:null,...r};case"suppressions":return{phase:e,suppressions:{total:0,byCategory:{}},...r};case"coverage-contracts":return{phase:e,coverageContracts:{count:0,loc:0,files:[]},...r}}}var q5=xp({envKey:"SCIP_QUERY_HEALTH_CONCURRENCY",defaultMinimum:y5,defaultMaximum:b5}),G5=xp({envKey:"SCIP_QUERY_HEALTH_FULL_CONCURRENCY",defaultMinimum:FI,defaultMaximum:FI});function sye(e){if(console.log(`
|
|
534
|
-
Codebase Health Score: ${e.score}/100`),console.log(` Risk: ${e.riskScore}/100 (risk-oriented graph facts + change graph)`),console.log(` Hygiene: ${e.hygieneScore}/100 (tidiness candidates)
|
|
535
|
-
`),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${Ku(e.overview.indexSizeBytes)}
|
|
536
|
-
`),e.warnings&&e.warnings.length>0){console.log(" Warnings:");for(let n of e.warnings)console.log(` ${n}`);console.log("")}console.log(" Findings:");let t=e.findings;if(t.deadSymbols>0&&console.log(` Dead code: ${t.deadSymbols} symbols (${t.deadLoc} LOC)`),t.isolatedSymbols>0&&console.log(` Isolated symbols: ${t.isolatedSymbols} (${t.isolatedLoc} LOC)`),t.cycles>0&&console.log(` Circular deps: ${t.cycles}`),t.similarPairs>0&&console.log(` Similar pairs: ${t.similarPairs}`),t.twinDriftGroups>0&&console.log(` Drifted twins: ${t.twinDriftGroups} group(s)`),t.reactComponentDuplicatePairs>0&&console.log(` React components: ${t.reactComponentDuplicatePairs} duplicate pair(s)`),t.reactHookCandidatePairs>0&&console.log(` React hook reuse: ${Sp(t.reactHookCandidatePairs,t.reactHookCandidateScoreCount)} candidate pair(s)`),t.reactLargeComponentPressureFiles>0&&console.log(` React large comps: ${t.reactLargeComponentPressureFiles} component(s)`),t.vueComponentDuplicatePairs>0&&console.log(` Vue components: ${t.vueComponentDuplicatePairs} duplicate pair(s)`),t.vueComposableCandidatePairs>0&&console.log(` Vue composables: ${Sp(t.vueComposableCandidatePairs,t.vueComposableCandidateScoreCount)} candidate pair(s)`),t.vueLargeViewPressureFiles>0&&console.log(` Vue large views: ${t.vueLargeViewPressureFiles} file(s)`),t.extractionCandidates>0&&console.log(` Extract candidates: ${t.extractionCandidates}`),t.wrappers>0&&console.log(` Wrapper functions: ${Sp(t.wrappers,t.wrapperScoreCount)}`),t.passthroughs>0&&console.log(` Passthroughs: ${t.passthroughs}`),t.staleTypes>0&&console.log(` Stale abstractions: ${t.staleTypes}`),t.driftedFiles>0&&console.log(` Pattern drift: ${t.driftedFiles} files`),t.complexityHotspotCount>0&&console.log(` Complexity hotspots: ${t.complexityHotspotCount}`),e.actions.length>0){console.log(`
|
|
537
|
-
Prioritized Actions (highest impact + lowest effort first):`);for(let n=0;n<e.actions.length;n++){let r=e.actions[n],i=r.locRecoverable>0?` (~${r.locRecoverable} LOC involved)`:"";console.log(` ${n+1}. [${r.effort} effort / ${r.impact} impact] ${r.description}${i}`)}}if(e.topComplexity.length>0){console.log(`
|
|
538
|
-
Top Complexity Hotspots:`);for(let n of e.topComplexity)console.log(` ${n.score.toFixed(1).padStart(6)} ${n.symbol}`)}if(e.detectorEvidence.length>0){console.log(`
|
|
539
|
-
Detector Evidence Calibration:`);for(let n of e.detectorEvidence){let r=n.unavailableRequirements.length>0?`; unavailable: ${n.unavailableRequirements.join(", ")}`:"";console.log(` ${n.detector}: ${n.status}/${n.providerCoverage}${r}`)}console.log(" Full claims, non-claims, providers, and recovery commands are available in health --json.")}if(W5(e),K5(e),e.scoreBreakdown.length>0){console.log(`
|
|
540
|
-
Score Breakdown (100 minus the following):`);for(let n of e.scoreBreakdown)console.log(` -${String(n.points).padStart(2)} ${n.axis}: ${n.detail}`)}e.actions.length===0&&console.log(e.warnings&&e.warnings.length>0?`
|
|
541
|
-
No findings from completed analyses. Review warnings before interpreting this result as clean.`:`
|
|
542
|
-
No issues found. Codebase is clean.`)}function Sp(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${z5(t)} score-weighted)`}function z5(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function K5(e){if(e.pressure.length!==0){console.log(`
|
|
543
|
-
Maintenance Pressure:`);for(let t of e.pressure)console.log(` ${t.category}: ${t.count} / ${t.threshold} threshold (${t.ratio}x, -${t.extraPenalty} ${t.kind})`)}}function W5(e){let t=e.axes;if(console.log(`
|
|
544
|
-
Axes:`),console.log(` Zero-reference candidates: ${t.deletable.loc} LOC across ${t.deletable.symbols} symbols`),t.changeAmplification){let r=t.changeAmplification;console.log(` Change amplification: ${r.medianFilesPerCommit} files/commit median, ${r.p90FilesPerCommit} p90 (${r.commitsAnalyzed} commits)`)}if(t.hiddenCoupling&&t.hiddenCoupling.pairCount>0){console.log(` Hidden coupling: ${t.hiddenCoupling.pairCount} co-changing pair(s) without a dependency edge`);for(let r of t.hiddenCoupling.top.slice(0,3))console.log(` ${r.fileA} <-> ${r.fileB} (${r.together}x together, ${Math.round(r.confidence*100)}%)`)}if(t.churnWeightedComplexity&&t.churnWeightedComplexity.length>0){let r=t.churnWeightedComplexity[0];r.weighted>0&&console.log(` Churn x complexity: hottest is ${r.symbol} (${r.changes} changes, weighted ${r.weighted})`)}let n=t.evidenceQuality;if(console.log(` Evidence quality: ${n.graphFindings} graph-fact finding(s), ${n.heuristicFindings} heuristic finding(s), ${n.userSuppressed} user-suppressed`),e.validation&&e.validation.flaggedFiles>0){let r=e.validation,i=r.ratio===null?"n/a":`${r.ratio}x`;console.log(` Validation: flagged files fix-density ${r.flaggedFixDensity} vs baseline ${r.baselineFixDensity} (${i})`),console.log(` fix-commit signal: subject-keyword heuristic over ${r.validationBasis.commitsScanned} commits`)}}async function aye(e){let t=vp(o=>{let s=qi(o,{base:e.base});return s.note?{kind:"complete",result:Ac(o,{base:e.base})}:s.changedFiles.length===0?{kind:"complete",result:Ac(o,{base:e.base})}:{kind:"batched",plan:s}}),n=t.value;if(n.kind==="complete")return{result:n.result,observationReceipt:rl([t.anchor],[],["index-generation","live-workspace"])};let r=Y5(n.plan.changedFiles),i=await hp(r,V5(r.length),o=>Q5(o,e));return{result:Fc(n.plan.changedFiles,i.map(o=>o.result)),observationReceipt:rl([t.anchor],i.map(o=>o.observationReceipt),["index-generation","live-workspace"])}}var V5=xp({envKey:"SCIP_QUERY_DIFF_IMPACT_CONCURRENCY",defaultMinimum:p5,defaultMaximum:f5});function Y5(e){return wI(e,m5)}function xp(e){return(t,n=process.env,r=l5)=>J5(t,n,r,e)}function J5(e,t,n,r){let i=t[r.envKey],o=X5(n,r),s=i?parseInt(i,10):o;return!Number.isFinite(s)||s<1?Math.min(o,e):Math.min(s,e)}function X5(e,t){let n=e(),r=Number.isFinite(n)?Math.max(t.defaultMinimum,n-1):0;return Math.min(t.defaultMaximum,Math.max(t.defaultMinimum,r))}function Q5(e,t){let n=process.argv[1]??il(import.meta.url),r=[];return t.base&&r.push("--base",t.base),Es({cliPath:n,command:d5,args:r,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch"})}function cye(e){console.log(`Changed files: ${e.summary.totalChangedFiles}`),console.log(`Changed symbols: ${e.summary.totalChangedSymbols}`),console.log(`Affected consumer files: ${e.summary.totalAffectedFiles}`),e.summary.note&&console.log(`Note: ${e.summary.note}`);for(let n of e.evidenceTiers.filter(r=>r.state==="failed"))console.log(`WARNING: ${n.tier} evidence failed for ${n.attemptedSymbols} candidate symbol(s): ${n.reason}`);let t=e.attributionNotes.filter(n=>n.method==="unattributed");if(t.length>0){let n=[...new Set(t.map(r=>r.file))];for(let r of n){let i=t.filter(o=>o.file===r).length;console.log(`note: ${i} changed line-range(s) in ${r} belong to no indexed symbol`)}}console.log(""),e.changedSymbols.length>0&&(console.log("Changed symbols:"),Ju.list(e.changedSymbols,n=>` ${n.file} ${n.shortName} (fan-in: ${n.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
|
|
545
|
-
Affected consumer files:`),Ju.list(e.affectedConsumers,n=>` ${n.file} (${n.consumedSymbols} symbol(s))`))}import{AsyncLocalStorage as Z5}from"async_hooks";import{createHash as Ep}from"crypto";import{existsSync as eX,mkdirSync as tX}from"fs";import{tmpdir as nX}from"os";import{isAbsolute as rX,join as qI,resolve as GI}from"path";var Rp=2,iX="SCIP_QUERY_SESSION",HI="SCIP_QUERY_SESSION_DIR",oX=128,Ki=new Z5;function Cye(e,t){let n=e.sessionEnabled===!1||e.json?void 0:SX(),r={enabled:n!==void 0,reemit:e.reemit===!0,command:e.command,projectRoot:GI(e.cwd),sessionIdentity:n,staged:[],stagedEvidence:[],finalized:!1};return Ki.run(r,t)}function xye(e){let t=Ki.getStore();!t||t.finalized||(t.generationIdentity=e)}function Rye(e){let t=Ki.getStore();if(!t||t.finalized)return;t.finalized=!0;let n=t.state;if(!n){t.staged.length=0,t.stagedEvidence.length=0;return}try{if(e&&(t.staged.length>0||t.stagedEvidence.length>0)){let r=n.ledger.nextOrdinal,i=fX(t.staged).map(s=>({...s,ordinal:r,command:t.command})),o=hX(t.stagedEvidence).map(s=>({...s,ordinal:r,command:t.command}));n.ledger.ranges.push(...i),n.ledger.evidence.push(...o),n.ledger.nextOrdinal+=1,n.ledger.updatedAt=new Date().toISOString(),Cr(n.ledgerPath,n.ledger,{spacing:2,trailingNewline:!0})}}catch{}finally{n.lock.release(),t.state=null,t.staged.length=0,t.stagedEvidence.length=0}}function Eye(e){let t=e.source.split(`
|
|
546
|
-
`);if(t.length===0)return"";let n=sX(e.relativePath,e.startLine,t,e.ownerSymbol,e.sessionPolicy??"exact-unit"),r=e.indent??" ",i=e.sourceIndent??" ",o=e.focusLines??new Set;return n.map(s=>{let a=Yu(e.relativePath,s.startLine,s.endLine);if(s.kind==="covered"){let u=s.ordinal===null?"this command":`session #${s.ordinal} via ${s.command}`;return[`${r}${a} [source previously emitted: ${u}; not repeated]`,...e.afterHeader??[]].join(`
|
|
547
|
-
`)}let c=e.headerSuffix??"",l=s.lines.map((u,d)=>{let m=s.startLine+d,p=e.showFocusMarker===!1?"":o.has(m)?">":" ",f=e.lineNumberWidth??5;return`${i}${p}${String(ja(m)).padStart(f)} ${u}`});return[`${r}${a}${c}`,...e.blankAfterHeader?[""]:[],...e.afterHeader??[],...l].join(`
|
|
548
|
-
`)}).join(`
|
|
549
|
-
`)}function Iye(e){let t=Ki.getStore();if(!t||!t.enabled)return e.content;let n=Ip(t);if(!n)return e.content;let r=zI(e.content),i=ol(n.ledger.evidence,o=>o.kind===e.kind&&o.identity===e.identity&&o.contentHash===r);if(i&&!t.reemit){let o=e.label?`; ${UI(e.label)}`:"";return`${e.indent??""}[${e.kind} evidence previously emitted: receipt ${i.receiptId}; session #${i.ordinal} via ${i.command}${o}; not repeated]`}return t.stagedEvidence.push({kind:e.kind,identity:e.identity,contentHash:r,receiptId:vX(e.kind,e.identity,r),...e.label?{label:UI(e.label)}:{}}),e.content}function wye(e=!1){let t=Ki.getStore();if(!t?.enabled)return{enabled:!1,reason:"No explicit SCIP_QUERY_SESSION is active; source packets render independently.",uniqueLines:0,evidenceItems:0,emissions:0,rows:[]};let n=Ip(t);if(!n)return{enabled:!1,reason:"The exploration-session ledger was unavailable or contended; evidence output is fail-open for this command.",uniqueLines:0,evidenceItems:0,emissions:0,rows:[]};if(e){n.ledger.ranges=[],n.ledger.evidence=[],n.ledger.nextOrdinal=1,n.ledger.updatedAt=new Date().toISOString();try{Cr(n.ledgerPath,n.ledger,{spacing:2,trailingNewline:!0})}catch{return{enabled:!1,reason:"The exploration-session ledger could not be reset; evidence output remains fail-open.",uniqueLines:0,evidenceItems:0,emissions:0,rows:[]}}}let r=new Map;for(let a of n.ledger.ranges){let c=r.get(a.ordinal)??[];c.push(a),r.set(a.ordinal,c)}let i=new Map;for(let a of n.ledger.evidence){let c=i.get(a.ordinal)??[];c.push(a),i.set(a.ordinal,c)}let s=[...new Set([...r.keys(),...i.keys()])].sort((a,c)=>a-c).map(a=>{let c=r.get(a)??[],l=i.get(a)??[],u=c[0]?.command??l[0]?.command??"unknown",d=c.length===0?null:(()=>{let f=c.slice(0,8).map(h=>Yu(h.relativePath,h.startLine,h.endLine)).join(", "),g=c.length>8?`, ... ${c.length-8} more range(s)`:"";return` #${a} ${u}: ${f}${g}`})();if(l.length===0)return d;let m=l.slice(0,8).map(f=>`${f.receiptId} ${f.kind}${f.label?` ${f.label}`:""}`).join(", "),p=l.length>8?`, ... ${l.length-8} more item(s)`:"";return d?`${d}
|
|
550
|
-
evidence: ${m}${p}`:` #${a} ${u}: ${m}${p}`});return{enabled:!0,uniqueLines:yX(n.ledger.ranges),evidenceItems:n.ledger.evidence.length,emissions:new Set([...r.keys(),...i.keys()]).size,rows:s}}function sX(e,t,n,r,i){let o=Ki.getStore(),s=t+n.length-1;if(!o)return[{kind:"source",startLine:t,endLine:s,lines:[...n]}];let c=(o.enabled?Ip(o):null)?.ledger.ranges??[],l=n.map(zI),u=i==="exact-unit"&&!o.reemit?ol(c,h=>h.policy==="exact-unit"&&h.relativePath===e&&h.startLine===t&&h.endLine===s&&h.ownerSymbol===r&&CX(h.lineHashes,l)):void 0;if(u)return[{kind:"covered",startLine:t,endLine:s,ordinal:u.ordinal,command:u.command}];let d=i==="exact-unit"&&!o.reemit?cX(c,e,t,s,l):void 0;if(d)return[{kind:"covered",startLine:t,endLine:s,ordinal:d.ordinal,command:d.command}];let m=n.map((h,b)=>aX(c,e,t+b,l[b]));if(!(i==="preview"&&!o.reemit&&m.every(h=>h!==void 0)))return o.staged.push({relativePath:e,startLine:t,endLine:s,ownerSymbol:r,policy:i,lineHashes:l}),[{kind:"source",startLine:t,endLine:s,lines:[...n]}];let f=[],g=0;for(;g<n.length;){let h=m[g],b=g;for(;b+1<n.length&&lX(h,m[b+1]);)b+=1;let S=t+g,y=t+b;f.push({kind:"covered",startLine:S,endLine:y,ordinal:h.ordinal,command:h.command}),g=b+1}return f}function aX(e,t,n,r){let i=ol(e,o=>o.relativePath===t&&o.startLine<=n&&n<=o.endLine&&o.lineHashes[n-o.startLine]===r);if(i)return{ordinal:i.ordinal,command:i.command}}function cX(e,t,n,r,i){let o=ol(e,s=>s.policy==="exact-unit"&&s.relativePath===t&&s.startLine<=n&&s.endLine>=r&&i.every((a,c)=>s.lineHashes[n-s.startLine+c]===a));return o?{ordinal:o.ordinal,command:o.command}:void 0}function lX(e,t){return!e||!t?e===t:e.ordinal===t.ordinal&&e.command===t.command}function Ip(e){if(e.state!==void 0)return e.state;if(!e.sessionIdentity||!e.generationIdentity)return e.state=null,null;try{let t=bX();tX(t,{recursive:!0,mode:448});let n=Ep("sha256").update(e.projectRoot).update("\0").update(e.generationIdentity).update("\0").update(e.sessionIdentity).digest("hex"),r=qI(t,`${n}.json`),i=ui(`${r}.lock`,{kind:"source-emission-session",detail:{session:n.slice(0,12)}});if(i.kind!=="acquired")return e.state=null,null;let o;try{o=eX(r)?dX(JSON.parse(Ve(r,"source emission session ledger")),{projectRoot:e.projectRoot,generationIdentity:e.generationIdentity,sessionIdentity:e.sessionIdentity}):uX(e)}catch{return i.lock.release(),e.state=null,null}return e.state={ledgerPath:r,lock:i.lock,ledger:o},e.state}catch{return e.state=null,null}}function uX(e){return{version:Rp,projectRoot:e.projectRoot,generationIdentity:e.generationIdentity,sessionIdentity:e.sessionIdentity,nextOrdinal:1,updatedAt:new Date().toISOString(),ranges:[],evidence:[]}}function dX(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid source emission ledger.");let n=e;if(e.version===1&&n.projectRoot===t.projectRoot&&n.generationIdentity===t.generationIdentity&&n.sessionIdentity===t.sessionIdentity&&Number.isSafeInteger(n.nextOrdinal)&&(n.nextOrdinal??0)>0)return{version:Rp,projectRoot:t.projectRoot,generationIdentity:t.generationIdentity,sessionIdentity:t.sessionIdentity,nextOrdinal:n.nextOrdinal,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:new Date().toISOString(),ranges:[],evidence:[]};if(n.version!==Rp||n.projectRoot!==t.projectRoot||n.generationIdentity!==t.generationIdentity||n.sessionIdentity!==t.sessionIdentity||!Number.isSafeInteger(n.nextOrdinal)||(n.nextOrdinal??0)<=0||!Array.isArray(n.ranges)||!n.ranges.every(mX)||!Array.isArray(n.evidence)||!n.evidence.every(pX))throw new Error("Invalid source emission ledger.");return n}function mX(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.relativePath=="string"&&t.relativePath!==""&&Number.isSafeInteger(t.startLine)&&(t.startLine??-1)>=0&&Number.isSafeInteger(t.endLine)&&(t.endLine??-1)>=(t.startLine??0)&&Number.isSafeInteger(t.ordinal)&&(t.ordinal??0)>0&&typeof t.command=="string"&&t.command!==""&&(t.policy==="exact-unit"||t.policy==="preview")&&Array.isArray(t.lineHashes)&&t.lineHashes.length===(t.endLine??0)-(t.startLine??0)+1&&t.lineHashes.every(Zr)&&(t.ownerSymbol===void 0||typeof t.ownerSymbol=="string")}function pX(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return(t.kind==="unit"||t.kind==="edge")&&typeof t.identity=="string"&&t.identity!==""&&typeof t.contentHash=="string"&&Zr(t.contentHash)&&typeof t.receiptId=="string"&&/^ev-[0-9a-f]{12}$/u.test(t.receiptId)&&Number.isSafeInteger(t.ordinal)&&(t.ordinal??0)>0&&typeof t.command=="string"&&t.command!==""&&(t.label===void 0||typeof t.label=="string")}function fX(e){let t=[...e].sort((r,i)=>r.relativePath.localeCompare(i.relativePath)||r.startLine-i.startLine||r.endLine-i.endLine),n=[];for(let r of t){let i=n[n.length-1];if(i&&i.relativePath===r.relativePath&&i.ownerSymbol===r.ownerSymbol&&i.policy===r.policy&&r.startLine<=i.endLine+1&&gX(i,r)){let o=r.startLine-i.startLine;for(let s=0;s<r.lineHashes.length;s+=1)i.lineHashes[o+s]??=r.lineHashes[s];i.endLine=Math.max(i.endLine,r.endLine)}else n.push({...r,lineHashes:[...r.lineHashes]})}return n}function gX(e,t){let n=Math.max(e.startLine,t.startLine),r=Math.min(e.endLine,t.endLine);for(let i=n;i<=r;i+=1)if(e.lineHashes[i-e.startLine]!==t.lineHashes[i-t.startLine])return!1;return!0}function hX(e){let t=new Set,n=[];for(let r of e){let i=`${r.kind}\0${r.identity}\0${r.contentHash}`;t.has(i)||(t.add(i),n.push(r))}return n}function yX(e){let t=new Map;for(let r of e){let i=t.get(r.relativePath)??[];i.push(r),t.set(r.relativePath,i)}let n=0;for(let r of t.values()){r.sort((s,a)=>s.startLine-a.startLine||s.endLine-a.endLine);let i=-1,o=-1;for(let s of r)i<0?(i=s.startLine,o=s.endLine):s.startLine<=o+1?o=Math.max(o,s.endLine):(n+=o-i+1,i=s.startLine,o=s.endLine);i>=0&&(n+=o-i+1)}return n}function bX(){let e=process.env[HI];if(!e)return qI(nX(),`scip-query-source-sessions-${process.getuid?.()??"user"}`);if(!rX(e))throw new Error(`${HI} must be an absolute path.`);return GI(e)}function SX(){let e=process.env[iX]?.trim();if(e&&!(e.length>oX||!/^[A-Za-z0-9._:-]+$/.test(e)))return`explicit:${e}`}function vX(e,t,n){return`ev-${Ep("sha256").update(e).update("\0").update(t).update("\0").update(n).digest("hex").slice(0,12)}`}function UI(e){let t=e.replace(/[\r\n\t]+/gu," ").replace(/\s+/gu," ").trim();return t.length<=160?t:`${t.slice(0,157)}...`}function zI(e){return Ep("sha256").update(e).digest("hex")}function CX(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function ol(e,t){for(let n=e.length-1;n>=0;n-=1){let r=e[n];if(t(r))return r}}import{createHash as xX}from"crypto";import{existsSync as Lp,mkdirSync as RX,rmSync as EX}from"fs";import{tmpdir as IX}from"os";import{isAbsolute as wX,join as WI,resolve as sl}from"path";var VI=1,LX="SCIP_QUERY_SESSION",KI="SCIP_QUERY_SESSION_DIR",PX=128,YI=8,JI=32768,al=new Map;function Nye(e,t,n=!0){if(!n)return;let r=cl();if(!r)return;let i=Mp(e),o=t.map(a=>a.trim()).filter(a=>a.startsWith("scip-query system-map ")&&a.length<=JI).slice(0,YI),s=XI(i,r);o.length===0?al.delete(s):al.set(s,o)}function _ye(e,t,n,r=!0,i){if(!r||e!=="anchors"&&e!=="system-map")return;let o=cl();if(!o)return;let s=Mp(t),a=Dp(s,o);if(e==="system-map"){n?EX(a,{force:!0}):Lp(a)&&i&&wp(a,()=>{let c=Pp(a,s,o);c&&Cr(a,{...c,pendingMapContinuation:i,mapExecution:void 0,updatedAt:new Date().toISOString()},{spacing:2,trailingNewline:!0})});return}wp(a,()=>{let c=DX(s,o),l={version:VI,projectRoot:s,sessionIdentity:o,mapRequired:!0,...c.length>0?{recommendedMapCommands:c}:{},updatedAt:new Date().toISOString()};Cr(a,l,{spacing:2,trailingNewline:!0})})}function Oye(e,t=!0){if(!t)return;let n=cl();if(!n)return;let r=Mp(e),i=Dp(r,n);Lp(i)&&wp(i,()=>{let o=Pp(i,r,n);if(o){if(o.pendingMapContinuation)throw new Error(["MAP TRANSPORT INCOMPLETE","The selected system map has already been computed. Restarting it would repeat the same repository work.",`Continue exactly: ${o.pendingMapContinuation}`].join(`
|
|
551
|
-
`));if(o.mapExecution&&MX(o.mapExecution.processId))throw new Error(["NAVIGATION MAP ALREADY RUNNING","A selected system map is already computing in this SCIP_QUERY_SESSION.","Poll the existing terminal execution. Do not launch a duplicate map or inspect in parallel."].join(`
|
|
552
|
-
`));Cr(i,{...o,mapExecution:{processId:process.pid,startedAt:new Date().toISOString()},updatedAt:new Date().toISOString()},{spacing:2,trailingNewline:!0})}})}function Bye(e,t,n=!0){if(!n)return;let r=cl();if(!r)return;let i=Dp(sl(e),r);if(!Lp(i))return;let o=Pp(i,sl(e),r);if(!o?.mapRequired)return;let s=o.recommendedMapCommands?.length?["This refusal is a recoverable protocol step, not evidence that the requested code cannot be explored.","Run exactly one of the ranked map commands below, then finish every emitted continuation:",...o.recommendedMapCommands.map((a,c)=>` [${c+1}] ${a}`)]:[`Do not retry ${t}. Run one printed next-abstraction system-map command and finish every emitted continuation first.`];throw new Error(["NAVIGATION MAP REQUIRED","An anchors locator completed in this SCIP_QUERY_SESSION, but its selected system map has not reached transport completion.",`Do not retry ${t}.`,...s,"The map must complete before the agent can choose source detail; map and detail exploration cannot run concurrently."].join(`
|
|
553
|
-
`))}function Pp(e,t,n){try{let r=JSON.parse(Ve(e,"navigation session state"));return r.version===VI&&r.projectRoot===t&&r.sessionIdentity===n&&r.mapRequired===!0&&(r.recommendedMapCommands===void 0||Array.isArray(r.recommendedMapCommands)&&r.recommendedMapCommands.length<=YI&&r.recommendedMapCommands.every(i=>typeof i=="string"&&i.startsWith("scip-query system-map ")&&i.length<=JI))&&(r.pendingMapContinuation===void 0||typeof r.pendingMapContinuation=="string")&&(r.mapExecution===void 0||typeof r.mapExecution=="object"&&r.mapExecution!==null&&Number.isSafeInteger(r.mapExecution.processId)&&typeof r.mapExecution.startedAt=="string")?r:null}catch{return null}}function DX(e,t){let n=XI(e,t),r=al.get(n)??[];return al.delete(n),r}function XI(e,t){return`${e}\0${t}`}function MX(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Dp(e,t){let n=TX();RX(n,{recursive:!0,mode:448});let r=xX("sha256").update(e).update("\0").update(t).digest("hex");return WI(n,`navigation-${r}.json`)}function TX(){let e=process.env[KI];if(!e)return WI(IX(),`scip-query-source-sessions-${process.getuid?.()??"user"}`);if(!wX(e))throw new Error(`${KI} must be an absolute path.`);return sl(e)}function Mp(e){let t=process.env.SCIP_QUERY_PROJECT_ROOT?.trim();return sl(t||e)}function cl(){let e=process.env[LX]?.trim();if(e&&!(e.length>PX||!/^[A-Za-z0-9._:-]+$/u.test(e)))return`explicit:${e}`}function wp(e,t){let n=ui(`${e}.lock`,{kind:"navigation-session",detail:{state:e.slice(-17,-5)}});if(n.kind!=="acquired")throw new Error("Navigation session state is busy. Retry the completed command.");try{t()}finally{n.lock.release()}}export{kr as a,ro as b,Kt as c,fg as d,e4 as e,pa as f,IQ as g,uD as h,Ci as i,cy as j,G6 as k,Ar as l,cA as m,bA as n,xF as o,Bo as p,ig as q,K4 as r,$o as s,jo as t,nc as u,$S as v,B0 as w,aN as x,QZ as y,pne as z,pN as A,SN as B,Bt as C,_e as D,mv as E,mO as F,PB as G,Qo as H,Yd as I,XB as J,zr as K,j$ as L,q$ as M,G$ as N,z$ as O,ij as P,aj as Q,cj as R,lj as S,dj as T,mj as U,pj as V,nx as W,ts as X,nm as Y,_j as Z,ns as _,$j as $,jj as aa,Wj as ba,Qj as ca,Zj as da,e1 as ea,is as fa,cm as ga,os as ha,iH as ia,ss as ja,as as ka,um as la,cs as ma,ls as na,dm as oa,JH as pa,us as qa,nq as ra,Pq as sa,vm as ta,$q as ua,qi as va,vR as wa,SG as xa,ms as ya,Jz as za,fs as Aa,SK as Ba,gs as Ca,uW as Da,dW as Ea,SW as Fa,AW as Ga,jW as Ha,rV as Ia,Km as Ja,kE as Ka,Wm as La,AE as Ma,Kc as Na,AV as Oa,vs as Pa,Cs as Qa,xs as Ra,U2 as Sa,q2 as Ta,G2 as Ua,rp as Va,Qc as Wa,op as Xa,RY as Ya,rJ as Za,iJ as _a,sJ as $a,cJ as ab,SJ as bb,wJ as cb,gM as db,i8 as eb,Pa as fb,Mo as gb,Yy as hb,T8 as ib,k8 as jb,A8 as kb,F8 as lb,N8 as mb,_8 as nb,X8 as ob,Qy as pb,Q8 as qb,Zy as rb,eb as sb,_a as tb,FT as ub,NT as vb,_T as wb,OT as xb,nb as yb,Ba as zb,S9 as Ab,$a as Bb,rb as Cb,v9 as Db,C9 as Eb,x9 as Fb,R9 as Gb,qT as Hb,zu as Ib,E9 as Jb,Ku as Kb,I9 as Lb,L9 as Mb,P9 as Nb,D9 as Ob,M9 as Pb,ib as Qb,Mt as Rb,Vu as Sb,T9 as Tb,Vr as Ub,bhe as Vb,Dhe as Wb,ja as Xb,QT as Yb,Yu as Zb,F9 as _b,Ju as $b,_I as ac,u5 as bc,d5 as cc,nye as dc,rye as ec,iye as fc,oye as gc,A5 as hc,sye as ic,aye as jc,cye as kc,Cye as lc,xye as mc,Rye as nc,Eye as oc,Iye as pc,wye as qc,Nye as rc,_ye as sc,Oye as tc,Bye as uc};
|
|
554
|
-
//# sourceMappingURL=chunk-Z67JOKRE.js.map
|