scip-query 0.20.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +69 -0
- package/README.md +255 -884
- package/dist/augment-vue-worker.js +1 -1
- package/dist/by-kind-CI3O6PQG.js +2 -0
- package/dist/call-graph-6QTUTXH7.js +2 -0
- package/dist/call-graph-evidence-lZa2dwQA.d.ts +11 -0
- package/dist/change-analysis-types-CCtoCHbC.d.ts +9 -0
- package/dist/chunk-26CT72HM.js +2 -0
- package/dist/{chunk-7PIO7NKH.js → chunk-2COFMIVK.js} +2 -2
- package/dist/chunk-2H4IAJHO.js +2 -0
- package/dist/chunk-2I3RSUWX.js +16 -0
- package/dist/chunk-2RP27XLR.js +2 -0
- package/dist/chunk-2ZBMOQGG.js +3 -0
- package/dist/{chunk-HX4GQPZP.js → chunk-32A42O5B.js} +3 -3
- package/dist/chunk-35ELD3RM.js +2 -0
- package/dist/chunk-35IW3P4H.js +2 -0
- package/dist/{chunk-DQGFVPUV.js → chunk-3653GTR7.js} +3 -3
- package/dist/chunk-3EX7DNBC.js +2 -0
- package/dist/chunk-3FQ3KMCD.js +2 -0
- package/dist/{chunk-5E4WNAVD.js → chunk-3PII3JI5.js} +2 -2
- package/dist/chunk-3TNRNKAT.js +2 -0
- package/dist/chunk-3VLJ2DCA.js +2 -0
- package/dist/{chunk-XSRF6Q77.js → chunk-46JLFIGA.js} +2 -2
- package/dist/chunk-4DCKBY6T.js +5 -0
- package/dist/chunk-4EXFZP6H.js +2 -0
- package/dist/chunk-4IIMPWMR.js +29 -0
- package/dist/chunk-4ILHWBYF.js +2 -0
- package/dist/chunk-4N6QSEMZ.js +10 -0
- package/dist/chunk-4OE2JO6I.js +2 -0
- package/dist/{chunk-7BAVHKMJ.js → chunk-4S4DF62J.js} +9 -9
- package/dist/chunk-4UUCUASK.js +554 -0
- package/dist/chunk-5236NQV3.js +2 -0
- package/dist/chunk-54EOGFBR.js +2 -0
- package/dist/{chunk-LY4WC4AD.js → chunk-5H7IWVXJ.js} +2 -2
- package/dist/chunk-5IZTXSOL.js +117 -0
- package/dist/{chunk-AZJQQKDD.js → chunk-5SE323LF.js} +2 -2
- package/dist/chunk-5ZJH6DDE.js +2 -0
- package/dist/chunk-63MBA7EG.js +3 -0
- package/dist/chunk-6BJ7SOY7.js +2 -0
- package/dist/chunk-6GJAP4OE.js +2 -0
- package/dist/chunk-6IEVHGWG.js +26 -0
- package/dist/chunk-6SWA6B24.js +7 -0
- package/dist/chunk-6T7H2AFY.js +3 -0
- package/dist/chunk-73Z33VFI.js +4 -0
- package/dist/chunk-7COHFNJK.js +38 -0
- package/dist/chunk-7HU2IJ2T.js +3 -0
- package/dist/chunk-7IOAZRVL.js +60 -0
- package/dist/chunk-7KCZELVM.js +2 -0
- package/dist/chunk-7PPYXENX.js +2 -0
- package/dist/chunk-7TWP3MCP.js +2 -0
- package/dist/chunk-AA7K3XLM.js +21 -0
- package/dist/chunk-AJVMVE7X.js +7 -0
- package/dist/chunk-ANWGXPPN.js +4 -0
- package/dist/chunk-APLKXICZ.js +3 -0
- package/dist/{chunk-JDOEX4E6.js → chunk-AQDWTCDC.js} +2 -2
- package/dist/chunk-AUP6YI5M.js +2 -0
- package/dist/chunk-B7ECWJAZ.js +2 -0
- package/dist/{chunk-ZHXX42OH.js → chunk-BATIVRU2.js} +4 -4
- package/dist/chunk-BBEDPVPB.js +4 -0
- package/dist/chunk-BBWPOMGU.js +2 -0
- package/dist/chunk-BD6CV7PN.js +2 -0
- package/dist/{chunk-XKWKXZKW.js → chunk-BHE44MHT.js} +2 -2
- package/dist/chunk-BOJ5SVE2.js +2 -0
- package/dist/chunk-BZYSGZRK.js +2 -0
- package/dist/chunk-CA5RE6H7.js +2 -0
- package/dist/chunk-CKDOY6JA.js +2 -0
- package/dist/chunk-CN2WGM7D.js +2 -0
- package/dist/chunk-COTMS5KM.js +3 -0
- package/dist/chunk-CSDDOUA4.js +3 -0
- package/dist/chunk-CT5SI2I4.js +2 -0
- package/dist/chunk-D5EKVZPI.js +2 -0
- package/dist/{chunk-FKSELJQF.js → chunk-D5W4UZY5.js} +2 -2
- package/dist/{chunk-RUJURYSV.js → chunk-DEUGHURX.js} +2 -2
- package/dist/chunk-DHKBIOXF.js +7 -0
- package/dist/chunk-DMQ7ZKJG.js +81 -0
- package/dist/chunk-DMUGTKMD.js +2 -0
- package/dist/chunk-DOPCR5BY.js +2 -0
- package/dist/chunk-DRENNWRG.js +2 -0
- package/dist/chunk-E4EJBGDZ.js +2 -0
- package/dist/chunk-E7BJXRNV.js +2 -0
- package/dist/chunk-EA4SH4U5.js +5 -0
- package/dist/{chunk-L7AW2QB5.js → chunk-EKZRF57O.js} +2 -2
- package/dist/chunk-ELNRLMC5.js +29 -0
- package/dist/chunk-F4FNK44D.js +2 -0
- package/dist/chunk-F7WQ337U.js +308 -0
- package/dist/chunk-FEQIQ26E.js +2 -0
- package/dist/chunk-FGB567HK.js +23 -0
- package/dist/chunk-FHV7NMFU.js +29 -0
- package/dist/chunk-FN6EJM6Q.js +2 -0
- package/dist/chunk-FTSQNONX.js +2 -0
- package/dist/chunk-FUG6RPYY.js +6 -0
- package/dist/chunk-G2F6T5BV.js +2 -0
- package/dist/chunk-G6OGPXJW.js +9 -0
- package/dist/chunk-GFLTPNWV.js +3 -0
- package/dist/chunk-GTDP2SKQ.js +2 -0
- package/dist/chunk-H46QMB7E.js +2 -0
- package/dist/chunk-H5EXS3HM.js +2 -0
- package/dist/chunk-HEOMG7IM.js +8 -0
- package/dist/chunk-HG5YI7PV.js +2 -0
- package/dist/{chunk-7SQQWSY3.js → chunk-HGKEAP7F.js} +2 -2
- package/dist/chunk-HUZNZ3H2.js +2 -0
- package/dist/chunk-HWLCBKFE.js +2 -0
- package/dist/chunk-I3U2FN2T.js +13 -0
- package/dist/{chunk-JAYYFEQY.js → chunk-I7PFL5P3.js} +2 -2
- package/dist/{chunk-2HPVVXM5.js → chunk-ICHBVITH.js} +2 -2
- package/dist/chunk-ICUQONOG.js +38 -0
- package/dist/chunk-IDPLC3FI.js +5 -0
- package/dist/{chunk-A73XVBCR.js → chunk-IGKKTHJR.js} +2 -2
- package/dist/chunk-IOKWFRFQ.js +4 -0
- package/dist/chunk-IPAL6DP2.js +3 -0
- package/dist/chunk-IUJ3ZFEE.js +7 -0
- package/dist/chunk-IXJ26KJJ.js +16 -0
- package/dist/chunk-IYV2YBHM.js +2 -0
- package/dist/chunk-JVZNWJBH.js +2 -0
- package/dist/chunk-K5MZYZV7.js +3 -0
- package/dist/{chunk-3G66UZBH.js → chunk-KFK7GF5C.js} +2 -2
- package/dist/chunk-KTRGJLY7.js +18 -0
- package/dist/chunk-KW6B5OL4.js +2 -0
- package/dist/chunk-KWARB5FZ.js +2 -0
- package/dist/chunk-LHTT5C3Z.js +2 -0
- package/dist/chunk-LPGDO2XA.js +3 -0
- package/dist/chunk-LXLD46LH.js +21 -0
- package/dist/chunk-MEI3PTUK.js +2 -0
- package/dist/chunk-MJNV7OCG.js +5 -0
- package/dist/chunk-MO226P4Q.js +4 -0
- package/dist/{chunk-3CLX5EOX.js → chunk-MOBF2GH6.js} +2 -2
- package/dist/chunk-MXNGIEPU.js +3 -0
- package/dist/chunk-MYUKI5VN.js +4 -0
- package/dist/{chunk-TFRAYKN6.js → chunk-N5C65OFK.js} +2 -2
- package/dist/{chunk-PXY7F6Y4.js → chunk-O2RM7E7L.js} +5 -5
- package/dist/chunk-OFUBXBYX.js +3 -0
- package/dist/chunk-OFY4HTMI.js +2 -0
- package/dist/chunk-OIRWZIYL.js +38 -0
- package/dist/chunk-OIVZ7PW6.js +438 -0
- package/dist/chunk-ORBKAUCH.js +4 -0
- package/dist/chunk-OUB4J26T.js +2 -0
- package/dist/chunk-OVPS2ILI.js +20 -0
- package/dist/chunk-PHSPBQM6.js +5 -0
- package/dist/{chunk-JVYA47YU.js → chunk-PIZY2GX6.js} +2 -2
- package/dist/chunk-PNISDVYC.js +3 -0
- package/dist/chunk-PQOL42AW.js +2 -0
- package/dist/chunk-PUVZNFVY.js +11 -0
- package/dist/chunk-PZEI2TVL.js +4 -0
- package/dist/{chunk-ZK26BAQL.js → chunk-Q2J2VZZT.js} +2 -2
- package/dist/chunk-Q7HB7BFJ.js +2 -0
- package/dist/{chunk-ZTETIQ35.js → chunk-QBANU5BQ.js} +2 -2
- package/dist/chunk-QD7IFBCR.js +10 -0
- package/dist/chunk-QDCCHMVZ.js +2 -0
- package/dist/chunk-QLQBZOJH.js +3 -0
- package/dist/{chunk-PQCI4SQX.js → chunk-QXR5QPSF.js} +2 -2
- package/dist/chunk-R2MOKIVO.js +2 -0
- package/dist/{chunk-EN3O7VJA.js → chunk-RFWAUHVW.js} +2 -2
- package/dist/chunk-RGCJ4646.js +16 -0
- package/dist/{chunk-BPAPWKP6.js → chunk-S3RTPPLQ.js} +8 -8
- package/dist/chunk-S73HBCGI.js +11 -0
- package/dist/chunk-SDPA5DKN.js +210 -0
- package/dist/chunk-SEUJVWT2.js +3 -0
- package/dist/chunk-SF7X6QNW.js +2 -0
- package/dist/chunk-SKUMCCC5.js +2 -0
- package/dist/chunk-SSSJO4RG.js +2 -0
- package/dist/chunk-SWFAFA4G.js +49 -0
- package/dist/chunk-SYUNTKO2.js +2 -0
- package/dist/chunk-T6FRID7Y.js +3 -0
- package/dist/chunk-TGWNNMPF.js +3 -0
- package/dist/chunk-TM5XEDDR.js +4 -0
- package/dist/chunk-TNOHGHZQ.js +2 -0
- package/dist/chunk-U2GPTA5U.js +3 -0
- package/dist/{chunk-SXP2MBJH.js → chunk-U7DR7MJD.js} +2 -2
- package/dist/chunk-U7LRSQG6.js +3 -0
- package/dist/chunk-UL4VJUMD.js +2 -0
- package/dist/chunk-UNORWZIJ.js +16 -0
- package/dist/chunk-UQ7XPRWU.js +2 -0
- package/dist/{chunk-6SHPK5ZE.js → chunk-URMZLV2N.js} +2 -2
- package/dist/chunk-URTX2BEA.js +6 -0
- package/dist/chunk-UZFCZ7SJ.js +2 -0
- package/dist/{chunk-KMKTIO2G.js → chunk-V7LQZTTZ.js} +2 -2
- package/dist/chunk-VETXXOYU.js +3 -0
- package/dist/chunk-VGRUM7JI.js +3 -0
- package/dist/{chunk-WXZLAAWK.js → chunk-VNKYRJKN.js} +2 -2
- package/dist/chunk-VWLIOEEF.js +11 -0
- package/dist/chunk-WB6LGCFB.js +6 -0
- package/dist/{chunk-W4ETQAXM.js → chunk-WK4FD4PG.js} +2 -2
- package/dist/{chunk-O64IZ6UX.js → chunk-WKPZCQLI.js} +2 -2
- package/dist/chunk-WSG3DK5H.js +2 -0
- package/dist/chunk-WULAPQUD.js +38 -0
- package/dist/chunk-WZQFY5S7.js +4 -0
- package/dist/chunk-X434XZAI.js +2 -0
- package/dist/chunk-X7PJJYKX.js +29 -0
- package/dist/chunk-XDAUYDFT.js +2 -0
- package/dist/chunk-XITQLISP.js +2 -0
- package/dist/chunk-XRXCANFQ.js +4 -0
- package/dist/chunk-XVDMJMES.js +3 -0
- package/dist/chunk-XXJ7WL3F.js +35 -0
- package/dist/chunk-Y4XQ7LES.js +9 -0
- package/dist/chunk-YIEFEPG6.js +16 -0
- package/dist/chunk-YRVERHJR.js +49 -0
- package/dist/{chunk-CJST5ETY.js → chunk-YUFWLWIC.js} +2 -2
- package/dist/chunk-YUKYB54I.js +1 -0
- package/dist/chunk-Z3GCK3PD.js +3 -0
- package/dist/chunk-ZBNL3QCY.js +4 -0
- package/dist/chunk-ZD3Z54IW.js +2 -0
- package/dist/chunk-ZDVDSDFG.js +4 -0
- package/dist/{chunk-32LVLCLN.js → chunk-ZHSARYVS.js} +3 -3
- package/dist/{chunk-BDCC2NPY.js → chunk-ZW44MCJM.js} +2 -2
- package/dist/{chunk-N5W4YZMK.js → chunk-ZYREOING.js} +2 -2
- package/dist/cli-main.js +8 -0
- package/dist/cli.js +1 -3
- package/dist/code-CczEvHui.d.ts +121 -0
- package/dist/code-EQL6ZBLH.js +2 -0
- package/dist/code-result-json-6E4J6LGZ.js +2 -0
- package/dist/command-descriptors-QH3G2OVD.js +346 -0
- package/dist/{config-types-jVM3D7MA.d.ts → config-types-Cm-VSEBb.d.ts} +189 -23
- package/dist/dataflow-2BLMUZBP.js +2 -0
- package/dist/{db-B5PM5yNk.d.ts → db-LKJXAlNS.d.ts} +1 -1
- package/dist/dependence-slice-MGAJDZXB.js +2 -0
- package/dist/deps-GQMUYVKW.js +2 -0
- package/dist/direct-navigation-6RUJKLAV.js +3 -0
- package/dist/entry-map-V2NQP5JU.js +2 -0
- package/dist/exploration-topology-BG4v30HZ.d.ts +256 -0
- package/dist/file-dep-graph-Bqg3t3Px.d.ts +4 -0
- package/dist/file-kind-BKCVMNUf.d.ts +10 -0
- package/dist/files-VM53I4IU.js +2 -0
- package/dist/graph-evidence-CbUPCSKV.d.ts +126 -0
- package/dist/graph-exploration-contract-CqDsnPQL.d.ts +7 -0
- package/dist/{health-Do5TKSJI.d.ts → health-Wl5G_LRt.d.ts} +33 -34
- package/dist/hierarchy-D553WRSZ.js +2 -0
- package/dist/imports-DOZAJWLW.js +2 -0
- package/dist/index.d.ts +4 -31
- package/dist/index.js +1 -1
- package/dist/members-HE67475K.js +2 -0
- package/dist/methods-K5JK4PPH.js +2 -0
- package/dist/next-anchor-candidates-BwMczMvX.d.ts +90 -0
- package/dist/output-continuation-command-LKBUTNRL.js +3 -0
- package/dist/output-pagination-VAWOGX4R.js +19 -0
- package/dist/postinstall.js +1 -1
- package/dist/project-reindex-4ARU6QCM.js +3 -0
- package/dist/queries/affected.d.ts +22 -4
- package/dist/queries/affected.js +1 -1
- package/dist/queries/anchors.d.ts +123 -0
- package/dist/queries/anchors.js +2 -0
- package/dist/queries/architecture.d.ts +3 -2
- package/dist/queries/architecture.js +1 -1
- package/dist/queries/bottlenecks.d.ts +26 -7
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.d.ts +2 -2
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.d.ts +17 -3
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.d.ts +2 -2
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.d.ts +2 -2
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/co-change.d.ts +2 -2
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.d.ts +5 -26
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.d.ts +2 -2
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.d.ts +2 -2
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/context.d.ts +145 -0
- package/dist/queries/context.js +2 -0
- package/dist/queries/convergence.d.ts +2 -2
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.d.ts +8 -3
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.d.ts +34 -7
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dataflow.d.ts +40 -14
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.d.ts +2 -2
- package/dist/queries/dead.js +1 -1
- package/dist/queries/decorative-checkers.d.ts +3 -3
- package/dist/queries/decorative-checkers.js +1 -1
- package/dist/queries/deep-chains.d.ts +4 -38
- package/dist/queries/deep-chains.js +1 -1
- package/dist/queries/dependence-slice.d.ts +47 -0
- package/dist/queries/dependence-slice.js +2 -0
- package/dist/queries/dependency-depth.d.ts +49 -0
- package/dist/queries/dependency-depth.js +2 -0
- package/dist/queries/deps.d.ts +4 -2
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-impact.d.ts +3 -3
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.d.ts +4 -4
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.d.ts +2 -2
- package/dist/queries/drift.js +1 -1
- package/dist/queries/duplicate-bodies.d.ts +2 -2
- package/dist/queries/duplicate-bodies.js +1 -1
- package/dist/queries/entry-map.d.ts +121 -0
- package/dist/queries/entry-map.js +2 -0
- package/dist/queries/evidence.d.ts +70 -0
- package/dist/queries/evidence.js +2 -0
- package/dist/queries/extract-candidates.d.ts +2 -2
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.d.ts +18 -5
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.d.ts +2 -2
- package/dist/queries/files.js +1 -1
- package/dist/queries/health.d.ts +4 -3
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.d.ts +5 -3
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.d.ts +11 -5
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.d.ts +2 -2
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.d.ts +4 -4
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +56 -136
- package/dist/queries/index.js +1 -1
- package/dist/queries/isolated.d.ts +2 -2
- package/dist/queries/isolated.js +1 -1
- package/dist/queries/locality-candidates.d.ts +2 -2
- package/dist/queries/locality-candidates.js +1 -1
- package/dist/queries/members.d.ts +2 -2
- package/dist/queries/members.js +1 -1
- package/dist/queries/methods.d.ts +2 -2
- package/dist/queries/methods.js +1 -1
- package/dist/queries/not-implemented.d.ts +3 -3
- package/dist/queries/not-implemented.js +1 -1
- package/dist/queries/outline.d.ts +2 -2
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.d.ts +5 -9
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/plan-context.d.ts +27 -64
- package/dist/queries/plan-context.js +1 -1
- package/dist/queries/react-component-duplicates.d.ts +2 -2
- package/dist/queries/react-component-duplicates.js +1 -1
- package/dist/queries/react-hook-candidates.d.ts +2 -2
- package/dist/queries/react-hook-candidates.js +1 -1
- package/dist/queries/react-large-component-pressure.d.ts +2 -2
- package/dist/queries/react-large-component-pressure.js +1 -1
- package/dist/queries/recent-duplicates.d.ts +2 -2
- package/dist/queries/recent-duplicates.js +1 -1
- package/dist/queries/redundant-reexports.d.ts +2 -2
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/reference-neighborhood.d.ts +4 -0
- package/dist/queries/reference-neighborhood.js +2 -0
- package/dist/queries/reference-reachability.d.ts +48 -0
- package/dist/queries/reference-reachability.js +2 -0
- package/dist/queries/refs.d.ts +2 -2
- package/dist/queries/refs.js +1 -1
- package/dist/queries/self-audit.d.ts +2 -2
- package/dist/queries/self-audit.js +1 -1
- package/dist/queries/similar-chains.d.ts +2 -2
- package/dist/queries/similar-chains.js +1 -1
- package/dist/queries/similar-files.d.ts +2 -2
- package/dist/queries/similar-files.js +1 -1
- package/dist/queries/similar-signatures.d.ts +2 -2
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.d.ts +2 -2
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice.d.ts +3 -36
- package/dist/queries/slice.js +1 -1
- package/dist/queries/source-inspection.d.ts +209 -0
- package/dist/queries/source-inspection.js +2 -0
- package/dist/queries/source-search.d.ts +13 -0
- package/dist/queries/source-search.js +2 -0
- package/dist/queries/stale-abstractions.d.ts +2 -2
- package/dist/queries/stale-abstractions.js +1 -1
- package/dist/queries/stats.d.ts +2 -2
- package/dist/queries/surface.d.ts +13 -4
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.d.ts +2 -2
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system-map.d.ts +449 -0
- package/dist/queries/system-map.js +2 -0
- package/dist/queries/system.d.ts +5 -3
- package/dist/queries/system.js +1 -1
- package/dist/queries/test-quality.d.ts +2 -2
- package/dist/queries/test-quality.js +1 -1
- package/dist/queries/trace.d.ts +47 -3
- package/dist/queries/trace.js +1 -1
- package/dist/queries/twin-ab.d.ts +3 -3
- package/dist/queries/twin-ab.js +1 -1
- package/dist/queries/twin-drift.d.ts +3 -3
- package/dist/queries/twin-drift.js +1 -1
- package/dist/queries/unused-imports.d.ts +2 -2
- package/dist/queries/unused-imports.js +1 -1
- package/dist/queries/unused-params.d.ts +2 -2
- package/dist/queries/unused-params.js +1 -1
- package/dist/queries/value-flow.d.ts +43 -0
- package/dist/queries/value-flow.js +2 -0
- package/dist/queries/vue-component-duplicates.d.ts +2 -2
- package/dist/queries/vue-component-duplicates.js +1 -1
- package/dist/queries/vue-composable-candidates.d.ts +2 -2
- package/dist/queries/vue-composable-candidates.js +1 -1
- package/dist/queries/vue-large-view-pressure.d.ts +2 -2
- package/dist/queries/vue-large-view-pressure.js +1 -1
- package/dist/queries/wrapper-candidates.d.ts +2 -2
- package/dist/queries/wrapper-candidates.js +1 -1
- package/dist/query-service-fastpath.js +6 -0
- package/dist/query-service-server.js +5 -0
- package/dist/refs-NBHKL4UQ.js +2 -0
- package/dist/refs-pagination-BBVTIHMH.js +2 -0
- package/dist/reindex-worker.js +27 -45
- package/dist/reindex.d.ts +62 -42
- package/dist/reindex.js +32 -33
- package/dist/repository-text-C0Q8VYdN.d.ts +19 -0
- package/dist/runtime.d.ts +286 -7
- package/dist/runtime.js +4 -3
- 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-BnEwZRLJ.d.ts → scip-cli-CppzF5MK.d.ts} +33 -2
- package/dist/slice-U6S6LBSB.js +2 -0
- package/dist/source-search-types-Dwz8KeuW.d.ts +79 -0
- package/dist/source-snippet-_wrcgmZc.d.ts +15 -0
- package/dist/stats-OOJ74B32.js +2 -0
- package/dist/surface-C7SS5CDQ.js +2 -0
- package/dist/symbol-resolution-3FVEKDTJ.js +2 -0
- package/dist/system-6K2NOO5C.js +2 -0
- package/dist/trace-II5K2TMH.js +2 -0
- package/dist/typescript-mailbox-worker.js +1 -1
- package/dist/value-flow-MKFUUE5B.js +2 -0
- package/dist/watch-server.js +3 -2
- package/docs/AGENT_GUIDE.md +133 -476
- package/docs/AI_FAILURE_MODES.md +30 -301
- package/docs/API.md +1 -1
- package/docs/API_EVOLUTION.md +6 -0
- package/docs/CLI_JSON_OUTPUT.md +207 -29
- package/docs/COMMAND_REFERENCE.md +255 -154
- package/docs/CONFIGURATION_WRITE_SAFETY.md +14 -13
- package/docs/DETECTOR_EVIDENCE_CONTRACTS.md +84 -0
- package/docs/DETECTOR_GUIDE.md +46 -138
- package/docs/DURABILITY.md +7 -1
- package/docs/INDEX_GENERATIONS.md +6 -0
- package/docs/LOCK_PROTOCOL.md +8 -0
- package/docs/REINDEX_METADATA_COMPATIBILITY.md +13 -3
- package/docs/SECURITY_MODEL.md +39 -42
- package/docs/accuracy-audit-checklist.md +4 -0
- package/docs/accuracy-hardening-goal.md +9 -2
- package/docs/analyzer-inventory.md +59 -264
- package/docs/analyzer-validation-protocol.md +62 -170
- package/docs/architecture-coherence-vision.md +18 -12
- package/docs/locality-analyzer-design.md +1 -1
- package/docs/schemas/cli-json-envelope.schema.json +212 -27
- package/docs/schemas/cli-json-export-receipt.schema.json +25 -0
- package/docs/schemas/cli-output-page.schema.json +1 -1
- package/docs/schemas/observation-receipt.schema.json +164 -0
- package/docs/schemas/project-config.schema.json +27 -45
- package/docs/schemas/suppression-record.schema.json +1 -34
- package/package.json +65 -8
- package/skills/concrete-plan/SKILL.md +8 -0
- package/skills/concrete-plan/agents/openai.yaml +4 -0
- package/skills/scip-explore/SKILL.md +3 -85
- package/skills/scip-explore/agents/openai.yaml +3 -3
- package/skills/scip-integrity-audit/SKILL.md +185 -0
- package/skills/scip-integrity-audit/agents/openai.yaml +4 -0
- package/skills/scip-plan/SKILL.md +67 -49
- package/skills/scip-plan/agents/openai.yaml +3 -3
- package/skills/scip-query/SKILL.md +77 -77
- package/skills/scip-query/agents/openai.yaml +3 -3
- package/skills/scip-setup/SKILL.md +10 -102
- package/skills/scip-setup/agents/openai.yaml +3 -3
- package/dist/chunk-26QA6FAI.js +0 -8
- package/dist/chunk-2KAZEZ6M.js +0 -2
- package/dist/chunk-3ORVDL3H.js +0 -2
- package/dist/chunk-46XGSFNI.js +0 -2
- package/dist/chunk-4MAK2HOY.js +0 -6
- package/dist/chunk-4TURLRL5.js +0 -16
- package/dist/chunk-4UQVNCQE.js +0 -2
- package/dist/chunk-55Q3WLZX.js +0 -2
- package/dist/chunk-5I5G2QOX.js +0 -3
- package/dist/chunk-6LDJQXAH.js +0 -2
- package/dist/chunk-6O5TICIZ.js +0 -3
- package/dist/chunk-7O5IKBTZ.js +0 -16
- package/dist/chunk-7S5E7KWT.js +0 -2
- package/dist/chunk-7WPLAODU.js +0 -5
- package/dist/chunk-AFHORGLH.js +0 -42
- package/dist/chunk-AIE7TFJW.js +0 -9
- package/dist/chunk-AQOFWNQJ.js +0 -1
- package/dist/chunk-B2PX5I6M.js +0 -2
- package/dist/chunk-B75HZHUP.js +0 -2
- package/dist/chunk-B7PBSLZN.js +0 -2
- package/dist/chunk-BBW6JFHN.js +0 -2
- package/dist/chunk-BNXCIFVY.js +0 -2
- package/dist/chunk-BS2NMXQZ.js +0 -4
- package/dist/chunk-C3KV2II6.js +0 -2
- package/dist/chunk-C43RDDP4.js +0 -20
- package/dist/chunk-DAFAHMNB.js +0 -42
- package/dist/chunk-DQLPXMH6.js +0 -8
- package/dist/chunk-EKZTZXHZ.js +0 -117
- package/dist/chunk-EW2NTSFA.js +0 -18
- package/dist/chunk-F3Z4OUDS.js +0 -8
- package/dist/chunk-FJH2NW7J.js +0 -66
- package/dist/chunk-FTFP6O3L.js +0 -11
- package/dist/chunk-FYLK2DEJ.js +0 -2
- package/dist/chunk-GH74ASD6.js +0 -11
- package/dist/chunk-GMXWZP2B.js +0 -2
- package/dist/chunk-GOUBFH5O.js +0 -3
- package/dist/chunk-HLF2TX6R.js +0 -2
- package/dist/chunk-HX7M4BDI.js +0 -30
- package/dist/chunk-HZ72SESS.js +0 -128
- package/dist/chunk-IB2N4FIY.js +0 -10
- package/dist/chunk-IZYYAFN5.js +0 -2
- package/dist/chunk-JFGGXWQF.js +0 -947
- package/dist/chunk-JN4NMBEX.js +0 -8
- package/dist/chunk-JW56N3KI.js +0 -4
- package/dist/chunk-JZ2OXNWB.js +0 -2
- package/dist/chunk-KFZNKUNT.js +0 -2
- package/dist/chunk-L5GJNV2T.js +0 -8
- package/dist/chunk-L7JDSCDF.js +0 -4
- package/dist/chunk-LU47HG23.js +0 -14
- package/dist/chunk-LVY7NPF7.js +0 -2
- package/dist/chunk-MKCDWWGV.js +0 -4
- package/dist/chunk-MNE7YG56.js +0 -2
- package/dist/chunk-MRXBEXSY.js +0 -26
- package/dist/chunk-MV7OWDUX.js +0 -2
- package/dist/chunk-NGEXCJJW.js +0 -11
- package/dist/chunk-NIW6JDC5.js +0 -29
- package/dist/chunk-PBUQFCNB.js +0 -16
- package/dist/chunk-POAVPHH7.js +0 -2
- package/dist/chunk-QZ4JVECJ.js +0 -2
- package/dist/chunk-RDO52JGY.js +0 -2
- package/dist/chunk-RJT3TUUZ.js +0 -2
- package/dist/chunk-RVLDN63O.js +0 -4
- package/dist/chunk-RXOXSKY3.js +0 -2
- package/dist/chunk-S7OYBOCK.js +0 -2
- package/dist/chunk-SMNXQT5Z.js +0 -3
- package/dist/chunk-SRAFT254.js +0 -2
- package/dist/chunk-T7YQSHPQ.js +0 -3
- package/dist/chunk-UJCOIXDY.js +0 -2
- package/dist/chunk-UJPRPGCO.js +0 -13
- package/dist/chunk-WCCFZ7V7.js +0 -113
- package/dist/chunk-WUPW3UN3.js +0 -3
- package/dist/chunk-X54AGLVX.js +0 -2
- package/dist/chunk-Y2MVPNKY.js +0 -5
- package/dist/chunk-YKUU5AIC.js +0 -3
- package/dist/chunk-YLCJLTPL.js +0 -2
- package/dist/chunk-YTQVETEO.js +0 -2
- package/dist/chunk-Z4N3MZYA.js +0 -38
- package/dist/chunk-ZJOOT3BG.js +0 -2
- package/dist/command-descriptors-DSS46KXI.js +0 -642
- package/dist/diff-gate-types-B0QYpDv1.d.ts +0 -11
- package/dist/direct-navigation-6YHV6IB5.js +0 -3
- package/dist/queries/diff-gate.d.ts +0 -253
- package/dist/queries/diff-gate.js +0 -2
- package/docs/COMMITTED_RECORD_COMPATIBILITY.md +0 -154
- package/docs/analyzer-validation-ledger.md +0 -516
- package/docs/schemas/outcome-event-record.schema.json +0 -95
- package/skills/_shared/SKILL.md +0 -101
- package/skills/_shared/agents/openai.yaml +0 -4
- package/skills/_shared/references/agent-contract-catalog.md +0 -105
- package/skills/_shared/references/command-catalog.md +0 -118
- package/skills/_shared/references/detector-precision-and-diffgate.md +0 -59
- package/skills/_shared/references/evidence-and-dead-code.md +0 -25
- package/skills/scip-audit/SKILL.md +0 -77
- package/skills/scip-audit/agents/openai.yaml +0 -4
- package/skills/scip-audit/references/claims.md +0 -98
- package/skills/scip-audit/references/cleanup.md +0 -100
- package/skills/scip-audit/references/directory.md +0 -222
- package/skills/scip-audit/references/frontend.md +0 -130
- package/skills/scip-audit/references/integrity.md +0 -154
- package/skills/scip-audit/references/maintainability.md +0 -162
- package/skills/scip-audit/references/twin-drift.md +0 -104
- package/skills/scip-diagnose/SKILL.md +0 -52
- package/skills/scip-diagnose/agents/openai.yaml +0 -4
- package/skills/scip-diagnose/references/debug.md +0 -117
- package/skills/scip-diagnose/references/probe-reachability.md +0 -77
- package/skills/scip-diagnose/references/root-cause.md +0 -145
- package/skills/scip-diagnose/references/triage.md +0 -119
- package/skills/scip-explore/references/diagrams.md +0 -40
- package/skills/scip-explore/references/language-playbook.md +0 -49
- package/skills/scip-improve/SKILL.md +0 -56
- package/skills/scip-improve/agents/openai.yaml +0 -4
- package/skills/scip-improve/references/cleanup-batches.md +0 -53
- package/skills/scip-improve/references/directory-moves.md +0 -53
- package/skills/scip-improve/references/doc-reconcile.md +0 -30
- package/skills/scip-improve/references/frontend-extraction.md +0 -39
- package/skills/scip-improve/references/maintainability-mechanism.md +0 -43
- package/skills/scip-improve/references/twin-drift.md +0 -35
- package/skills/scip-plan/references/api-impact.md +0 -19
- package/skills/scip-plan/references/conductor.md +0 -41
- package/skills/scip-plan/references/high-assurance.md +0 -43
- package/skills/scip-plan/references/hyper-optimization.md +0 -50
- package/skills/scip-plan/references/tla-model.md +0 -88
- package/skills/scip-setup/references/bootstrap-workflow.md +0 -119
- package/skills/scip-setup/references/language-verification.md +0 -61
- package/skills/scip-setup/references/lifecycle-commands.md +0 -119
- package/skills/scip-setup/references/per-repo-triage.md +0 -24
- package/skills/scip-verify/SKILL.md +0 -229
- package/skills/scip-verify/agents/openai.yaml +0 -4
- package/skills/scip-verify/references/calibrate-detectors.md +0 -170
|
@@ -0,0 +1,554 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{$ as yf,$a as Pf,$b as M,$c as ng,$d as sr,A as Ht,Ab as te,Ac as le,Ae as Jl,B as Pn,Bb as Zn,Bc as pt,Cb as Y,Cc as Nr,Cd as cg,Ce as Sg,D as df,Db as Nf,Dc as ia,Dd as zl,E as mf,Ea as Rf,Eb as Zs,Ec as Kf,F as Fl,Fb as Gt,Fc as Wf,Fd as ua,G as pf,Ga as Ef,Gb as un,Gc as Vf,Gd as or,H as ae,Hb as _f,Hc as oa,Hd as da,He as vg,I as gi,Ic as nn,Id as lg,Ie as Cg,J as ff,Jc as rr,Jd as ma,K as zs,Ka as If,Kb as bi,Kc as dn,Kd as ug,L as Ct,Lb as ea,Lc as Yf,M as Ke,Ma as Ar,Mb as zt,Mc as Jf,Nb as Si,Nc as Xf,Ne as xg,O as Dn,Ob as Of,Oc as Gl,Od as Di,Oe as Rg,P as Ks,Pc as Qf,Pe as Eg,Q as Mn,Qb as go,R as hi,Ra as wf,Rb as pe,Sb as vi,Sc as Zf,Tb as ta,Tc as yo,U as yi,Ub as er,Uc as eg,Ud as dg,V as Ut,Vb as qe,Vc as ir,W as lt,Wa as jl,Wc as tg,Wd as bo,Y as gf,Ya as Vs,Yb as tr,Yd as Kl,Z as Nl,Za as Hl,Zb as nr,Zd as Wl,_ as hf,_a as Lf,_b as Bf,_d as Vl,ab as ut,ac as W,ae as mg,ba as _l,bb as dt,bc as Kt,be as pg,c as qs,ca as bf,cb as qt,cc as mt,ce as fg,da as Ol,db as Ys,dc as Ae,ea as ke,eb as Df,ec as Ce,f as se,fb as Mf,fc as Ze,gc as Ci,ge as So,h as jt,hb as Tf,hc as $f,hd as rg,he as pa,i as Gs,ib as X,ic as jf,id as Ii,ie as gg,j as fi,ja as Sf,jb as Qn,jc as xi,jd as sa,je as hg,k as tn,ka as _,kb as Q,kc as Ri,kd as aa,ke as yg,lb as Js,lc as Hf,ld as wi,le as bg,m as kl,ma as Ws,mb as Xs,mc as z,md as Wt,n as cf,na as Dt,nb as Qs,nc as He,nd as _r,oa as po,ob as Ne,oc as Uf,p as kr,pa as Qe,pb as Tn,pc as qf,pd as ig,qa as vf,qb as fo,qc as ho,qd as og,rb as kf,rc as na,rd as Or,sb as Af,sc as Gf,sd as sg,ta as Bl,tb as de,tc as We,td as Br,u as lf,ua as $l,ub as Ff,uc as ra,ud as ca,v as Al,vb as Ul,vc as _e,vd as Li,w as Xn,wa as Cf,wb as ql,wc as K,wd as Pi,x as Le,xb as Fr,xc as kn,xd as la,y as uf,ya as xf,yc as Ei,yd as ag,ye as Yl,z as ln,zc as zf}from"./chunk-OIVZ7PW6.js";import{existsSync as _w}from"fs";import{isAbsolute as Ig,join as Ow}from"path";function Mt(e,t){let n=Xl(e,t,{allowMultiple:!1})[0]?.relativePath;return n||Pg(e,t)}function $r(e,t){return Xl(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function wg(e,t){let n=Xl(e,t,{allowMultiple:!0});return n.length===1?n[0].relativePath:null}function Lg(e,t){let n=gi(e,t,{allowMultiple:!0,requirePathMatch:!0});return n.length===1?n[0].relativePath:null}function Pg(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=Ig(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=Ow(e.config.projectRoot,r);return _w(i)?r:null}function Xl(e,t,n){let r=Pg(e,t);if(r)return gi(e,r,n).filter(a=>a.relativePath===r);let i=t.replace(/\\/g,"/").replace(/^\.\//,""),o=Ig(i)||i.includes("/"),s=gi(e,t,{...n,requirePathMatch:o});if(s.length===0){if(o)return[];let a=le(e,t);return!a||e.isIgnored(a.relativePath)?[]:[{relativePath:a.relativePath,score:700}]}return s}function Dg(e,t){let n=wg(e,t);if(!n)return[];let r=na(e,[n],{sort:!0});if(r.length===0)return[];let i=Math.max(0,Qn(X(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&&!jf(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 KL,extname as uh}from"path";function Tt(e,t){let n=Q(e,t.relativePath);if(n.length===0)return!1;let r=W(t.symbol);if(!r)return!1;let i=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
|
|
3
|
+
`),o=Ne(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:Bw(n,r)}function Bw(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${Ne(t)}\\b`);return e.some(r=>n.test(r))}import{createHash as $w}from"crypto";import{isUtf8 as jw}from"buffer";import{TextDecoder as Hw}from"util";var Tg=new Hw("utf-8",{fatal:!0});function Zl(e){return Ys(e.config.projectRoot)}function fa(e,t){let n=Dn(t),r;try{r=Hl(e.config.projectRoot,n,{inputKind:"repository text file"})}catch(o){if(dt(o)||o instanceof jl)return null;throw o}let i=Uw(r);return i===null?null:Ag(n,r,i,Ng(e),Fg(e))}function kg(e,t={}){let n=[],r=ga(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 ga(e,t,n){let r=Zl(e).filter(f=>!t.scope||f.includes(t.scope)),i=Ng(e),o=Fg(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?Lf(e.config.projectRoot,f,m[0],{inputKind:"repository text file",computeSha256:S,scratchBuffer:p}):Pf(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=Ql(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=Hl(e.config.projectRoot,f,{inputKind:"repository text file"})}catch(x){if(x instanceof jl){c.push(f);continue}if(dt(x))continue;a.push(f);continue}if(m.length===0&&!_g(g)){s.push(f);continue}if(m.length===0){l+=g.byteLength,u+=1,h=S?Og(g):void 0;let x=Ql(f,h,i,o);d[x.state]+=1}if(t.includeBytes&&!t.includeBytes(f,g))continue;let y=Tg.decode(g);n(Ag(f,g,y,i,o,h),b)}return{candidateFiles:r.length,scannedTextFiles:u,semanticFiles:d,scannedBytes:l,skippedBinaryPaths:s,skippedUnreadablePaths:a,skippedOversizedPaths:c}}function Ag(e,t,n,r,i,o){let s=o??Og(t);return{relativePath:e,text:n,bytes:t.byteLength,freshness:{exactText:{state:"current",basis:"working-tree-read",sha256:s},semantic:Ql(e,s,r,i)}}}function Ql(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 Fg(e){return new Set(e.all(`SELECT documents.relative_path FROM documents WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`).map(t=>t.relative_path))}function Ng(e){let t=new Map;if(!e.generation.metadataRaw)return t;let n=kr(e.generation.metadataRaw);if(n.kind!=="legacy"&&n.kind!=="supported")return t;let r=n.metadata.fingerprint;if(!Mg(r)||!Array.isArray(r.files))return t;for(let i of r.files)!Mg(i)||typeof i.path!="string"||typeof i.hash!="string"||t.set(i.path,i.hash);return t}function Uw(e){return _g(e)?Tg.decode(e):null}function _g(e){return!e.includes(0)&&jw(e)}function Og(e){return $w("sha256").update(e).digest("hex")}function Mg(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}import{SymbolInformation_Kind as ye}from"@c4312/scip";var ha=new Map(Object.entries(ye).filter(([e,t])=>Number.isInteger(Number(e))&&typeof t=="string").map(([e,t])=>[Number(e),t])),Bg=new Map([...ha.entries()].map(([e,t])=>[t.toLowerCase(),e]));function vo(e){return ha.get(e)??"Unknown"}function mn(){return[ye.Function,ye.Method,ye.Macro,ye.Constructor,ye.Getter,ye.Setter,ye.StaticMethod,ye.SingletonMethod,ye.AbstractMethod,ye.ProtocolMethod,ye.TraitMethod]}function $g(){return[ye.Class,ye.Interface,ye.Struct,ye.Trait,ye.Type,ye.TypeAlias,ye.Enum,ye.Union,ye.Protocol]}function m4(){return[ye.Constant,ye.Variable,ye.Value,ye.Field,ye.Property,ye.StaticDataMember,ye.StaticField,ye.StaticProperty,ye.StaticVariable,ye.EnumMember]}function Vt(e,t,n={}){let r=Hr(e,[t],{additive:n.additive,semantic:n.semantic,semanticEvidence:n.semanticEvidence}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(o=>mt(o.symbol)||o.source==="ast-callsite"):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function An(e,t,n){return jr(e,[t],n).get(t.symbolId)??[]}function jr(e,t,n){let r=Kw(e)?Vw(e,t,{semantic:n.semantic!==!1,semanticEvidence:n.semanticEvidence}):Ww(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 qw=Le("caller-rows",{clearGroups:["whole-project"]}),Gw=Le("targeted-caller-strategy",{clearGroups:["whole-project"]}),zw=2e4;function Kw(e){return Gw.get(e,()=>(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>zw)}function Ww(e,t){return qw.get(e,()=>{let n=He(e),r=Hr(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 Vw(e,t,n){let r=n.semantic&&n.semanticEvidence?t.flatMap(p=>{let f=Yw(e,p);return f?[f]:[]}):[],i=new Map(r.map(p=>[p.symbolId,p])),o=n.semanticEvidence?.referenceMap(e,r)??new Map,s=eg(e,t),a=new Set(t.map(p=>p.symbol)),l=[...new Set(t.flatMap(p=>er(e,"reverse",[p.relativePath])))].flatMap(p=>z(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=We(z(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 Yw(e,t){let n=mn().join(", "),r=$g().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 Hr(e,t,n={}){if(t.length===0)return new Map;let r=n.additive??!1,i=[],o=[];for(let u of t)de(u.relativePath)&&un(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(tL(n.semanticEvidence.calleeMap(e,t)));let l=r?t:o;return l.length>0&&c(Zw(e,l)),s}function Hg(e,t){let n=new Map,r=Jw(t,n),i=dn(e);for(let[o,s]of r){let a=un(e,o);if(!a)continue;let c=Gf(s);for(let l of a){let u=c.get(l.line);if(!u)continue;let d=Xw(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 Jw(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 Xw(e,t,n,r){let i=vi(e,t,r.calleeLeaf);if(i){let a=nn(t,n.get(i.importedName)??[]).filter(c=>Ke(i.sourcePath,c.file));return a.length===1?a[0]:null}let o=nn(t,n.get(r.calleeLeaf)??[]);if(o.length===0)return null;let s=Qw(e,t,o,r.calleeQualifier);return s||rr(e,t,o,r.memberAccess,r.calleeQualifier)}function Qw(e,t,n,r){if(!r||de(t)!=="clojure")return null;let o=pe(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=>Ke(s,c.file));if(a)return a}return n.find(s=>/`([^`]+)`\//.exec(s.symbol)?.[1]===r)??null}function Zw(e,t){if(t.length===0)return new Map;let r=eu(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=eu(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=eu([...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=eL(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=[],E=null,R=()=>{if(E)return E;let w=d.get(x.documentId)??"",I=new Set;if(w){let A=zf(e,w),k=Math.max(0,x.startLine),T=Math.min(A.length-1,x.endLine);for(let L=k;L<=T;L+=1)for(let F of A[L])I.add(F)}return E=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=W(I.symbol);if(!L||!R().has(L))continue}let k=`${I.symbol}|${w.chunk_id}`;v.has(k)||(v.add(k),C.push({...I,chunkId:w.chunk_id,source:"scip-chunk"}))}u.set(x.symbolId,C)}}return u}var jg=500;function eu(e){let t=[...new Set(e)],n=[];for(let r=0;r<t.length;r+=jg)n.push(t.slice(r,r+jg));return n}function eL(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 tL(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 nL=12,rL=280;function Mi(e,t,n,r){let i=iL(e,t,n,r);if(i.size===0)return cL();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 z(e,t))i.has(l.leaf)&&a(l.leaf,l.relativePath,l.startLine,l.endLine);for(let l of pe(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 sr(e,l.sourcePath,d,{maxReexportDepth:3}))a(u,m.relativePath,m.startLine,m.endLine)}o.sort(qg);let c=o.map(l=>{let u=oL(e,l);return u?{...l,source:u}:null}).filter(l=>l!==null).slice(0,nL);return tu(c)}function ya(e,t=[]){return tu(sL(e.flatMap(n=>n?.inline??[]),t))}function Ug(e){return e?e.inline.reduce((t,n)=>t+n.name.length+n.source.length+32,0):0}function iL(e,t,n,r){let i=Y(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 oL(e,t){if(t.startLine!==t.endLine)return null;let n=(Q(e,t.relativePath)[t.startLine]??"").trim();if(!n||n.length>rL)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 sL(e,t){let n=new Map;for(let r of e){if(aL(r,t))continue;let i=`${r.relativePath}:${r.startLine}:${r.endLine}:${r.name}`;n.has(i)||n.set(i,{...r})}return[...n.values()].sort(qg)}function aL(e,t){return t.some(n=>n.relativePath===e.relativePath&&n.startLine<=e.startLine&&n.endLine>=e.endLine)}function qg(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||e.name.localeCompare(t.name)}function tu(e){return{coverage:"indexed-project-literal-values",inline:e}}function cL(){return tu([])}var lL=12,uL=20,ru=200,iu=800,dL=.9,mL=64,pL=uf("behavior-construct-ranges"),zg={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"},Ra=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],Kg=[...Ra,"lifecycle"],Wg=["loop","await","throw","mutation","spread","catch","finally","lifecycle"],fL=new Set(["onBeforeMount","onBeforeUnmount","onMounted","onUnmounted","useEffect","useInsertionEffect","useLayoutEffect"]);var Vg=new Set(["object","object_pattern","dictionary","field_declaration_list","struct_expression","struct_pattern"]);function Ti(e,t,n,r,i=[],o={}){let s=te(e,t);if(!s)return null;let a=Q(e,t),c=xt(e,t,n,r,i),l=wa(e,t,c.startLine,c.endLine),u=l?.startLine??n,d=l?.endLine??r,m=(l?ki(s.rootNode,c.startLine,c.endLine):null)??Fr(s.rootNode,u,d);if(!m)return null;let p=Zg(m,a,u,d,i);if(!p||p.lines.length===0||p.lines.some(b=>b.text.length>iu))return null;let f=AL(a,u,d),g=FL(p);if((o.requireSavings??!0)&&g>=f*dL)return null;let h=Ra.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:K(t)==="test"?$L(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 Ea(e,t,n,r,i){if(i.length===0)return[];let o=te(e,t);if(!o)return[];let s=Q(e,t),a=xt(e,t,n,r,i),c=wa(e,t,a.startLine,a.endLine),l=c?.startLine??n,u=c?.endLine??r,d=(c?ki(o.rootNode,a.startLine,a.endLine):null)??Fr(o.rootNode,l,u);if(!d)return[];let m=Zg(d,s,l,u,i);return m?m.lines.filter(p=>p.text.length<=iu&&p.signals.some(f=>["branch","loop","catch","finally"].includes(f))&&i.some(f=>f>=p.line&&f<=p.endLine)):[]}function Yg(e,t,n,r){let i=te(e,t);if(!i)return null;let o=ki(i.rootNode,n,r)??Fr(i.rootNode,n,r);if(!o)return null;let s=[],a=au(o),c=[];return cu(o,o,l=>{if(xo.has(l.type)||hL.has(l.type)){bL(s,c,l);return}if(Ia.has(l.type)){SL(s,c,l);return}if(wo.has(l.type)){vL(s,c,l);return}Lo.has(l.type)&&CL(s,l)}),{facts:wL(s),terminals:Qg(a),unsupported:c}}function xt(e,t,n,r,i=[]){let o=i.filter(u=>u>=n&&u<=r),s=pL.get(e,t,X(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=gL(e,t,n,r,o);if(s.set(a,[l.startLine,l.endLine]),s.size>mL){let u=s.keys().next().value;u!==void 0&&s.delete(u)}return l}function gL(e,t,n,r,i){let o=te(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);nh(o.rootNode,d,m,f=>{LL(f)&&f.startPosition.row>=n&&f.endPosition.row<=r&&i.every(g=>f.startPosition.row<=g&&f.endPosition.row>=g)&&u.push(f),ar.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=wa(e,t,n,r);if(a)return{startLine:a.startLine,endLine:a.endLine};if(i.length===0)return{startLine:n,endLine:r};let c=(Y(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 ou(e,t,n,r,i={}){if(r-n+1<(i.minimumBodyLines??uL))return null;let s=th(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=OL(a),l=a.filter(b=>b.text.length<=ru);if(l.length===0)return null;let u=Wg.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=BL(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 Fn(e,t,n,r){let i=th(e,t,n,r,[],!1);return i?new Map(i.candidates.map(o=>[o.line,o.signals.filter(s=>s!=="lifecycle")])):new Map}var ar=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"]),kt=new Set(["block","body","compound_statement","declaration_list","statement_block"]),xo=new Set(["if_expression","if_statement","unless","unless_statement"]),hL=new Set(["conditional_expression","ternary_expression"]),Ia=new Set(["do_statement","enhanced_for_statement","for_expression","for_in_statement","for_of_statement","for_statement","loop_expression","while_statement"]),wo=new Set(["match_expression","match_statement","switch_expression","switch_statement"]),Jg=new Set(["case_statement","match_arm","switch_case","switch_default"]),Lo=new Set(["try_expression","try_statement"]),va=new Set(["catch_clause","except_clause","rescue"]),Eo=new Set(["ensure","finally_clause"]),Ro=new Set(["else","else_clause"]),Xg=new Set(["raise_statement","return_statement","throw_statement"]),yL=new Set(["block_comment","comment","line_comment"]);function bL(e,t,n){let r=n.childForFieldName("condition")??uu(n),i=n.childForFieldName("consequence")??n.childForFieldName("body")??n.namedChildren.find(c=>kt.has(c.type)),o=n.childForFieldName("alternative")??n.namedChildren.find(c=>Ro.has(c.type));if(!r||!i){t.push(lu(n,"conditional-fields-unresolved"));return}let s=fn(r,"predicate",r.text),a=fn(i,Gg(i),"consequence");if(pn(e,s,a,"predicate-consequence",{branchRole:"consequence"}),Ca(e,s,i,"consequence"),o){let c=fn(o,Gg(o),"alternative");pn(e,s,c,"predicate-alternative",{branchRole:"alternative"}),Ca(e,s,o,"alternative");return}pn(e,s,su(s,"otherwise continue"),"predicate-fallthrough",{branchRole:"fallthrough"})}function SL(e,t,n){let r=n.childForFieldName("body")??n.namedChildren.find(s=>kt.has(s.type));if(!r){t.push(lu(n,"loop-body-unresolved"));return}let i=n.childForFieldName("condition"),o=fn(i??n,"predicate",i?.text??rn(n,r));pn(e,o,fn(r,"outcome","iteration"),"loop-iteration",{branchRole:"iteration"}),Ca(e,o,r,"iteration"),pn(e,o,su(o,"loop exits"),"loop-exit",{branchRole:"exit"})}function vL(e,t,n){let r=n.childForFieldName("body")??n.namedChildren.find(c=>kt.has(c.type)),i=n.childForFieldName("value")??n.childForFieldName("condition")??n.childForFieldName("subject")??uu(n),o=RL(r??n);if(!i||o.length===0){t.push(lu(n,"switch-cases-unresolved"));return}let s=fn(i,"predicate",i.text),a=!1;for(let c of o){let l=IL(c);a||=l;let u=rn(c,c.namedChildren.find(d=>xa(d)));pn(e,s,fn(c,"outcome",u||(l?"default":"case")),l?"predicate-default":"predicate-case",{branchRole:l?"default":"case"}),Ca(e,s,c,l?"default":"case")}a||pn(e,s,su(s,"no case matched"),"predicate-fallthrough",{branchRole:"fallthrough"})}function CL(e,t){let n=fn(t,"scope","try");for(let r of EL(t)){let i=Eo.has(r.type),o=fn(r,"handler",i?"finally":rn(r,ba(r)));pn(e,n,o,i?"finally-cleanup":"exception-handler",{branchRole:i?"finally":"catch"}),xL(e,o,r,i?"finally":"catch")}}function xL(e,t,n,r){for(let i of au(n)){let o=i.label.startsWith("throw")||i.label.startsWith("raise")?"throw":"return";pn(e,t,i,o==="throw"?"handler-throw":"handler-return",{branchRole:r,terminalKind:o})}}function Ca(e,t,n,r){for(let i of au(n)){let o=i.label.startsWith("throw")||i.label.startsWith("raise")?"throw":"return";pn(e,t,i,o==="throw"?"predicate-throw":"predicate-return",{branchRole:r,terminalKind:o})}}function pn(e,t,n,r,i){e.push({controller:t,outcome:n,subtype:r,attributes:i})}function fn(e,t,n){return{kind:t,label:Io(n).slice(0,iu),startLine:e.startPosition.row,endLine:e.endPosition.row,implicit:!1}}function su(e,t){return{...e,kind:"outcome",label:t,implicit:!0}}function Gg(e){return Xg.has(e.type)?"terminal":"outcome"}function au(e){let t=[];return cu(e,e,n=>{Xg.has(n.type)&&t.push(fn(n,"terminal",n.text))}),Qg(t)}function cu(e,t,n){n(t);for(let r of t.namedChildren)r!==e&&ar.has(r.type)||cu(e,r,n)}function RL(e){let t=[],n=r=>{for(let i of r.namedChildren)wo.has(i.type)||(Jg.has(i.type)?t.push(i):n(i))};return n(e),t}function EL(e){let t=[],n=r=>{for(let i of r.namedChildren)Lo.has(i.type)||(va.has(i.type)||Eo.has(i.type)?t.push(i):ar.has(i.type)||n(i))};return n(e),t}function IL(e){let t=rn(e,e.namedChildren.find(n=>xa(n))).trim();return e.type==="switch_default"||/^(?:default\b|_\s*=>)/u.test(t)}function lu(e,t){return{startLine:e.startPosition.row,endLine:e.endPosition.row,reason:t}}function wL(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 Qg(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 LL(e){return ar.has(e.type)||Ia.has(e.type)||wo.has(e.type)||Lo.has(e.type)||va.has(e.type)||Eo.has(e.type)}function Zg(e,t,n,r,i){let s=ki(e,n,r)??e,a=ba(s),c=[],l=0,u=0,d=(C,E,R,w,I=!1,A=!0)=>{let k=I?R.trim():Io(R);if(!k)return;let T=Math.max(n,C.startPosition.row),L=Math.min(r,C.endPosition.row);c.push({line:T,endLine:Math.max(T,L),depth:E,signals:Ra.filter(F=>w.includes(F)||F==="anchor"&&i.some(N=>N>=T&&N<=L)),text:k,copied:I}),A&&(l+=1,I&&(u+=1))},m=(C,E)=>{for(let R of C.namedChildren)v(R,E)},p=(C,E)=>{if(xo.has(C.type)){f(C,E,"else if");return}if(Ro.has(C.type)){let R=C.namedChildren.find(I=>xo.has(I.type));if(R){f(R,E,"else if");return}d(C,E,"else",["branch"],!1,!1);let w=ba(C)??C.namedChildren.find(I=>kt.has(I.type));if(w)v(w,E+1);else for(let I of C.namedChildren)v(I,E+1);return}d(C,E,"else",["branch"],!1,!1),v(C,E+1)},f=(C,E,R=C.type.startsWith("unless")?"unless":"if")=>{let w=C.childForFieldName("condition")??uu(C),I=C.childForFieldName("consequence")??C.childForFieldName("body")??C.namedChildren.find(T=>kt.has(T.type)),A=C.childForFieldName("alternative")??C.namedChildren.find(T=>Ro.has(T.type)),k=w?w.text:rn(C,I);d(C,E,`${R} ${TL(k)}`,Co(w,["branch"])),I&&v(I,E+1),A&&p(A,E)},g=(C,E)=>{let R=C.childForFieldName("body")??C.namedChildren.find(w=>kt.has(w.type));d(C,E,rn(C,R),Co(C,["loop"])),R&&v(R,E+1)},h=(C,E)=>{let R=C.childForFieldName("body")??C.namedChildren.find(w=>kt.has(w.type));d(C,E,rn(C,R),Co(C,["branch"])),R&&v(R,E+1)},b=(C,E)=>{let R=C.namedChildren.find(w=>xa(w));d(C,E,rn(C,R),["branch"],!1,!1);for(let w of C.namedChildren)(w===R||xa(w))&&v(w,E+1)},S=(C,E)=>{d(C,E,"try",[],!1);for(let R of C.namedChildren)kt.has(R.type)?v(R,E+1):(va.has(R.type)||Eo.has(R.type))&&v(R,E)},y=(C,E,R)=>{let w=C.childForFieldName("body")??C.namedChildren.find(A=>kt.has(A.type)),I=R==="finally"?"finally":rn(C,w);d(C,E,I,[R],!1,!1),w&&v(w,E+1)},x=(C,E)=>{let R=ba(C);d(C,E,rn(C,R),Co(C,["binding"])),R&&v(R,E+1)},v=(C,E)=>{if(C.startPosition.row>r||C.endPosition.row<n||yL.has(C.type)||C.type==="empty_statement")return;if(kt.has(C.type)){m(C,E);return}if(xo.has(C.type)){f(C,E);return}if(Ia.has(C.type)){g(C,E);return}if(wo.has(C.type)){h(C,E);return}if(Jg.has(C.type)){b(C,E);return}if(Lo.has(C.type)){S(C,E);return}if(va.has(C.type)){y(C,E,"catch");return}if(Eo.has(C.type)){y(C,E,"finally");return}if(Ro.has(C.type)){p(C,E);return}if(ar.has(C.type)){x(C,E);return}let w=!eh(C)||kL(C);d(C,E,C.text,Co(C),w)};return v(a&&a!==s?a:s,0),l===0?null:{constructKind:ML(s),signature:DL(s,a,t,n),lines:c,sourceStatements:l,copiedStatements:u}}function ki(e,t,n){let r=e.namedChildren.filter(i=>i.startPosition.row<=t&&i.endPosition.row>=n);for(let i of r.sort(PL)){let o=ki(i,t,n);if(o)return o}return ar.has(e.type)&&e.startPosition.row<=t&&e.endPosition.row>=n?e:null}function PL(e,t){return e.endPosition.row-e.startPosition.row-(t.endPosition.row-t.startPosition.row)||e.startPosition.row-t.startPosition.row}function ba(e){return e.childForFieldName("body")??e.childForFieldName("consequence")??e.namedChildren.find(t=>kt.has(t.type))??null}function DL(e,t,n,r){let i=rn(e,t);return i||(n[r]??e.text).trim()}function ML(e){return e.type.includes("constructor")?"constructor":e.type.includes("method")||e.type==="method"?nu(e,new Set(["class_body","class_declaration","class_definition"]))?"class method":"object method":e.type==="arrow_function"||e.type==="function_expression"||e.type==="lambda"?nu(e,new Set(["object","pair"]))?"object member":"function value":e.type.includes("function")?nu(e,ar)?"nested function":"module function":"source construct"}function nu(e,t){let n=e.parent;for(;n;){if(t.has(n.type))return!0;n=n.parent}return!1}function uu(e){return e.namedChildren.find(t=>!kt.has(t.type)&&!Ro.has(t.type))??null}function rn(e,t){if(!t)return Io(e.text);let n=Math.max(0,t.startIndex-e.startIndex);return Io(e.text.slice(0,n)).replace(/[:{]\s*$/u,"").trim()}function TL(e){let t=Io(e);return t.startsWith("(")&&t.endsWith(")")?t.slice(1,-1).trim():t}function Io(e){return e.trim().replace(/\r?\n[\t ]*/gu," ")}function Co(e,t=[]){let n=new Set(t);return e&&Po(e,r=>{let i=zg[r.type];i&&n.add(i),r.type==="call_expression"&&(n.add("call"),rh(r)&&n.add("shape")),du.has(r.type)&&n.add("binding")}),Ra.filter(r=>n.has(r))}function kL(e){let t=!1;return Po(e,n=>{t||!n.text.includes(`
|
|
40
|
+
`)||/(?:string|template|heredoc|raw_string)/u.test(n.type)&&(t=!0)}),t}function xa(e){return kt.has(e.type)||xo.has(e.type)||Ia.has(e.type)||wo.has(e.type)||Lo.has(e.type)||ar.has(e.type)||eh(e)}function eh(e){return/(?:statement|declaration|expression|assignment|return|throw|raise|break|continue|yield|with_item)$/u.test(e.type)||du.has(e.type)}function AL(e,t,n){let r=0;for(let i=t;i<=n;i+=1)r+=(e[i]?.length??0)+10;return r}function FL(e){return e.constructKind.length+e.signature.length+80+e.lines.reduce((t,n)=>t+n.text.length+n.depth*2+10,0)}function th(e,t,n,r,i,o){let s=te(e,t);if(!s)return null;let a=Q(e,t),c=wa(e,t,n,r),l=o?c?.startLine??n:n,u=o?c?.endLine??r:r,m=(c?.startLine===l&&c.endLine===u?ki(s.rootNode,l,u):null)??Fr(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");Po(m,y=>{let x=zg[y.type];if(x&&h(y.startPosition.row,x),x==="shape"&&NL(f,y,m,l,u),y.type==="call_expression"){let C=(y.childForFieldName("function")??y.namedChild(0))?.text.split(".").at(-1);if(rh(y)){h(y.startPosition.row,"shape");let E=Sa(y.text);E.length<=ru&&g.set(y.startPosition.row,E)}if(C&&fL.has(C)){h(y.startPosition.row,"lifecycle");let E=Sa(y.text);E.length<=ru&&g.set(y.startPosition.row,E)}}du.has(y.type)&&h(y.startPosition.row,"binding")});let b=Y(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:Kg.filter(v=>x.has(v)),text:g.get(y)??Sa(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 NL(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=Sa(o?.text??"");if(!s||s.includes(`
|
|
41
|
+
`)||s.length>60)return;let a=_L(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 _L(e,t){let n=e.parent;for(;n&&n!==t.parent;){if(Vg.has(n.type))return n;if(n===t)break;n=n.parent}return e.parent??e}function wa(e,t,n,r){return Y(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 Po(e,t){t(e);for(let n of e.namedChildren)Po(n,t)}function nh(e,t,n,r){r(e);for(let i of e.namedChildren)i.startPosition.row>t||i.endPosition.row<n||nh(i,t,n,r)}function Sa(e){return e.trim().replace(/\s+/gu," ")}function rh(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 Po(t,r=>{Vg.has(r.type)&&(n=!0)}),n}function OL(e){let t={};for(let n of Kg){let r=e.filter(i=>i.signals.includes(n)).length;r>0&&(t[n]=r)}return t}function BL(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(Wg),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 du=new Set(["lexical_declaration","variable_declarator","const_item","static_item","let_declaration","assignment"]);function $L(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>=lL))break}return r}var jL=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 Ai(e,t,n){let r=te(e,t)?.rootNode??null,i=HL(r,n);if(!i)return null;let o=Q(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 Do(e,t,n,r,i){let o=xt(e,t,r,i,[n]),s=o.startLine===o.endLine&&/(?:=>|\(|\{|\[|,)\s*$/u.test(Q(e,t)[o.startLine]??"");if(!s&&(o.startLine>r||o.endLine<i))return o;let a=Ai(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 HL(e,t){if(!e||!sh(e,t))return null;let n=oh(e,t);for(;n;){if(jL.has(n.type))return n;n=n.parent}return null}function oh(e,t){let n=e.namedChildren.filter(r=>sh(r,t)).sort((r,i)=>ih(r)-ih(i));return n.length>0?oh(n[0],t):e}function sh(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function ih(e){return e.endIndex-e.startIndex}var UL=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=Q(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 ah(e,t,n,r,i){let o=La(e,t,n,r);if(!o)return null;let s=te(e,t)?.rootNode??null;if(!s)return{...o,kind:"bounded-context"};let a=qL(s,n,i);if(a.length!==1)return{...o,kind:a.length===0?"non-call-reference":"bounded-context"};let c=a[0],l=Q(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 ch(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=Q(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 cr(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=Q(e,t);if(o.length===0||n<0||n>=o.length)return null;let s=Ai(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 qL(e,t,n){let r=[];return lh(e,t,n,r),r.filter(i=>!r.some(o=>o!==i&&o.startIndex>=i.startIndex&&o.endIndex<=i.endIndex))}function lh(e,t,n,r){if(zL(e,t)){UL.has(e.type)&&GL(e)===n&&r.push(e);for(let i of e.namedChildren)lh(i,t,n,r)}}function GL(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 zL(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function dh(e,t,n={}){let{context:r=0}=n,i=Ch(t);if(i)return xh(e,i.filePath,i.startLine,i.endLine,r);let o=Sh(e,t);if(o)return hh(e,o);let s=le(e,t);return s?Mo(e,s,r):null}function i3(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=>WL(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:ya(s.map(c=>c.bindingClosure),a)}}function WL(e,t,n,r){let i=Ch(t);if(i){let u=xh(e,i.filePath,i.startLine,i.endLine,n);return u?VL(e,t,u,n):mu(e,t,"definition-source-unreadable")}let o=Sh(e,t);if(o)return JL(e,t,o,n,r);let s=pt(e,t);if(!s.match)return mu(e,t,"definition-not-found");let a=oP(e,s),c=a.map(vh);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=Mo(e,d,n);return m?[m]:[]}):[],definitions:[],candidates:c,omittedCandidates:Math.max(0,s.total-c.length),suggestions:[]}}let l=Mo(e,s.match,n);return l?iP(t,l):mu(e,t,"definition-source-unreadable")}function VL(e,t,n,r){let i=z(e,n.relativePath).filter(l=>!mh(l,n.relativePath)),o=YL(e,n,i),s=gh(o.map(l=>Mo(e,l,r)).filter(l=>l!==null)).filter(l=>!bh(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(vh);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 YL(e,t,n){if(!To(t.freshness))return[];if(n.length===0)return[];let r=Hr(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 fh(e,[...o.values()],n)}function JL(e,t,n,r,i){let o=n.relativePath,s=QL(e,o),a=To(n.freshness)?z(e,o).filter(g=>!mh(g,o)):[],c=a.filter(g=>Tt(e,g)),l=c.length>0?c:XL(s,a),u=i==="all"?[]:fh(e,l,a),d=i==="all"||a.length===0?[hh(e,n)]:gh(u.map(g=>Mo(e,g,r)).filter(g=>g!==null)),m=eP(s,d),p=tP(o,s,d),f=nP(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 XL(e,t){let n=new Set(e.map(r=>r.symbol));return t.filter(r=>n.has(r.symbol))}function QL(e,t){return Dg(e,t).flatMap(n=>ZL(n,t)?n.children:[n])}function mh(e,t){return ph(t).has(e.leaf)}function ZL(e,t){return ph(t).has(W(e.symbol))}function ph(e){let t=KL(e);return new Set([t,t.slice(0,Math.max(0,t.length-uh(t).length))])}function fh(e,t,n){if(t.length===0)return[];let r=Hr(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(rP)}function gh(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=>bh(i,r))||n.push(r);return n}function hh(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??fu(t.relativePath),source:t.text,freshness:t.freshness,...To(t.freshness)?{bindingClosure:Mi(e,t.relativePath,0,Math.max(0,n.length-1))}:{}}}function eP(e,t){return Pa(e).filter(n=>t.some(r=>pu(n,r))).length}function tP(e,t,n){let r=[];return yh(r,e,t,n,0),r}function yh(e,t,n,r,i){for(let o of n){if(r.some(a=>pu(o,a)))continue;let s=Pa(o.children).filter(a=>!r.some(c=>pu(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}),yh(e,t,o.children,r,i+1)}}function Pa(e){return e.flatMap(t=>[t,...Pa(t.children)])}function nP(e){return Pa(e).length}function pu(e,t){return t.startLine<=e.startLine&&t.endLine>=e.endLine}function bh(e,t){return e.relativePath===t.relativePath&&e.startLine<=t.startLine&&e.endLine>=t.endLine}function rP(e,t){return e.startLine-t.startLine||t.endLine-e.endLine||e.symbol.localeCompare(t.symbol)}function iP(e,t){return{selector:e,status:"matched",kind:"source",totalCandidates:1,results:[t],definitions:[],candidates:[],omittedCandidates:0,suggestions:[]}}function mu(e,t,n){return{selector:t,status:"missing",kind:"source",totalCandidates:0,results:[],definitions:[],candidates:[],omittedCandidates:0,suggestions:ia(e,t,5),reason:n}}function Sh(e,t){try{return fa(e,t)}catch(n){if(n instanceof ff)return null;throw n}}function oP(e,t){if(!t.match)return[];let n=[t.match];for(let i of t.candidates){let o=z(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 vh(e){return{symbol:e.symbol,shortName:M(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function Ch(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 Mo(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=fa(e,t.relativePath);if(!i)return null;let s=i.text.split(`
|
|
47
|
+
`),a=t.endLine<=t.startLine?cr(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:M(t.symbol),relativePath:t.relativePath,startLine:u,endLine:d,language:r?.language??fu(t.relativePath),source:m,freshness:i.freshness,...To(i.freshness)?{bindingClosure:Mi(e,t.relativePath,u,d)}:{}}}function xh(e,t,n,r,i){let o=fa(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??fu(o.relativePath),source:d,freshness:o.freshness,...To(o.freshness)?{bindingClosure:Mi(e,o.relativePath,l,u)}:{}}}function To(e){return!!(e&&e.semantic.state!=="stale"&&e.semantic.basis!=="no-compiler-document")}function fu(e){switch(uh(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 Rh(e){let t=new Map,n=aP(e),r=new Map;return i=>{let o=sP(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=cP(z(e,i.file)),t.set(i.file,a));let c=lP(a,i);return r.set(o,c),c}}function sP(e){return`${e.file}\0${e.symbol}\0${e.line}`}function aP(e){return new Set(e.all("SELECT relative_path FROM documents").map(t=>t.relative_path))}function cP(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 lP(e,t){if(e.definitions.length===0)return t.symbol;let n=mP(t.symbol),r=uP(e.byLeaf,n),i=dP(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 uP(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 dP(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 mP(e){let t=new Set([e]),r=e.split(/::|\.|#/).filter(Boolean).at(-1);return r&&t.add(r),t}function Eh(e,t){let r=pe(e,t).map(i=>fP(t,i));return{usage:r,positions:gP(e,t,r)}}function Ih(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?pP(r.usage,i.sourcePaths):r.usage}}}function pP(e,t){return e.map((n,r)=>{let i=t.get(String(r));return i?{...n,sourcePath:i}:n})}function fP(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 gP(e,t,n){let r=te(e,t);if(!r)return[];let i=hP(r.rootNode),o=new Map;for(let a of i){let c=o.get(hu(a.importedName,a.localName));c?c.push(a.position):o.set(hu(a.importedName,a.localName),[a.position])}let s=[];return n.forEach((a,c)=>{let l=o.get(hu(a.importedName,a.localName??a.importedName))?.shift();l&&s.push({...l,id:String(c),file:t})}),s}function hP(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:gu(e,e.text)}];case"scoped_identifier":{let n=e.text.split("::").pop()??e.text;return[{importedName:n,localName:n,position:gu(e,n)}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=Of(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:gu(n??e,r)}]}default:return[]}}function gu(e,t){let n=Math.max(0,e.text.lastIndexOf(t));return{id:"",file:"",line:e.startPosition.row,column:e.startPosition.column+n+yP(t)}}function yP(e){return Math.max(0,Math.min(e.length-1,1))}function hu(e,t){return`${e}\0${t}`}import{spawnSync as Pu}from"child_process";import{existsSync as Du}from"fs";import{fileURLToPath as yD}from"url";function ur(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function Ta(e){let t=rg(ng,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 nD,mkdtempSync as Vh,rmSync as xu}from"fs";import{tmpdir as Iu}from"os";import{join as Ru}from"path";import{fileURLToPath as Bo,pathToFileURL as rD}from"url";import{SHARE_ENV as iD,Worker as oD}from"worker_threads";function dr(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 Ur(e,t,n){let r=ur(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 _P}from"child_process";import{createHash as OP,randomUUID as BP}from"crypto";import{existsSync as jh,realpathSync as $P,rmSync as jP}from"fs";import{tmpdir as HP}from"os";import{resolve as Ni}from"path";import{execFileSync as IP}from"child_process";import{existsSync as bP}from"fs";import{deserializeSCIP as SP,SymbolRole as vP}from"@c4312/scip";import{realpathSync as S3}from"fs";import{basename as C3,dirname as x3,join as R3,relative as E3,sep as I3}from"path";import{fileURLToPath as L3,pathToFileURL as P3}from"url";function ka(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 yu=new WeakMap,CP="SCIP_RUST_SCIP_OCCURRENCE_REFERENCE_MODE";function wh(e,t){let n=new Map,r=Aa(),i=t.filter(s=>Dh(s,r));if(i.length===0)return n;let o=Mh(e);if(!o)return n;for(let s of i){let a=Ph(o,s);a!==null&&n.set(s.symbolId,a)}return n}function Lh(e,t){if(!Dh(t,Aa()))return null;let n=Mh(e);return n?Ph(n,t):null}function Ph(e,t){return e.referencesBySymbol.get(t.symbol)??[]}function Dh(e,t="safe"){if(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||Ze(e.symbol)||/impl#\[[^\]]+\]\[Default\]default\(\)\.$/.test(e.symbol))return!1;if(t==="all")return!0;let n=Kt(e.symbol);if(n==="method")return!0;if(n!=="term")return!1;let r=nr(e.symbol);return"kind"in r?!1:!xP(r)}function xP(e){for(let t=0;t<e.descriptors.length-1;t+=1)if(e.descriptors[t]?.suffix==="type")return!0;return!1}function Mh(e){if(yu.has(e))return yu.get(e)??null;let t=RP(e);return yu.set(e,t),t}function RP(e){if(!e.generation.indexPath||!bP(e.generation.indexPath))return null;try{let t=SP(yi(e.generation.indexPath,{inputKind:"SCIP occurrence-reference index",maxBytes:hi})),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&vP.Definition)!==0)continue;let s=EP(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,ka(i));return{referencesBySymbol:n}}catch{return null}}function EP(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 Aa(){return process.env[CP]==="all"?"all":"safe"}var Th=new Map;function bu(e){let n=Ta(e).resolvedBinary??null;return{engine:"rust-analyzer",resolvedBinary:n,version:n?wP(e,n):"unavailable"}}function qr(e){return{...bu(e),scipOccurrenceReferenceMode:Aa()}}function wP(e,t){let n=`${e}\0${t}`,r=Th.get(n);if(r)return r;let i;try{i=IP(t,["--version"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim()}catch{i="unknown"}return Th.set(n,i),i}import{createHash as LP}from"crypto";var PP=new Set(["Cargo.lock","Cargo.toml","rust-project.json","rust-toolchain","rust-toolchain.toml"]);function kh(e){let t=Df(e,{includePath:DP});return LP("sha256").update(JSON.stringify(t)).digest("hex")}function DP(e){let t=e.replaceAll("\\","/"),n=t.split("/").at(-1)??t;return t.endsWith(".rs")||PP.has(n)?!0:t===".cargo/config"||t===".cargo/config.toml"||t.endsWith("/.cargo/config")||t.endsWith("/.cargo/config.toml")}import{createHash as MP}from"crypto";import{resolve as TP}from"path";var Fi=3;function vu(e){return MP("sha256").update(_r({kind:"scip-query-durable-rust-mailbox",protocolVersion:Fi,sessionDir:TP(e)})).digest("hex")}function Nh(e,t){return se(e)?e.protocolVersion!==Fi?Fh(e.protocolVersion===void 0?"helper wrote a prior uncorrelated response protocol":`helper wrote unsupported response protocol ${String(e.protocolVersion)}`):e.mailboxVersion!==Br||e.id!==t.requestId||e.operationKey!==t.operationKey||e.sessionIdentity!==t.sessionIdentity||e.deadlineAtMs!==t.deadlineAtMs?Fh("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"||!NP(e.errorCode)?Su("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"||!kP(e.response,t.requestKind)?Su("helper wrote an invalid success response"):{ok:!0,session:e.session,response:e.response}:Su("helper wrote an invalid response object")}function kP(e,t){return!se(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")):Ah(e.references,AP)&&(e.incompleteReferenceSymbolIds===void 0||Array.isArray(e.incompleteReferenceSymbolIds)&&e.incompleteReferenceSymbolIds.every(n=>Number.isSafeInteger(n)))&&(e.callees===void 0||Ah(e.callees,FP))&&(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 Ah(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 AP(e){return se(e)&&typeof e.file=="string"&&jt(e.line)&&jt(e.column)}function FP(e){return se(e)&&typeof e.symbol=="string"&&typeof e.file=="string"&&jt(e.line)&&(e.callsiteLine===void 0||jt(e.callsiteLine))}function NP(e){return e==="unsupported-protocol"||e==="malformed-request"||e==="expired-request"||e==="handler-error"}function Su(e){return{ok:!1,code:"malformed-response",error:e}}function Fh(e){return{ok:!1,code:"incompatible-response",error:e}}var UP=5e3,Hh=10,qP=3e4;function _h(e,t,n,r=zh){let i=r.engineIdentity(e),o={protocolVersion:Fi,projectRoot:r.canonicalProjectRoot(e),projectFingerprint:r.projectFingerprint(e),engine:{engine:i.engine,resolvedBinary:i.resolvedBinary,version:i.version},workerFingerprint:r.fileFingerprint(t),environment:Uh(r.environment())};return{key:Kh(_r(o)),...o}}function ko(e,t,n,r){if(e.protocolVersion!==Fi||!n(e.pid))return!1;if(!e.processIdentity)return!0;let i=r?.(e.pid);return i!=null&&aa(e.processIdentity,i)}function Cu(e,t,n){let r;try{r=Nl(t,{maxBytes:Mn,inputKind:"Rust semantic engine artifact"})}catch{r="missing"}let i=Kh(_r({projectRoot:Ni(e),serverPath:Ni(t),serverFingerprint:r})).slice(0,20);return Ni(n,`scip-query-rust-session-${i}`)}function Oh(e){let t=e===void 0?Number.NaN:Number(e);return Number.isInteger(t)&&t>=0?t:0}function Uh(e){return Object.fromEntries(Object.entries(e).filter(([t])=>Gh(t)).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,n??null]))}function qh(e,t){let n=t.runtime??YP,r=t.identityRuntime??zh,i=Cu(e,t.serverPath,t.tempRoot??HP()),o=!1,s=(a,c)=>{if(o)throw new Error("Durable Rust semantic session was already disposed.");return zP(i,t.serverPath,t.semanticWorkerPath,a,c,n,t.mailboxLimits)};return{requestSemantic(a,c){let l=_h(e,t.semanticWorkerPath,a,r),{readinessDeadlineMs:u,...d}=a;return s({kind:"semantic",identityKey:l.key,workerEnvironment:$h(),request:{...d,referenceRetryTimeoutMs:GP(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,a.referenceRetryTimeoutMs),settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:Oh(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},requestImportDefinitions(a,c){let l=_h(e,t.semanticWorkerPath,a,r),{readinessDeadlineMs:u,...d}=a;return s({kind:"import-definitions",identityKey:l.key,workerEnvironment:$h(),request:{...d,settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:Oh(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},shutdown(){o=!0}}}function GP(e,t){return t!==void 0?t:e===void 0?qP:void 0}function zP(e,t,n,r,i,o,s={}){let a=o.now(),c=a+i,l=(o.monotonicNow??Wt)(),u=l+i,d=Li("rust-semantic-v3",r),m=Pi(d),p=ca(e),f=vu(e),g=la(p,{mailboxVersion:Br,protocolVersion:Fi,id:m,operationKey:d,clientId:o.randomId(),enqueuedAtMs:a,deadlineAtMs:c,sessionIdentity:f,request:r},{nowMs:a,limits:s});for(Bh(e,t,n,u,o);(o.monotonicNow??Wt)()<=u;){if(jh(g.responsePath)){let b=KP(Ut(g.responsePath,{maxBytes:s.maxItemBytes??Mn,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 ke()&&Ws({type:"span",name:"rust.semantic.durable-session.request",durationMs:(o.monotonicNow??Wt)()-l,ok:!0,session:b.session,kind:r.kind}),b.response}let h=Ao(e);(!h||!ko(h,o.now(),o.isProcessAlive,o.readProcessIdentity))&&Bh(e,t,n,u,o),o.sleep(Hh)}throw new Error(`Durable Rust semantic session timed out after ${(i/1e3).toFixed(0)}s.`)}function Bh(e,t,n,r,i){let o=Ao(e);if(o&&ko(o,i.now(),i.isProcessAlive,i.readProcessIdentity))return;jP(Ni(e,"server.json"),{force:!0}),i.spawnServer(t,e,n);let s=i.monotonicNow??Wt,a=Math.min(r,s()+UP);for(;s()<=a;){let c=Ao(e);if(c&&ko(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 Ao(e){try{let t=JSON.parse(Ut(Ni(e,"server.json"),{maxBytes:Ks,inputKind:"durable Rust session state"}));if(typeof t.protocolVersion!="number"||t.sessionIdentity!==void 0&&(typeof t.sessionIdentity!="string"||t.sessionIdentity!==vu(e))||typeof t.pid!="number"||typeof t.heartbeatAtMs!="number"||t.busyUntilMs!==void 0&&typeof t.busyUntilMs!="number"||t.mailbox!==void 0&&!WP(t.mailbox))return null;let n=t.processIdentity===void 0?null:sa(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 KP(e,t){try{return Nh(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 WP(e){if(!e||typeof e!="object")return!1;let t=e;return jt(t.pending)&&jt(t.inflight)&&jt(t.responses)&&jt(t.deadLetters)&&jt(t.invalid)&&jt(t.totalItems)&&typeof t.totalBytes=="number"&&Number.isFinite(t.totalBytes)&&t.totalBytes>=0&&(t.oldestPendingAt===void 0||Number.isFinite(Date.parse(t.oldestPendingAt)))}function $h(){return Object.fromEntries(Object.entries(process.env).filter(([e])=>VP(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t??null]))}function Gh(e){return e==="HOME"||e==="PATH"||e.startsWith("CARGO_")||e.startsWith("RA_")||e.startsWith("RUST")}function VP(e){return Gh(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 zh={canonicalProjectRoot(e){try{return $P(e)}catch{return Ni(e)}},projectFingerprint(e){return kh(e)},engineIdentity:bu,fileFingerprint(e){return Nl(e,{maxBytes:Mn,inputKind:"Rust semantic engine artifact"})},environment(){return Uh(process.env)}},YP={now:Date.now,monotonicNow:Wt,randomId:BP,isProcessAlive:Ii,readProcessIdentity:wi,spawnServer(e,t,n){if(!jh(e))throw new Error(`Durable Rust semantic session helper was not found at ${e}. Run npm run build first.`);_P(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 Kh(e){return OP("sha256").update(e).digest("hex")}import{randomUUID as h6}from"crypto";import{readdirSync as JP,rmSync as b6,writeFileSync as S6}from"fs";import{join as XP}from"path";var QP="rust-analyzer-owner-",ZP=".json",eD=16*1024;async function Wh(e,t){if(!e)return[];let n;try{n=JP(e)}catch{return[]}let r=n.filter(s=>s.startsWith(QP)&&s.endsWith(ZP)).map(s=>XP(e,s)),i=[],o=[];for(let s of r){let a=tD(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=>ag(s,t)))),i}function tD(e){try{let t=Ut(e,{maxBytes:eD,inputKind:"rust-analyzer process ownership record"}),n=JSON.parse(t),r=sa(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 Yh=15e3,Jh=8,Qh=5e3,sD=64,aD=96,wu=class{constructor(t,n,r={}){this.projectRoot=t;this.status=n;this.opts=r;this.requester=r.requester??uD(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:No(n),references:_o(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!0});return{...Fo(r),resolvedBinary:n.resolvedBinary,references:dr(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:_o(t)}}}calleesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:No(n),callees:Oo(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!0});return{...Fo(r),resolvedBinary:n.resolvedBinary,callees:Eu(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:Oo(t)}}}referencesAndCalleesForDefinitions(t,n){let r=this.status(this.projectRoot);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:No(r),references:_o(t),callees:Oo(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{...Fo(o),resolvedBinary:r.resolvedBinary,references:dr(t,new Map(o.references),new Set(o.incompleteReferenceSymbolIds??[])),callees:Eu(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:No(n),signatures:Xh(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!1,includeSignatures:!0});return{...Fo(r),resolvedBinary:n.resolvedBinary,signatures:gD(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:Xh(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:No(r),sourcePaths:new Map(n.map(i=>[i.id,null]))};try{let i=this.requestImportDefinitions(r.resolvedBinary,t,n);return{...Fo(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=Fa(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Yh),o=Na(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),s=Fa(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Jh),a=Na(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=$o(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=hD(m);return _("rust.semantic.session.request",()=>this.requester.requestSemantic(m,Ur(p,Lu(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:_o(n)}:this.opts.fallbackReferenceResolver?.referencesForDefinitions(n),s=r.length===0?{available:!0,resolvedBinary:t.resolvedBinary,callees:Oo(r)}:this.opts.fallbackCalleeResolver?.calleesForDefinitions(r);if(o&&s){let a={resolvedBinary:o.resolvedBinary??s.resolvedBinary??t.resolvedBinary,references:dr(n,o.references),callees:Eu(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:_o(n),callees:Oo(r)}}requestImportDefinitions(t,n,r){let i=Fa(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Yh),o=Fa(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Jh),s=Na(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),a=Na(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,Qh),c={projectRoot:this.projectRoot,rustAnalyzerBinary:t,file:n,positions:[...r],requestTimeoutMs:i,diagnosticsTimeoutMs:s,settleDelayMs:a,concurrency:o};return _("rust.semantic.import-definitions.session.request",()=>this.requester.requestImportDefinitions(c,Ur(r.length,i,o)),()=>({file:n,positions:r.length}))}};function Fo(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function No(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function Zh(e,t,n={}){return new wu(e,t,n)}function $o(e,t){let n=ry(e);if(n!==null)return n;let r=t.includeReferences!==!1;return r&&t.includeCallees!==!0&&t.includeSignatures!==!0&&t.definitionCount<=sD||r&&t.includeCallees===!0&&t.includeSignatures!==!0&&t.definitionCount<=aD?0:Qh}function ey(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 cD(e){return ey(e).transport}function B6(e,t){let n=ey(t);if(n.transport==="worker")return{...n,state:"per-command"};let r=Bo(ny()),i=Cu(e,r,Iu()),o=Ao(i);return o?{...n,state:ko(o,Date.now(),Ii,wi)?"live":"stale",pid:o.pid,heartbeatAtMs:o.heartbeatAtMs,...o.busyUntilMs===void 0?{}:{busyUntilMs:o.busyUntilMs}}:{...n,state:"stopped"}}function lD(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=fD(u);r=!0;try{a()}catch{}ke()&&Ws({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 uD(e,t,n={worker:()=>dD(),durable:()=>qh(e,{serverPath:Bo(ny()),semanticWorkerPath:Bo(ty())})}){return cD(t)==="durable"?lD(n.durable(),n.worker):n.worker()}function dD(e={}){let t=null,n=null,r=1,i=!1,o=null,s=null,a=d=>{d&&xu(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,Wh(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?rD(e.semanticWorkerPath):ty();if(!nD(Bo(d)))throw new Error(`Rust semantic session worker was not found at ${Bo(d)}. Run npm run build before using built semantic Rust queries.`);return n=Vh(Ru(Iu(),"scip-query-rust-session-")),t=new oD(d,e.shareEnvironment?{env:iD}:void 0),t.unref(),t},u=()=>{let d=n??Vh(Ru(Iu(),"scip-query-rust-session-"));return n=d,Ru(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=mD(Ut(f,{maxBytes:Mn,inputKind:"Rust semantic worker response"}));if(!S.ok)throw new Error(S.error);return S.response}finally{xu(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=pD(Ut(f,{maxBytes:Mn,inputKind:"Rust import-definition worker response"}));if(!S.ok)throw new Error(S.error);return S.response}finally{xu(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 mD(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 pD(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 fD(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 _o(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Oo(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Xh(e){return new Map(e.map(t=>[t.symbolId,null]))}function Eu(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??[]]))}function gD(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function hD(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 Lu(e,t){return t&&t>0?Math.max(e,t):e}function ty(){return new URL("./rust-semantic-session-worker.js",import.meta.url)}function ny(){return new URL("./rust-semantic-session-server.js",import.meta.url)}function Fa(e,t){return ur(e)??t}function Na(e,t){return ry(e)??t}function ry(e){if(!e)return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var Mu=15e3,Tu=8;function ay(e,t={}){let n=t.status??Ta,r=vD(e,n),i=CD(e,n),o=xD(e,n),s=t.referenceResolver||t.calleeResolver||t.signatureResolver||!bD(t)?null:Zh(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??Ih(t.sourceImportUsageResolver??SD(),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 R=S();return R.dependencyAvailable?b??R:R},x=R=>{if(R.length===0)return new Map;let w=Ho(R);try{let I=a.referencesForDefinitions(w),A=S();return b=_a(A,I),I.available?new Map(I.references):dr(w,I.references)}catch(I){let A=S();return b=jo(A,I),Gr(w)}},v=R=>{if(R.length===0)return new Map;let w=Ho(R),I=w.filter(iy);if(I.length===0)return zr(w);let A=new Map,k=sy(I,p),T=[];for(let L of I)g.has(L.symbolId)?A.set(L.symbolId,g.get(L.symbolId)??[]):k.has(L.symbolId)?A.set(L.symbolId,k.get(L.symbolId)??[]):oy(L,m)?A.set(L.symbolId,[]):T.push(L);if(T.length===0)return _i(w,A,void 0);try{let L=c.calleesForDefinitions(T),F=S();b=_a(F,L);let N=_i(T,L.callees,d);for(let[re,ge]of N)A.set(re,ge);return _i(w,A,void 0)}catch(L){let F=S();return b=jo(F,L),zr(w)}},C=(R,w)=>{let I=Ho(R),A=Ho(w),k=A.filter(iy),T=new Map,L=sy(k,p),F=[];for(let N of k)L.has(N.symbolId)?T.set(N.symbolId,L.get(N.symbolId)??[]):oy(N,m)?T.set(N.symbolId,[]):F.push(N);if(I.length===0&&F.length===0)return{references:Gr(I),callees:_i(A,T,void 0)};try{let N=s?s.referencesAndCalleesForDefinitions(I,F):wD(a,c,{referenceDefinitions:I,calleeDefinitions:F}),re=S();b=_a(re,N);let ge=N.available?new Map(N.references):dr(I,N.references);for(let[ne,U]of N.callees)T.set(ne,U);let Me=_i(A,T,d);for(let[ne,U]of Me)g.set(ne,U);return{references:ge,callees:Me}}catch(N){let re=S();return b=jo(re,N),{references:Gr(I),callees:zr(A)}}},E=R=>{if(R.length===0)return new Map;let w=Ho(R);try{let I=l.signaturesForDefinitions(w),A=S();return b=_a(A,I),cy(w,I.signatures)}catch(I){let A=S();return b=jo(A,I),Oa(w)}};return{language:"rust",availability:y,dispose:()=>{s?.dispose()},importUsage:R=>{let w=f.get(R);if(w)return w;try{let I=u.importUsage(R);return f.set(R,I),I}catch(I){let A=S();return b=jo(A,I),[]}},referencesFor:R=>x([R]).get(R.symbolId)??[],referencesForDefinitions:x,referencesAndCalleesForDefinitions:C,calleesFor:R=>v([R]).get(R.symbolId)??[],calleesForDefinitions:v,signatureFor:R=>E([R]).get(R.symbolId)??null}}function _a(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 jo(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 bD(e){if(e.usePersistentSession!==void 0)return e.usePersistentSession;let t=process.env.SCIP_RUST_SEMANTIC_SESSION;return t!=="0"&&t!=="false"}function SD(){return{importUsageFacts:()=>({usage:[],positions:[]})}}function Ho(e){return e.map(t=>{let n=t;return{...t,leaf:typeof n.leaf=="string"?n.leaf:W(t.symbol),parentTypeName:n.parentTypeName??null,isFunctionLike:typeof n.isFunctionLike=="boolean"?n.isFunctionLike:Ae(t.symbol),isTypeLike:n.isTypeLike??!1,kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosingSymbol??null}})}function iy(e){return e.isFunctionLike}function oy(e,t){if(!t)return!1;try{return t(e)}catch{return!1}}function sy(e,t){if(!t||e.length===0)return new Map;try{return t(e)}catch{return new Map}}function vD(e,t){return{referencesForDefinitions:n=>RD(e,t,n)}}function CD(e,t){return{calleesForDefinitions:n=>ED(e,t,n)}}function xD(e,t){return{signaturesForDefinitions:n=>ID(e,t,n)}}function RD(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:Fu(r),references:Gr(n)};let i=ku();if(!Du(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:Gr(n)};let o=Oi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Mu),s=Ba(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),a=Oi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Tu),c=Ba(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),l=$o(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=Pu(process.execPath,[i],{cwd:e,input:JSON.stringify(u),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Ur(n.length,Lu(o,u.referenceRetryTimeoutMs),a)}),m=Nu(d.stdout);if(m)return{...Au(m),resolvedBinary:r.resolvedBinary,references:dr(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:Gr(n)}}function ED(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:Fu(r),callees:zr(n)};let i=ku();if(!Du(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:zr(n)};let o=Oi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Mu),s=Oi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Tu),a=Ba(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=$o(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=Pu(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Ur(n.length,o,s)}),d=Nu(u.stdout);if(d)return{...Au(d),resolvedBinary:r.resolvedBinary,callees:_i(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:zr(n)}}function ID(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:Fu(r),signatures:Oa(n)};let i=ku();if(!Du(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:Oa(n)};let o=Oi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Mu),s=Oi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Tu),a=Ba(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=$o(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=Pu(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Ur(n.length,o,s)}),d=Nu(u.stdout);if(d)return{...Au(d),resolvedBinary:r.resolvedBinary,signatures:cy(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:Oa(n)}}function wD(e,t,n){let r=n.referenceDefinitions.length>0?e.referencesForDefinitions(n.referenceDefinitions):{available:!0,references:Gr(n.referenceDefinitions)},i=n.calleeDefinitions.length>0?t.calleesForDefinitions(n.calleeDefinitions):{available:!0,callees:zr(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 Gr(e){return new Map(e.map(t=>[t.symbolId,[]]))}function zr(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Oa(e){return new Map(e.map(t=>[t.symbolId,null]))}function _i(e,t,n){let r=0,i=0;return _("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 cy(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function ku(){return yD(new URL("./rust-semantic-worker.js",import.meta.url))}function Au(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function Fu(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function Nu(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 Oi(e,t){return ur(e)??t}function Ba(e,t){if(!e)return t;let n=Number(e);return Number.isInteger(n)&&n>=0?n:t}import{existsSync as LD}from"fs";import{deserializeSCIP as PD,SymbolRole as DD}from"@c4312/scip";var _u=new WeakMap;function uy(e,t){let n=t.filter(MD);if(n.length===0)return new Map;let r=!1,i=0,o=0;return _("rust.scip-occurrence.callees",()=>{let s=AD(e);if(r=!!s,!s)return new Map;let a=new Map;for(let c of n){let l=TD(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 MD(e){return!(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||!e.isFunctionLike||e.leaf==="main"||Ze(e.symbol))}function TD(e,t,n){let r=Y(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)||!kD(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 kD(e,t){let n=ly(e),r=ly(t);if(n.size!==r.size)return!1;for(let[i,o]of n)if(r.get(i)!==o)return!1;return!0}function ly(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 AD(e){if(_u.has(e))return _u.get(e)??null;let t=FD(e);return _u.set(e,t),t}function FD(e){if(!e.generation.indexPath||!LD(e.generation.indexPath))return null;try{let t=He(e).filter(o=>o.symbol.startsWith("rust-analyzer ")&&o.relativePath.endsWith(".rs")&&o.isFunctionLike),n=new Map(t.map(o=>[o.symbol,o])),r=PD(yi(e.generation.indexPath,{inputKind:"SCIP occurrence-callee index",maxBytes:hi})),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&DD.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:Ze(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 $a=class{sessions=new WeakMap;getOrCreate(t,n,r){let i=ND(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 ND(e,t){return`${e.config.projectRoot}:${t}-workspace`}import{randomUUID as aM}from"crypto";import{existsSync as cM}from"fs";import{dirname as lM}from"path";function dy(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 fe}from"perf_hooks";function Yt(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}import fy from"path";import{realpathSync as my}from"fs";function _D(e,t){return e.getReferences().map(n=>{let r=n.getNode();return ja(r,t)})}function OD(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function gy(e,t,n,r){let i=[];for(let o of OD(e))for(let s of _D(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 Bi(i)}function hy(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();$i(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:ja(a,r),node:a}))}return i}function ja(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:$i(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function yy(e,t,n){let r=e.getSourceFile(),i=Bu(r,e),o=e.getText(),s=new RegExp(`\\b${Ne(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 Bi(c.filter(l=>$i(n,fy.join(n,l.file))===t))}function Ou(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 Bu(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function Bi(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 $i(e,t){let n=e||process.cwd(),r=py(n,t);if(r)return r;try{return py(my(n),my(t))}catch{return null}}function py(e,t){let n=fy.relative(e,t).replace(/\\/g,"/");return!n||n===".."||n.startsWith("../")?null:n}function by(e,t,n,r){let i=BD(t,r);return i.size===0?new Map:$D(e,n,i)}function BD(e,t){let n=new Map;for(let r of z(e,t)){let i=W(r.symbol)??r.leaf;if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return n}function $D(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of jD(e,o)){let a=n.get(s);if(!a)continue;let c=Bu(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 jD(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 HD=Xn("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function Sy(e,t,n,r){let i=Hu(e,t),o=$u(i.get(r)??[],n);if(o)return o;let s=[];for(let a of i.values())for(let c of a)((c.leaf||W(c.symbol)||"").includes(r)||c.symbol.includes(r))&&s.push(c);return $u(s,n)}function ju(e,t,n,r){return $u(Hu(e,t).get(r)??[],n)}function vy(e,t){let n=new Map;for(let[r,i]of Hu(e,t)){let o=i[0];o&&n.set(r,o)}return n}function Hu(e,t){return HD.get(e,t,()=>{let n=new Map;for(let r of z(e,t)){let i=r.leaf||W(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 $u(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 UD from"path";import{realpathSync as qD}from"fs";function Cy(e,t){let n=new Map,r=null,i=null,o=()=>(i??=ae(e,{extensions:ua}),i),s=()=>(r??=_("typescript.source-file-index",()=>GD(e.config.projectRoot,t,o()),()=>({projects:t.length,indexedDocuments:o().length})),r),a=c=>or(c)?Yt(n,c,()=>{let l=xy(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&&Uu(d,m)),m)return{project:u,sourceFile:m}}return null}):null;return{sourceFile:c=>a(c)?.sourceFile??null,sourceFileMatch:a,indexedTypeScriptLikeDocuments:o}}function GD(e,t,n){let r=t.map(({project:i})=>{let o=new Map;for(let s of i.getSourceFiles())Uu(o,s);return{project:i,sourceFiles:o}});for(let i of n){let o=xy(e,i);if(o)for(let s of r){if(s.sourceFiles.has(o))break;let a=s.project.addSourceFileAtPathIfExists(o)??null;if(a){Uu(s.sourceFiles,a);break}}}return r}function Uu(e,t){let n=qu(t.getFilePath());e.set(n,t);try{e.set(qu(qD(n)),t)}catch(r){if(!dt(r))throw r}}function xy(e,t){try{return qu(Vs(e,t,{inputKind:"indexed TypeScript source file"}).absolutePath)}catch(n){if(!dt(n))throw n;return null}}function qu(e){return UD.resolve(e)}function Gu(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Ry(e){let t=`${e.relativeDir}/src`;return[`${t}/index.ts`,`${t}/index.tsx`,`${t}/index.mts`,`${t}/index.cts`]}import{existsSync as Uo}from"fs";import ft from"path";var zu=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function Ku(e,t){let r=t?ft.dirname(ft.join(e,t)):e,i=ft.resolve(e);for(;r.startsWith(i);){for(let s of zu){let a=ft.join(r,s);if(Uo(a))return a}let o=ft.dirname(r);if(o===r)break;r=o}for(let o of zu){let s=ft.join(e,o);if(Uo(s))return s}return null}function Ey(e){let t=e.config.projectRoot,n=new Set(zD(t,e.config.semantic?.typescript?.tsconfigs)),r=ae(e,{includeIgnored:!1,extensions:ua});for(let i of r){let o=Ku(t,i);o&&n.add(ft.resolve(o))}if(n.size===0){let i=Ku(t);i&&n.add(ft.resolve(i))}return[...n].filter(i=>!Iy(t,i)).sort((i,o)=>i.localeCompare(o))}function zD(e,t=[]){let n=new Set;for(let r of t){let i=ft.isAbsolute(r)?r:ft.join(e,r);Uo(i)&&n.add(ft.resolve(i))}for(let r of KD(e))for(let i of zu){let o=ft.join(r,i);Uo(o)&&n.add(ft.resolve(o))}if(n.size===0){let r=Ku(e);r&&n.add(ft.resolve(r))}return[...n].filter(r=>!Iy(e,r)).sort((r,i)=>r.localeCompare(i))}function KD(e){let t=ft.join(e,"package.json");if(!Uo(t))return[];let n;try{n=JSON.parse(lt(t,"project package manifest"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>yf(e,i))}function Iy(e,t){let n=ft.relative(e,t).replace(/\\/g,"/");return n.startsWith("..")||n.includes("/node_modules/")||n.startsWith("node_modules/")||n.includes("/dist/")||n.startsWith("dist/")}var WD=32;function Ty(e,t){let n=_("typescript.provider.load",()=>da());if(!n)return ma("ts-morph is not installed");let r=_("typescript.provider.tsconfig-discovery",()=>Ey(e));if(r.length===0)return ma("no tsconfig found");try{let i=_("typescript.provider.project-bundles",()=>lg(n,r),()=>({tsconfigs:r.length}));return VD(e,n,i)}catch(i){return ma(i instanceof Error?i.message:String(i),r[0],r)}}function VD(e,t,n,r={}){return _("typescript.provider.construct",()=>new Wu(e,t,n),()=>({tsconfigs:n.length,reusedProjects:r.reusedProjects===!0}))}var Wu=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=hf(t.config.projectRoot),this.sourceFiles=Cy(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 Yt(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let r=JD();return _("typescript.import-usage.file",()=>this.importUsageForSourceFile(t,n,r),()=>({file:t,...r}))})}referencesFor(t){return Yt(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);return this.referencesForDefinitionNode(t,n)})}referencesForDefinitions(t,n={}){let r=new Map,i=ke(),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=>!Ly(u));if(a.length>=WD){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=>Ly(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=Py();_("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,...Dy(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=He(this.db).filter(o=>or(o.relativePath)),r=t.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(n,r);return ug(n,i,r)}referencesForDefinitionsBySymbolScan(t,n){let r=ke(),i=Py(),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 _("typescript.references-map.inverted-scan",()=>{let c=r?fe.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+=fe.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?fe.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+=fe.now()-f);let g=r?fe.now():0;this.addHierarchyMemberReferences(t,o,r?i:void 0),r&&(i.hierarchyMs+=fe.now()-g);for(let[h,b]of o){let S=Bi(b);o.set(h,S),r&&(i.referenceCount+=S.length)}},()=>({definitions:t.length,...Dy(i)})),o}addReferencesFromSourceFileScan(t,n,r,i,o,s,a,c,l,u){let d=this.compilerCheckerForSourceFile(t),m=t.compilerNode,p=ZD(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=Yt(c,h,()=>this.compilerSymbolKeys(h)),y=null,x=null,v=b&&r.has(b.symbolId)?i.get(b.symbolId):void 0;if(v&&(y=Ha(m,g),!wy(v,n,y))){let C=m.getLineAndCharacterOfPosition(g.getStart(m));x={file:n,line:C.line,column:C.character};let E=l.get(v.symbolId)??[];E.push(x),l.set(v.symbolId,E),u&&(u.requestedHits+=1)}for(let C of S)for(let E of o.get(C)?.values()??[]){if(y??=Ha(m,g),wy(E,n,y))continue;if(!x){let w=m.getLineAndCharacterOfPosition(g.getStart(m));x={file:n,line:w.line,column:w.character}}let R=l.get(E.symbolId)??[];R.push(x),l.set(E.symbolId,R),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=$i(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 Yt(this.calleesCache,t.symbolId,()=>Yt(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?fe.now():0,o=this.packageImportReferencesForDefinition(t);if(r&&(r.packageRefsMs+=fe.now()-i,r.packageReferenceCount+=o.length),!n)return o;let s=r?fe.now():0,a=gy(n,t,o,this.db.config.projectRoot);return r&&(r.semanticRefsMs+=fe.now()-s,r.referenceCount+=a.length),a}signatureFor(t){return Yt(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 My(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${My(o)}`})}importUsageForSourceFile(t,n,r){let i=[],o=new Map;for(let s of n.getImportDeclarations()){r.declarations+=1;let a=_l(this.db,t,s.getModuleSpecifierValue()),c=s.getImportClause()?.isTypeOnly()??!1;for(let l of Vu(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||XD(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:ja(s,this.db.config.projectRoot),node:s}),r.matchedReferences+=1;break}}}),i.map(s=>s.typeOnlyDeclaration?YD(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 hy(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=>!Ou(c.node)),s=i.some(c=>Ou(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=Gu(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,Bi(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,Bi(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=Gu(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of Vu(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=yy(a.identifier,r,this.db.config.projectRoot);l.length>0&&rM(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 Ry(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?_l(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 Yt(this.indexedDefinitionLeafCache,t,()=>vy(this.db,t)).get(n)??null}nodeForDefinition(t){return Yt(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return Yt(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?by(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?fe.now():0,s=t.declarations??[];n&&(n.declarationsMs+=fe.now()-o,n.declarationChecks+=s.length);for(let a of s){let c=n?fe.now():0,l=a.getSourceFile(),u=$i(this.db.config.projectRoot,l.fileName),d=l.getLineAndCharacterOfPosition(a.getStart(l)).line;if(n&&(n.declarationLocationMs+=fe.now()-c),!u||this.db.isIgnored(u))continue;let m=n?fe.now():0,p=this.compilerDeclarationName(a),f=r?ju(this.db,u,d,i)??(p&&p!==i?ju(this.db,u,d,p):null):Sy(this.db,u,d,i);if(n&&(n.indexedLookupMs+=fe.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=ke(),i=0,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=r?tM():void 0;return _("typescript.callee-map.file",()=>{let p=r?fe.now():0,f=this.sourceFiles.sourceFile(t);if(r&&(c=Math.round(fe.now()-p)),!f)return new Map;let g=r?fe.now():0,h=z(this.db,t).sort((R,w)=>R.startLine-w.startLine||w.endLine-R.endLine);if(r&&(l=Math.round(fe.now()-g)),i=h.length,h.length===0)return new Map;let b=new Map,S=r?fe.now():0,y=this.compilerCheckerForSourceFile(f),x=f.compilerNode;r&&(u=Math.round(fe.now()-S));let v=new Map,C=R=>{if(this.tsMorph.ts.isCallExpression(R)||this.tsMorph.ts.isNewExpression(R)){r&&(o+=1);let w=this.semanticCalleeForCallNode(y,x,h,R,v,n,m);w&&(r&&(s+=1),QD(b,w.callerId,w.target))}this.tsMorph.ts.forEachChild(R,C)},E=r?fe.now():0;C(x),r&&(d=Math.round(fe.now()-E));for(let[R,w]of b)b.set(R,iM(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?nM(m):{}}))}semanticCalleeForCallNode(t,n,r,i,o,s,a){let c=a?fe.now():0,l=eM(r,Ha(n,i));if(a&&(a.callerLookupMs+=fe.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?fe.now():0;m=this.definitionFromCompilerSymbol(d,a),a&&(a.targetLookupMs+=fe.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:Ha(n,i)}}:null}compilerSymbolForExpression(t,n,r){let i=r?fe.now():0,o=t.getSymbolAtLocation(n);if(r&&(r.expressionSymbolMs+=fe.now()-i),o)return o;r&&(r.typeFallbacks+=1);let s=r?fe.now():0,a=t.getTypeAtLocation(n).getSymbol();return r&&(r.typeSymbolMs+=fe.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 Vu(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 YD(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 JD(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function XD(e){for(let t=e;t;t=t.getParent())if(t.getKindName()==="ImportDeclaration")return!0;return!1}function QD(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function ZD(e){let t=new Set;for(let n of e.getImportDeclarations())for(let r of Vu(n))r.localName&&t.add(r.localName);return t}function eM(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 Ha(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line}function wy(e,t,n){return t===e.relativePath&&n>=e.startLine&&n<=e.endLine}function Ly(e){return e.symbol.includes("#")?Kt(e.symbol)==="type"&&e.relativePath.endsWith(".d.ts"):!1}function tM(){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 nM(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 Py(){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 Dy(e){return{...e,scanMs:Math.round(e.scanMs),packageRefsMs:Math.round(e.packageRefsMs),semanticRefsMs:Math.round(e.semanticRefsMs),hierarchyMs:Math.round(e.hierarchyMs)}}function rM(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function iM(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 My(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}import{join as oM}from"path";var Ua=3;var sM="typescript-semantic";function ky(e){let t=oM(e,sM),n=ca(t);return{...n,requestDir:n.legacyRequestDir}}function Ay(e){return dg(e)}var uM=12e4,dM=5;function _y(e,t,n={}){let r=new Yu(e,n),i=null,o=null,s=process.env.SCIP_QUERY_SKIP_WATCH_SERVICE==="1",a=()=>(i??=Ty(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=>Ny(p),()=>a().referencesForDefinitions?.(d,m)??new Map(d.map(p=>[p.symbolId,a().referencesFor(p)]))),u=d=>c({kind:"callees",definitions:[...d]},m=>Ny(m),()=>a().calleesForDefinitions?.(d)??new Map(d.map(m=>[m.symbolId,a().calleesFor(m)])));return{language:"typescript",availability:()=>(o??=c({kind:"availability"},fM,()=>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=>pM(m),()=>a().referenceFragmentsForFiles?.(d)??new Map),calleesFor:d=>u([d]).get(d.symbolId)??[],calleesForDefinitions:u,signatureFor:d=>c({kind:"signature",definition:d},gM,()=>a().signatureFor(d)),dispose:()=>i?.dispose?.()}}var Yu=class{constructor(t,n={}){this.db=t;this.runtime=n.runtime??yM,this.timeoutMs=n.timeoutMs??hM(),this.mailboxLimits=n.mailboxLimits??{},this.cacheDir=lM(t.config.dbPath),this.projectRoot=Rf(t.config.projectRoot)}db;runtime;timeoutMs;cacheDir;projectRoot;mailboxLimits;request(t){let n=cg(this.cacheDir),r=ky(this.cacheDir),i=zl(n.statePath);if(!Fy(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??Wt)()+this.timeoutMs,l=Sf(),u=Li("typescript-semantic-v3",{generation:o,profileEnvironment:l,request:t}),d=Pi(u),m=la(r,{mailboxVersion:Br,operationKey:u,clientId:this.runtime.randomId(),enqueuedAtMs:s,deadlineAtMs:a,protocolVersion:Ua,id:d,generation:o,profileEnvironment:l,request:t},{nowMs:s,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??Wt)()<=c;){if(cM(m.responsePath))return mM(Ut(m.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript semantic mailbox response"}),d,o,u);let p=zl(n.statePath);if(!Fy(p,this.projectRoot,this.runtime))throw new Error("TypeScript semantic service stopped while processing a request.");this.runtime.sleep(dM)}throw new Error(`TypeScript semantic service timed out after ${this.timeoutMs}ms.`)}};function Fy(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptSemantic?.protocolVersion===Ua&&n.isProcessAlive(e.pid)&&(!e.processIdentity||r!=null&&aa(e.processIdentity,r))}function mM(e,t,n,r){let i=JSON.parse(e);if(i.protocolVersion!==Ua||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 Ny(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid numeric map.");return new Map(e)}function pM(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid string map.");return new Map(e)}function fM(e){let t=dy(e);if(!t)throw new Error("TypeScript semantic service wrote invalid availability.");return t}function gM(e){if(e!==null&&typeof e!="string")throw new Error("TypeScript semantic service wrote an invalid signature.");return e}function hM(){let e=Number(process.env.SCIP_TYPESCRIPT_SEMANTIC_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:uM}var yM={now:Date.now,monotonicNow:Wt,randomId:aM,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:Ii,readProcessIdentity:wi};var Oy=new $a;lf({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>Oy.clear(e)});function Kr(e,t){let n=et(t)??"typescript";return Oy.getOrCreate(e,n,()=>n==="rust"?ay(e.config.projectRoot,{sourceImportUsageResolver:{importUsageFacts:r=>Eh(e,r)},calleeSymbolResolver:Rh(e),sourceZeroCalleeOracle:r=>bM(e,r),scipOccurrenceCalleeOracle:r=>uy(e,r)}):_y(e,t))}function et(e){return e?de(e)==="rust"?"rust":or(e)?"typescript":null:"typescript"}function bM(e,t){let n=Y(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 SM=/^[A-Za-z_][A-Za-z0-9_]*$/,By=/\bDefault::default\b/g,vM=/^\.\.\s*Default::default\b/;function $y(e,t){let n=new Map,r=new Map;for(let i of t){let o=Ju(e,i,r);o!==null&&n.set(i.symbolId,o)}return n}function Ju(e,t,n=new Map){let r=xM(t.symbol);if(!r)return null;let i=oa(e,[t.symbolId]);if(i.length===0)return null;let o=new RegExp(`(^|[^A-Za-z0-9_])${Ne(r)}::default\\b`,"g"),s=new RegExp(`(^|[^A-Za-z0-9_])${Ne(r)}\\s*$`),a=CM(e,t.symbolId),c=[];for(let l of i){let u=RM(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=vM.exec(b.slice(x));if(v){if(a&&p.includes(m)){let E=x+v[0].lastIndexOf("default");c.push({file:l.relative_path,line:g,column:E}),S.add(E),f+=1}x+=v[0].length-1;continue}let C=b[x];if(C==="{"){let E=s.test(b.slice(0,x));m+=1,E&&p.push(m);continue}if(C==="}")for(m=Math.max(0,m-1);p.length>0&&p[p.length-1]>m;)p.pop()}for(By.lastIndex=0;y=By.exec(b);){let x=y.index+9;if(!S.has(x))return null}}if(f===0)return null}return ka(c)}function CM(e,t){return e.get("SELECT 1 AS present FROM mentions WHERE symbol_id = ? AND role = 1 LIMIT 1",t)?.present===1}function xM(e){let t=/impl#\[([^\]]+)\]\[Default\]default\(\)\./.exec(e)?.[1]??null;return!t||!SM.test(t)?null:t}function RM(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:EM(e,t);return n.set(t,i),i}function EM(e,t){try{return ut(e.config.projectRoot,t,{inputKind:"indexed Rust source file"})}catch(n){if(!dt(n))throw n;return null}}var IM="typescript-import-usage-v1",wM="typescript-signatures-v1",Xu=Le("semantic-prefetched-callees",{clearGroups:["whole-project","source-file","semantic-provider"]}),jy=po({kind:"semantic-import-usage",invalidation:Qe("semantic-import-usage"),serialize:e=>JSON.stringify(e),deserialize:Xy}),Hy=po({kind:"semantic-signatures",invalidation:Qe("semantic-signatures"),serialize:e=>JSON.stringify(e),deserialize:NM}),Uy=Dt({kind:"typescript-import-usage",invalidation:Qe("typescript-import-usage"),serialize:e=>JSON.stringify(e),deserialize:Xy}),qy=Dt({kind:"typescript-signatures",invalidation:Qe("typescript-signatures"),serialize:e=>JSON.stringify(e),deserialize:_M});function Rt(e){let t=new Map,n=new Set;return{capability:(r,i)=>Qy(e,r,i),importUsage:r=>PM(e,r),references:r=>Ky(e,r),materializeReferences:(r,i)=>Vy(e,r,t,n,i),callerMap:r=>DM(e,r,t,n),calleeMap:r=>kM(e,r),signature:r=>AM(e,r)}}function LM(e,t){if(t.size===0)return;let n=Xu.get(e,()=>new Map);for(let[r,i]of t)n.set(r,[...i])}function zy(e,t){if(!Xu.has(e))return{hits:[],misses:[...t]};let n=Xu.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 Go(e,t){return Rt(e).importUsage(t)}function PM(e,t){if(et(t)==="typescript"){let o="fallback",s=0,a=0,c=0,l=0;return _("typescript.import-usage.materialize",()=>{let u=bo(e,t,IM);if(u?.key){s=1;let m=Uy.read(e,t,u.key);if(m)return o="hit",a=1,m;c=1;let p=gn(e,t);if(!p)return o="unavailable",[];let f=p.importUsage(t);return Uy.write(e,t,u.key,f),o="computed",f}l=1;let d=gn(e,t);return d?(o="direct-fallback",d.importUsage(t)):(o="unavailable",[])},()=>({state:o,eligible:s,cacheHits:a,cacheMisses:c,fallbacks:l}))}let n=Jy(e,"semantic-import-usage",t);if(n){let o=jy.read(e,t,n);if(o)return o}let r=gn(e,t);if(!r)return[];let i=r.importUsage(t);return n&&jy.write(e,t,n,i),i}function qa(e,t){return Rt(e).references(t)}function Ky(e,t){let n=Ju(e,t);if(n)return n;let r=Lh(e,t);if(r)return r;let i=gn(e,t.relativePath);return i?i.referencesFor(t):[]}function mr(e,t){return Rt(e).callerMap(t)}function Wy(e,t){let n=new Map,r=new Map;for(let i of t){if(et(i.relativePath)==="typescript"){let o=gn(e,i.relativePath);if(!o)continue;let s=r.get(o)??[];s.push(i),r.set(o,s);continue}Qu(e,n,i,Ky(e,i))}for(let[i,o]of r){let s=Wl(e,o,c=>Kr(e,c)),a=s?.references??(i.referencesForDefinitions?i.referencesForDefinitions(o,{exact:!0}):new Map(o.map(c=>[c.symbolId,i.referencesFor(c)])));!s&&ke()&&Kl(e,o,a,c=>Kr(e,c));for(let c of o)Qu(e,n,c,a.get(c.symbolId)??[])}return n}function DM(e,t,n=new Map,r=new Set){let i=new Map,o=Vy(e,t,n,r),s=0;return _("semantic.callers.from-references",()=>{for(let a of t)s+=Qu(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 Vy(e,t,n,r,i={}){let o=Pn(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,E=t.filter(w=>et(w.relativePath)==="typescript"&&!n.has(w.symbolId)&&!r.has(w.symbolId)),R=Wl(e,E,w=>Kr(e,w));if(R){b=E.length,S=R.cacheHits,y=R.cacheMisses,x=R.computedFiles;for(let w of E)n.set(w.symbolId,R.references.get(w.symbolId)??[])}if(_("semantic.references.cache-scan",()=>{for(let[w,I]of Da(t)){let A=[];for(let L of I)n.has(L.symbolId)?u+=1:r.has(L.symbolId)?h+=1:A.push(L);if(A.length===0){g+=1;continue}let k=MM(e,o,w);if(!k){for(let L of A)et(L.relativePath)||(l+=1),c.push(L);continue}f+=1;let T=mf(e,w,k);for(let L of A){let F=T.get(L.symbol)??null;if(F!==null){let N=TM(F);if(N){d+=1,n.set(L.symbolId,N);continue}m+=1}a.push({definition:L,cacheFingerprint:k})}}},()=>({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=_("semantic.references.compute-misses",()=>{let w=Zu(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)&&Qy(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&&_("semantic.references.cache-write",()=>pf(e,s),()=>({entries:s.length})),C.size>0&&Kl(e,v,C,w=>Kr(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 MM(e,t,n){if(!t)return null;let r=et(n);return r==="typescript"?t:r==="rust"?ln(JSON.stringify({kind:"semantic-references",language:r,engine:qr(e.config.projectRoot),projectFingerprint:t})):null}function Zu(e,t,n={}){let r=ke(),i=new Map,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=0,p=0;return _("semantic.references.provider-loop",()=>{let f=$y(e,t),g=wh(e,t),h=new Map,b=n.prefetchCallees?new Map:null,S=[];for(let x of t){let v,C=()=>(v??=gn(e,x.relativePath),v);if(b){let I=C();if(I?.referencesAndCalleesForDefinitions){let A=b.get(I);A?A.push(x):b.set(I,[x]),p+=1}}let E=f.get(x.symbolId);if(E){a+=1,c+=E.length,qo(i,x.symbolId,E,r,I=>{d+=1,m+=I});continue}let R=g.get(x.symbolId);if(R){l+=1,u+=R.length,qo(i,x.symbolId,R,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)??[],E=x.referencesAndCalleesForDefinitions(C,v);y.add(x),LM(e,E.callees);for(let R of C){if(!E.references.has(R.symbolId))continue;let w=E.references.get(R.symbolId)??[];qo(i,R.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 E of v){if(!C.has(E.symbolId))continue;let R=C.get(E.symbolId)??[];qo(i,E.symbolId,R,r,w=>{d+=1,m+=w})}}for(let{provider:x,definition:v}of S){let C=x.referencesFor(v);qo(i,v.symbolId,C,r,E=>{d+=1,m+=E})}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 qo(e,t,n,r,i){e.set(t,n),r&&n.length>0&&i(n.length)}function Qu(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 TM(e){try{return JSON.parse(e)}catch{return null}}function Ga(e,t){return Rt(e).calleeMap(t)}function kM(e,t){let n=ke(),r=new Map,i=0,o=0,s=0,a=0;return _("semantic.callees.provider-loop",()=>{let c=new Map,l=[];for(let u of t){let d=gn(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)??[];Gy(r,p.symbolId,f,n,g=>{s+=1,a+=g})}}for(let{provider:u,definition:d}of l){let m=u.calleesFor(d);Gy(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 Gy(e,t,n,r,i){n.length>0&&(e.set(t,n),r&&i(n.length))}function Yy(e,t){return Rt(e).signature(t)}function AM(e,t){if(et(t.relativePath)==="typescript"){let s="fallback",a=0,c=0,l=0,u=0;return _("typescript.signature.materialize",()=>{let d=bo(e,t.relativePath,wM);if(d?.key){a=1;let p=qy.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=gn(e,t.relativePath);if(!f)return s="unavailable",null;let g=f.signatureFor(t);return qy.write(e,t.relativePath,d.key,{...p,[t.symbol]:g}),s="computed",g}u=1;let m=gn(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=Jy(e,"semantic-signatures",t.relativePath),r=FM(t);if(n){let s=Hy.read(e,r,n);if(s)return s.signature}let i=gn(e,t.relativePath);if(!i)return null;let o=i.signatureFor(t);return n&&Hy.write(e,r,n,{signature:o}),o}function Jy(e,t,n){let r=Pn(e);if(!r)return null;let i=et(n);return i!=="rust"?null:ln(JSON.stringify({kind:t,language:i,engine:qr(e.config.projectRoot),projectFingerprint:r}))}function FM(e){return`${e.relativePath}\0${e.symbol}`}function Xy(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 _M(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 Qy(e,t,n){let r=et(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,...Kr(e,n).availability()}}catch(i){return{slot:t,language:r,available:!1,reason:i instanceof Error?i.message:String(i)}}}function gn(e,t){if(!et(t))return null;let n=Kr(e,t);return n.availability().available?n:null}var ue={references:qa,referenceMap:Zu,callerMap:(e,t)=>Rt(e).callerMap(t),calleeMap:ed};function ed(e,t){let n=ke(),r=new Map,i=zy(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=OM(e,i.hits);if(f.entries.length>0&&_("semantic.callees.prefetch-cache-write",()=>Fl(e,f.entries),()=>({entries:f.entries.length,sourceMissing:f.sourceMissing,skippedUnsupportedLanguage:f.skippedUnsupportedLanguage})),_("semantic.callees.cache-scan",()=>{for(let[y,x]of Da(i.misses)){if(!et(y)){n&&(a+=x.length);continue}let v=X(e,y);if(!v){n&&(c+=x.length),s.push(...x);continue}let C=Ht(e,y,v),E=Zy(e,y);if(!E){s.push(...x);continue}let R=df(e,y,C,E);for(let w of x){let I=R.get(w.symbol)??null;if(I!==null){let A=$M(I);if(A){n&&(l+=1),A.length>0&&r.set(w.symbolId,A);continue}n&&(u+=1)}o.push({def:w,contentHash:C,depsDigest:E})}}},()=>({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=_("semantic.callees.compute-misses",()=>{let y=Ga(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=>Rt(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?_("semantic.callees.cache-write",()=>Fl(e,S),()=>({entries:S.length})):_("semantic.callees.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",misses:o.length})),r}function OM(e,t){let n=[],r=new Map,i=0,o=0;for(let{definition:s,callees:a}of t){if(!et(s.relativePath)){o+=1;continue}if(!r.has(s.relativePath)){let l=X(e,s.relativePath),u=l?Zy(e,s.relativePath):null;r.set(s.relativePath,l&&u?{contentHash:Ht(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 BM="typescript-callees-v2-callsite-line";function Zy(e,t){let n=et(t);if(n==="typescript")return bo(e,t,BM)?.key??null;let r=HM(e,t);return n==="rust"?ln(JSON.stringify({kind:"semantic-callees",language:n,engine:qr(e.config.projectRoot),positionMapping:"nearby-leaf-v2-callsite-line",depsDigest:r})):r}function $M(e){try{return JSON.parse(e)}catch{return null}}var jM=Xn("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function HM(e,t){return jM.get(e,t,()=>{let r=[...qe(e).get(t)??[]].sort().map(i=>`${i}:${Ht(e,i,X(e,i))}`);return ln(r.join("|"))})}function l8(e,t,n={}){let r=le(e,t);if(!r)return[];let o=!Ae(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine}]:[],s=ir(e,r,{semantic:n.semantic,semanticEvidence:ue}).map(u=>({relativePath:u.file,line:u.line})),a=UM(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 UM(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=qM(t.symbol);if(n.length===0)return[];let r=[];for(let i of ae(e,{extensions:[".rb"],includeIgnored:!1})){let o=X(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 qM(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 pd,statSync as bk}from"fs";import{join as Sk}from"path";import{existsSync as ji}from"fs";import{randomUUID as yb}from"crypto";import{isAbsolute as CT,join as _n,relative as xT,resolve as RT}from"path";var pr=1,fr=2,GM="./node_modules/scip-query/docs/schemas/project-config.schema.json";function td(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(!se(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?pr:n;if(r!==pr&&r!==fr)return{kind:"unsupported",schemaVersion:r,direction:r<pr?"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=za(t),s=r!==fr||typeof t.$schema!="string";return r===pr?{kind:"legacy",sourceVersion:pr,config:o,needsMigration:s}:{kind:"supported",sourceVersion:fr,config:o,needsMigration:s}}function za(e){let t=e,{$schema:n,schemaVersion:r,...i}=t;return{$schema:typeof n=="string"&&n.trim()!==""?n:GM,schemaVersion:fr,...i}}function eb(e){return`${JSON.stringify(za(e),null,2)}
|
|
53
|
+
`}import{createHash as zM}from"crypto";var yn=1,hr=2,ob=1,od=1,id="sha256",KM=1;function Vr(e,t,n){if(!tn(e)||!Gs(t))throw new Error("Observation identity requires a bounded projection name and positive projection version.");return{schemaVersion:ob,canonicalizationVersion:od,hashAlgorithm:id,projection:{name:e,version:t},digest:zM(id).update(WM(e,t,n)).digest("hex")}}function WM(e,t,n){return`{"canonicalizationVersion":${od},"projection":${JSON.stringify(e)},"projectionVersion":${t},"value":${JSON.stringify(n)}}`}function VM(e){if(!se(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===yn)return tT(e)?{kind:"legacy",schemaVersion:yn,receipt:e}:{kind:"malformed",reason:"observation receipt v1 fields are malformed or contradictory"};if(t===hr)return nT(e)?{kind:"supported",schemaVersion:hr,receipt:e}:{kind:"malformed",reason:"observation receipt v2 facts are malformed or contradictory"};let n=t;return{kind:"unsupported",schemaVersion:n,direction:n<yn?"older":"future"}}function Ka(e){let t=VM(e);return t.kind==="legacy"||t.kind==="supported"}function YM(e,t){return{collaborationDomain:Wr(hn(e,n=>n.facts.collaborationDomain),hn(t,n=>n.facts.collaborationDomain)),repositoryLineage:Wr(hn(e,n=>n.facts.repositoryLineage),hn(t,n=>n.facts.repositoryLineage)),workspaceInstance:Wr(hn(e,n=>n.facts.workspaceInstance),hn(t,n=>n.facts.workspaceInstance)),wholeContent:Wr(hn(e,n=>n.facts.wholeContent),hn(t,n=>n.facts.wholeContent)),relevantInputs:JM(e,t),indexInput:Wr(hn(e,n=>n.facts.index?.inputs),hn(t,n=>n.facts.index?.inputs)),indexGeneration:XM(e,t),observationStability:ZM(e,t)}}function g8(e,t,n=YM(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=eT(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:KM,authority:i.length===0?"completion":o?"none":"advisory",requiredRelationships:["collaborationDomain","wholeContent","observationStability"],reasons:i}}function JM(e,t){let n=tb(e),r=tb(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:Wr(s?.identity,a?.identity)}})}function tb(e){return e.schemaVersion!==hr?new Map:new Map((e.facts.relevantInputs??[]).map(t=>[`${t.subject}\0${t.identity.projection.name}`,t]))}function XM(e,t){return e.schemaVersion===yn&&t.schemaVersion===yn?QM(e.index?.generationIdentity,t.index?.generationIdentity):e.schemaVersion===yn||t.schemaVersion===yn?Nn("unknown",["legacy-fact-not-comparable"],rb(e),rb(t)):Wr(e.facts.index?.generation,t.facts.index?.generation)}function QM(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?sb(n,r):Nn(e===t?"established":"disproven",[e===t?"identities-equal":"identities-different"],n,r)}function Wr(e,t){let n=e?[{kind:"identity",identity:e}]:[],r=t?[{kind:"identity",identity:t}]:[];return!e||!t?sb(n,r):sd(e,t)?Nn(e.digest===t.digest?"established":"disproven",[e.digest===t.digest?"identities-equal":"identities-different"],n,r):Nn("unknown",["identity-projections-not-comparable"],n,r)}function ZM(e,t){if(e.schemaVersion===yn||t.schemaVersion===yn)return Nn("unknown",["legacy-fact-not-comparable"],[],[]);let n=ib(e),r=ib(t),i=nb(e),o=nb(t);return i==="invalidated"||o==="invalidated"?Nn("disproven",[...i==="invalidated"?["left-observation-invalidated"]:[],...o==="invalidated"?["right-observation-invalidated"]:[]],n,r):i!=="fixed"||o!=="fixed"?Nn("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):Nn("established",["all-observed-sources-fixed"],n,r)}function nb(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 eT(e){if(e.schemaVersion!==hr)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=>sd(r.identity,t))?.identity;return n?n.digest===t.digest?"established":"disproven":"unknown"}function hn(e,t){return e.schemaVersion===hr?t(e):void 0}function rb(e){return e.schemaVersion===yn&&e.index?[{kind:"legacy-index-generation",value:e.index.generationIdentity}]:e.schemaVersion===hr&&e.facts.index?[{kind:"identity",identity:e.facts.index.generation}]:[]}function ib(e){return e.stabilityProofs.map(t=>({kind:"stability",proof:t}))}function sb(e,t){let n=e.length===0&&t.length===0?"both-facts-missing":e.length===0?"left-fact-missing":"right-fact-missing";return Nn("unknown",[n],e,t)}function Nn(e,t,n,r){return{state:e,reasons:t,facts:{left:n,right:r}}}function sd(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 tT(e){if(!se(e))return!1;let t=e.index,n=e.worktree;return cb(e.observedAt)&&tn(e.projectIdentity)&&lT(e.authorityKind)&&(t===void 0||se(t)&&tn(t.generationIdentity)&&(t.source==="immutable"||t.source==="legacy")&&(t.alignment==="not-certified"||t.alignment==="leased"))&&(n===void 0||se(n)&&tn(n.identity)&&typeof n.clean=="boolean"&&(n.headCommit===void 0||tn(n.headCommit))&&(n.treeOid===void 0||tn(n.treeOid)))&&cT(e.authorityKind,t,n)}function nT(e){if(!se(e))return!1;let t=e.facts,n=e.observedSources,r=e.stabilityProofs;if(!cb(e.observedAt)||!se(t)||!Array.isArray(n)||n.length===0||!n.every(iT)||!rd(n,c=>c.kind)||!Array.isArray(r)||!r.every(oT)||!rd(r,c=>c.source)||r.some(c=>!n.some(l=>l.kind===c.source))||!r.every(c=>aT(c,t))||["collaborationDomain","repositoryLineage","workspaceInstance","wholeContent"].some(c=>t[c]!==void 0&&!gr(t[c])))return!1;let o=t.relevantInputs;if(o!==void 0&&(!Array.isArray(o)||!o.every(rT)||!rd(o,c=>`${c.subject}\0${c.identity.projection.name}`)))return!1;let s=t.index;if(s!==void 0&&(!se(s)||!gr(s.generation)||s.inputs!==void 0&&!gr(s.inputs)||s.source!=="immutable"&&s.source!=="legacy"))return!1;let a=e.diagnostics;return(a===void 0||se(a)&&(a.clean===void 0||typeof a.clean=="boolean")&&(a.headCommit===void 0||tn(a.headCommit))&&(a.treeOid===void 0||tn(a.treeOid)))&&sT(t,n)}function gr(e){return!se(e)||!se(e.projection)?!1:e.schemaVersion===ob&&e.canonicalizationVersion===od&&e.hashAlgorithm===id&&tn(e.projection.name)&&Gs(e.projection.version)&&fi(e.digest)}function rT(e){return se(e)&&tn(e.subject)&&gr(e.identity)}function iT(e){return se(e)&&ab(e.kind)&&(e.identity===void 0||gr(e.identity))}function oT(e){return se(e)&&ab(e.source)&&(e.kind==="immutable"||e.kind==="fixed-snapshot"||e.kind==="bracketed"||e.kind==="not-established"||e.kind==="invalidated")}function sT(e,t){let n=e.index,r=t.find(c=>c.kind==="index-generation");if(r){if(!se(n)||!gr(n.generation)||r.identity&&!nd(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&&(!gr(i)||!nd(o.identity,i)))return!1;let s=e.wholeContent,a=t.find(c=>c.kind==="repository-snapshot");return!(a?.identity&&(!gr(s)||!nd(a.identity,s)))}function aT(e,t){return e.kind==="not-established"||e.kind==="invalidated"?!0:e.source==="index-generation"?e.kind==="immutable"&&se(t.index)&&t.index.source==="immutable":e.source==="repository-snapshot"?e.kind==="fixed-snapshot":e.source==="live-workspace"?e.kind==="bracketed":!1}function nd(e,t){return sd(e,t)&&e.digest===t.digest}function cT(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 lT(e){return e==="index-worktree"||e==="index-only"||e==="worktree-only"||e==="process-local"}function ab(e){return e==="index-generation"||e==="repository-snapshot"||e==="live-workspace"||e==="process"}function cb(e){return typeof e=="string"&&!Number.isNaN(Date.parse(e))}function rd(e,t){return new Set(e.map(t)).size===e.length}function Wa(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")&&cf.includes(t.reasonCode)&&Array.isArray(t.evidence)&&t.evidence.length>0&&t.evidence.every(uT)&&(t.observation===void 0||Ka(t.observation))&&!!t.invalidateOn&&typeof t.invalidateOn=="object"&&typeof t.invalidateOn.targetContentChange=="boolean"&&typeof t.invalidateOn.detectorMajorChange=="boolean"}function uT(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 Va=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 Yr(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 Va(t,e.length,r);return new RegExp(e,n)}import{createHash as lb}from"crypto";import{closeSync as dT,fstatSync as ub,openSync as mT,rmSync as pT}from"fs";import{dirname as fT}from"path";var gT=2e3,hT=10,yT=3,Ja=class extends Error{constructor(n,r,i){super(`Concurrent edit detected for ${n}; expected revision ${mb(r)}, but found ${mb(i)}. The latest file was left untouched.`);this.path=n;this.original=r;this.latest=i;this.name="FileRevisionConflictError"}path;original;latest},zo=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 Ko(e,t,n={}){let r=bT(e,n.lockTimeoutMs??gT,n.monotonicNow??Wt);try{let i=Math.max(0,Math.floor(n.maxRetries??yT));for(let o=0;;o+=1){let s=Ya(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=Ya(e);if(!vT(s.revision,c.revision)){if(o<i)continue;throw new Ja(e,s.revision,c.revision)}try{ST(e,a,s.revision)}catch(l){if(l.code==="EEXIST"){let u=Ya(e);if(o<i)continue;throw new Ja(e,s.revision,u.revision)}throw l}return{changed:!0,attempts:o+1,previous:s,current:Ya(e)}}}finally{r.release()}}function Ya(e){for(let t=0;t<4;t+=1){let n;try{n=mT(e,"r");let r=db(ub(n)),i=gf(n,{maxBytes:Mn,inputKind:"revisioned text file"}),o=db(ub(n));if(!pb(r,o))continue;return{path:e,text:i,revision:{exists:!0,hash:lb("sha256").update(i).digest("hex"),identity:o}}}catch(r){if(r.code==="ENOENT")return{path:e,text:"",revision:{exists:!1,hash:lb("sha256").update("").digest("hex")}};throw r}finally{n!==void 0&&dT(n)}}throw new Error(`Could not read a stable revision of ${e}; the file is changing continuously.`)}function bT(e,t,n){let r=`${e}.scip-query-write.lock`,i=n()+Math.max(0,t);for(;;){let o=Di(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,hT)}}function ST(e,t,n){if(t.kind==="delete"){if(!n.exists)return;pT(e),If(fT(e));return}let r=t.mode??n.identity?.mode;n.exists?ig(e,t.text,{durability:"durable",mode:r}):og(e,t.text,{durability:"durable",mode:r})}function vT(e,t){return e.exists===t.exists&&e.hash===t.hash&&(e.identity===void 0?t.identity===void 0:t.identity!==void 0&&pb(e.identity,t.identity))}function db(e){return{dev:e.dev,ino:e.ino,size:e.size,mtimeMs:e.mtimeMs,mode:e.mode&511}}function pb(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.mode===t.mode}function mb(e){return e.exists?e.hash.slice(0,12):"<absent>"}var yr=".scipquery.json",bb=2e3,Xa=5e3,ad=Xa,Sb=15*6e4,cd={enabled:!0,windowMs:15*6e4,maxRebuilds:2,maxEstimatedWriteBytes:1024*1024*1024},ET={enabled:!1,debounceMs:bb,cooldownMs:ad,gitPollMs:2e3,idleTimeoutMs:Sb,autoRefresh:!0,ignore:[],resourceBudget:cd};var IT=new Set(["$schema","schemaVersion","collaborationDomainId","languages","indexerConcurrency","watch","indexer","dbPath","entryRoots","semantic","suppressions","declaredCouplings","locality","architecture","coverageContracts","docs"]),wT=new Set(["enabled","debounceMs","cooldownMs","gitPollMs","idleTimeoutMs","autoRefresh","ignore","resourceBudget"]),LT=new Set(["enabled","windowMs","maxRebuilds","maxEstimatedWriteBytes"]),PT=new Set(["pathPrefixes","files","symbolPatterns","qualifiedVars"]),DT=new Set(["typescript","rust"]),MT=new Set(["tsconfigs"]),TT=new Set(["rustAnalyzerPath"]),fb=new Set(kl),kT=new Set(["pnpmWorkspaces","projectMode","projects","configPath","maxWarmSessions","workerIdleMs","workerSoftMemoryMb"]),AT=new Set(["architecturalBoundarySegments"]),FT=new Set(["boundaries","allowedDependencies","requireCompletePolicy","requireCompleteCoverage","requireAcyclic","requireResolvedBoundaries","requireMinimalPolicy","maxBoundaryFanOut","maxBoundaryFiles","testPaths"]),NT=new Set(["name","paths","subUnits","maxFiles"]),_T=new Set(["snapshotPaths"]),OT=new Set(["name","files","reason"]),BT=new Set(["id","check","file","reason","expiresAt","createdAt","decision"]),$T=new Set(["kind","reasonCode","decidedBy","policyVersion","observation","evidence","invalidateOn"]),jT=new Set(["kind","referent","claim","contentHash","generation"]),HT=new Set(["targetContentChange","detectorMajorChange"]),UT=new Set(["name","file","keys","mustEqual","allowExtra"]),qT=new Set(["type","identifier","marker"]),GT=new Set(["type","path","pattern"]),zT=new Set(["object-literal-keys","string-array","markdown-list"]),KT=new Set(["top-level-dirs","file-glob","registered-commands","builtin-skills"]);function vb(e){let t=_n(e,yr);if(!ji(t))return{};let n;try{n=Ut(t,{maxBytes:Ks,inputKind:"scip-query project config"})}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`unable to read ${yr} at ${t}: ${i}`,{cause:r})}return xb(td(n),t,"read").config}function U8(e,t={}){let n=[];return rk(e,n),WT(e,n),VT(e,n),YT(e,n,t),JT(e,n),ZT(e,n),XT(e,n,t),QT(e,n,t),nk(e,n,t),tk(e,n),n}function gb(e,t,n,r,i){if(!r)return;let o=RT(r,n),s=xT(r,o);if(s.startsWith("..")||CT(s)){e.push({level:"error",path:t,message:i.outside});return}ji(o)||e.push({level:"warning",path:t,message:i.missing})}function WT(e,t){let n=e;n.schemaVersion!==void 0&&n.schemaVersion!==fr&&t.push({level:"error",path:"schemaVersion",message:`Must be ${fr}; unversioned and v${pr} 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(kl);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{Yr(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 VT(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<Xa&&t.push({level:"warning",path:"watch.cooldownMs",message:`Values below ${Xa}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?.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 YT(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."}):gb(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]])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."}):gb(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 JT(e,t){if(e.locality===void 0)return;if(!se(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 XT(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&&!ji(_n(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 QT(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(!se(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&&!ji(_n(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&&!Wa(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"&&!ji(_n(n.projectRoot,c.referent))&&t.push({level:"error",path:`${s}.decision.evidence[${a}].referent`,message:`Suppression counterevidence does not exist: ${c.referent}`})}}function ZT(e,t){if(e.architecture===void 0)return;if(!se(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(!se(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}ek(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&&!se(o))t.push({level:"error",path:"architecture.allowedDependencies",message:"Must be an object keyed by boundary name."});else if(se(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=se(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 ek(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 tk(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 nk(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(!se(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&&!ji(_n(n.projectRoot,i.file))&&t.push({level:"warning",path:`${o}.file`,message:`Coverage contract file does not exist: ${i.file}`}),hb(t,i.keys,`${o}.keys`,zT,"Unknown coverage-contract key extractor type."),hb(t,i.mustEqual,`${o}.mustEqual`,KT,"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 hb(e,t,n,r,i){if(!se(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 q8(e){return{...ET,...e.watch,cooldownMs:Math.max(Xa,e.watch?.cooldownMs??ad),resourceBudget:{...cd,...e.watch?.resourceBudget}}}function G8(e,t){let n=_n(e,yr),r=yb(),i={collaborationDomainId:r,languages:t,watch:{enabled:!0,debounceMs:bb,cooldownMs:ad,gitPollMs:2e3,idleTimeoutMs:Sb,autoRefresh:!0,resourceBudget:{...cd}}},o=Ko(n,s=>{if(!s.revision.exists)return{kind:"write",text:Wo(i)};let a=Za(s,i);return a.config.collaborationDomainId?{kind:"unchanged"}:{kind:"write",text:Wo({...a.config,collaborationDomainId:r})}});return{configPath:n,changed:o.changed}}function z8(e,t,n=yb()){let r=_n(e,yr),i=t,o=Ko(r,s=>{let a=Za(s,t);if(a.config.collaborationDomainId)return i=a.config,{kind:"unchanged"};let c={...a.config,collaborationDomainId:n};return i=c,{kind:"write",text:Wo(c)}});return{configPath:r,config:i,changed:o.changed}}function K8(e,t,n){let r=_n(e,yr),i=[...n],o=t,s=Ko(r,a=>{let c=Za(a,t);if(Cb(t.languages,c.config.languages,i))throw new zo(r,"languages");let l={...c.config,languages:i};return o=l,a.revision.exists&&!c.needsMigration&&Qa(l,c.config)?{kind:"unchanged"}:{kind:"write",text:Wo(l)}});return{configPath:r,config:o,changed:s.changed}}function W8(e,t,n){let r=_n(e,yr),i=t,o=Ko(r,s=>{let a=Za(s,t);if(Cb(t.watch?.enabled,a.config.watch?.enabled,n))throw new zo(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&&Qa(c,a.config)?{kind:"unchanged"}:{kind:"write",text:Wo(c)}});return{configPath:r,config:i,changed:o.changed}}function Za(e,t){if(!e.revision.exists)return{config:za(t),needsMigration:!0};let n=xb(td(e.text),e.path,"update");return{config:n.config,needsMigration:n.needsMigration}}function Wo(e){return eb(e)}function Qa(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Cb(e,t,n){return!Qa(e,t)&&!Qa(t,n)}function xb(e,t,n){if(e.kind==="legacy"||e.kind==="supported")return e;if(e.kind==="malformed"){let i=n==="read"?`invalid ${yr} 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 ${yr} 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${pr} and current v${fr}). Upgrade scip-query before retrying; the file was left untouched.`)}function rk(e,t){if(!se(e))return;let n=e;if(Oe(t,n,"",IT),Oe(t,n.watch,"watch",wT),Oe(t,n.watch?.resourceBudget,"watch.resourceBudget",LT),Oe(t,n.entryRoots,"entryRoots",PT),Oe(t,n.semantic,"semantic",DT),Oe(t,n.semantic?.typescript,"semantic.typescript",MT),Oe(t,n.semantic?.rust,"semantic.rust",TT),Oe(t,n.locality,"locality",AT),Oe(t,n.architecture,"architecture",FT),Oe(t,n.docs,"docs",_T),Array.isArray(n.architecture?.boundaries))for(let[r,i]of n.architecture.boundaries.entries())Oe(t,i,`architecture.boundaries[${r}]`,NT);if(se(n.indexer)){Oe(t,n.indexer,"indexer",fb);for(let[r,i]of Object.entries(n.indexer))fb.has(r)&&Oe(t,i,`indexer.${r}`,kT)}if(Array.isArray(n.declaredCouplings))for(let[r,i]of n.declaredCouplings.entries())Oe(t,i,`declaredCouplings[${r}]`,OT);if(Array.isArray(n.suppressions)){for(let[r,i]of n.suppressions.entries())if(Oe(t,i,`suppressions[${r}]`,BT),se(i.decision)){if(Oe(t,i.decision,`suppressions[${r}].decision`,$T),Array.isArray(i.decision.evidence))for(let[o,s]of i.decision.evidence.entries())Oe(t,s,`suppressions[${r}].decision.evidence[${o}]`,jT);Oe(t,i.decision.invalidateOn,`suppressions[${r}].decision.invalidateOn`,HT)}}if(Array.isArray(n.coverageContracts))for(let[r,i]of n.coverageContracts.entries()){let o=`coverageContracts[${r}]`;Oe(t,i,o,UT),se(i)&&(Oe(t,i.keys,`${o}.keys`,qT),Oe(t,i.mustEqual,`${o}.mustEqual`,GT))}}function Oe(e,t,n,r){if(se(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 ec,lstatSync as ik}from"fs";import{resolve as ok}from"path";function c9(e){return e.state==="fresh"?!0:e.state!=="stale"?!1:!e.reason.startsWith("SQLite generation requires repair")}function Rb(e,t,n,r={}){let i=new Date().toISOString();if(!ec(n.dbPath))return{state:"missing",checkedAt:i,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!ec(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=kr(lt(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??yg(e),c=s.fingerprint,l=n.cacheDir&&r.gitContext&&Jl(r.gitContext,n.cacheDir,c)?c:void 0,u=n.cacheDir&&r.gitContext&&l&&ak(l,a,t)&&ck(e,l,t)?r.gitObservation?.context===r.gitContext?r.gitContext:Cf(r.gitContext):void 0,d=r.gitObservation&&r.gitObservation.context===r.gitContext?r.gitObservation.projectFileInventorySequence:void 0,m=u?.clean&&xf(e,void 0,{cachedInventoryAfterSequence:d})?u:void 0,p=n.cacheDir&&m&&l&&Jl(m,n.cacheDir,l)?l:sk(e,a,t),f=[...s.indexedLanguages??[]].sort(),g=o.capabilities.publishableGeneration&&JSON.stringify(s.fingerprint)===JSON.stringify(p)&&JSON.stringify(f)===JSON.stringify(p.languages),h=Yl(n.dbPath,n.metaPath),b=h.state==="invalid"||h.state==="drifted",S=g?bg(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 l9(e){let t=new Date().toISOString();if(!ec(e.dbPath))return{state:"missing",checkedAt:t,metaPath:e.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!ec(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=kr(lt(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=qs(r.fingerprint),s=[...o?.languages??[]].sort(),a=n.capabilities.publishableGeneration&&o!==null&&JSON.stringify(i)===JSON.stringify(s),c=Yl(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 sk(e,t,n){return Mf(e,t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath})}function ak(e,t,n){let r=lk(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 ck(e,t,n){if(!(t.languages.includes("typescript")||!!t.clojureConfigPath))return!0;let i=Ys(e);if(t.clojureConfigPath){let o=Dn(t.clojureConfigPath);if(!i.includes(o))return!1;try{if(!ik(ok(e,o)).isFile())return!1}catch{return!1}}return!t.languages.includes("typescript")||Ef(e,n.indexer?.typescript?.projectMode,n.indexer?.typescript?.projects??[],i)}function lk(e,t){return Tf(e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{existsSync as uk,readdirSync as dk}from"fs";import{createHash as mk}from"crypto";import{join as dd}from"path";function ud(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(ld(l));break;case"unsupported-future":i+=1,s.push(ld(l));break;case"malformed":o+=1,s.push(ld(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 ld(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 wb=dd(".scipquery","suppressions"),Eb="scip-query-suppression",Ib=1,tc=2;function pk(e){return dd(e,wb)}function fk(e){if(e.id&&e.id.trim()!=="")return`${e.id.trim()}.json`;let t=`${e.check??""}\0${e.file??""}`;return`CHECK-${mk("sha256").update(t).digest("hex").slice(0,12).toUpperCase()}.json`}function gk(e){return fk(e).slice(0,-5)}function hk(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!==Ib&&n.schemaVersion!==tc)return{state:n.schemaVersion>tc?"unsupported-future":"unsupported-older",error:`unsupported schemaVersion ${String(n.schemaVersion)}`};if(n.kind!==void 0&&n.kind!==Eb)return{state:"malformed",error:`kind must be ${Eb}`}}if(n.schemaVersion===Ib&&n.decision!==void 0)return{state:"malformed",error:"schemaVersion 1 cannot carry automated adjudication metadata"};if(n.schemaVersion===tc&&!Wa(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=yk(n);if(n.schemaVersion===void 0)return{state:"legacy",suppression:r,record:n,schemaVersion:0};let i=gk(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===tc?"current":"legacy",suppression:r,record:n,schemaVersion:n.schemaVersion}}function Lb(e){let t=pk(e);if(!uk(t))return{suppressions:[],compatibility:ud([]),warnings:[]};let n=[],r=[];for(let o of dk(t).sort()){if(!o.endsWith(".json"))continue;let s=dd(t,o),a=`${wb}/${o}`,c;try{c=JSON.parse(lt(s,"suppression record"))}catch{r.push({path:a,state:"malformed",reason:"malformed JSON"});continue}let l=hk(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=ud(r);return{suppressions:n,compatibility:i,warnings:i.issues.map(o=>`${o.path}: ${o.reason} \u2014 ignored`)}}function yk(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 rc(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var md,nc;function M9(e){md=e}function ic(){return nc}function Pb(e=rc(),t=void 0){if(t===void 0&&md?.projectRoot===e)return md;let n=vb(e),r=wf(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(pd(r.dbPath))return{projectRoot:e,config:n,paths:r,dbPath:r.dbPath,dbPathSource:"configured",gitContext:t};let o=Sk(e,"index.db");return{projectRoot:e,config:n,paths:r,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:Rk(o,r.dbPath),gitContext:t}}function T9(e){return Pb(e).dbPath}function k9(e,t,n,r={}){if(pd(n.dbPath)&&r.gitContext?.clean===!1&&r.watcherGeneration!==void 0&&Ay(n.dbPath)===r.watcherGeneration)return Cg(e,t,n,r.gitContext);let i=Rb(e,t,n,{gitContext:r.gitContext,gitObservation:r.gitObservation});return i.state==="fresh"?{kind:"local-fresh",freshness:i}:vg(e,t,n,r.gitContext)}function A9(e){return!e.startsWith("__")&&!vk.has(e)}function F9(e){return e==="search"||e==="code"}var vk=new Set(["capabilities","check-deps","config-validate","continue","doctor","init","install-skills","reindex","setup","setup-agent","status","suppress","uninstall","watch"]);function Ck(){try{return xk(rc(),{warnOnRootFallback:!0})}catch(e){console.error(`error: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}function xk(e,t={}){let{config:n,paths:r,dbPath:i,dbPathSource:o,rootFallbackWarning:s,gitContext:a}=Pb(e);if(!pd(i))throw new Error("No index.db found. Run: scip-query reindex");t.warnOnRootFallback&&o==="root-fallback"&&s&&console.error(s);let c=Lb(e).suppressions,l={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??r.indexPath,projectRoot:e,collaborationDomainId:n.collaborationDomainId,sharedEvidenceDbPath:Sg(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=hg(e);return new gg(l,u)}function Rk(e,t){let n="unknown time";try{n=bk(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 fd(e){return vf(()=>{let t=Ck(),n=nc;nc=t;try{return e(t)}finally{nc=n,t.close()}})}function N9(e,t){return t.concat([e])}function gd(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 _9(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, ${gd(e.estimatedWriteBytes)} estimated writes)${e.dirty?" \u2014 changes pending":""}`;case"draining":return`Stopping safely \u2014 ${e.reason}`;default:return Ek(e)}}function Ek(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}var Ik=new Map([[8,"\u2408"],[9,"\u2409"],[10,"\u2424"],[13,"\u240D"]]),B9=6500,$9=8e3,j9=6500,H9=3500;function Db(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=wk(e,o);continue}if(s===155){o=Mb(e,o+1);continue}if(s===144||s===152||s===157||s===158||s===159){o=Tb(e,o+1);continue}if(Dk(s)){s===10&&n?i+=`
|
|
54
|
+
`:s===9&&r?i+=" ":i+=Ik.get(s)??"\uFFFD",o+=1;continue}if(Mk(s)){i+="\uFFFD",o+=1;continue}i+=e[o],o+=1}return i}function Jt(e){return Db(e,{allowNewlines:!1,allowTabs:!1})}function yd(e,t=n=>process.stdout.write(n)){t(`${e}
|
|
55
|
+
`)}function U9(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(hd)),e.error=(...n)=>t.error(...n.map(hd)),e.warn=(...n)=>t.warn(...n.map(hd)),()=>{e.log=t.log,e.error=t.error,e.warn=t.warn}}function hd(e){return typeof e=="string"?Db(e):e}function wk(e,t){let n=e.charCodeAt(t+1);if(Number.isNaN(n))return e.length;if(n===91)return Mb(e,t+2);if(n===80||n===88||n===93||n===94||n===95)return Tb(e,t+2);let r=t+1;for(;r<e.length&&Lk(e.charCodeAt(r));)r+=1;return r<e.length&&Pk(e.charCodeAt(r))?r+1:t+1}function Mb(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 Tb(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 Lk(e){return e>=32&&e<=47}function Pk(e){return e>=48&&e<=126}function Dk(e){return e<=31||e>=127&&e<=159}function Mk(e){return e===1564||e===8206||e===8207||e>=8234&&e<=8238||e>=8294&&e<=8297}function oc(e){return e+1}function Tk(e,t){return`${oc(e)}-${oc(t)}`}function bd(e,t,n){return`${Jt(e)}:${Tk(t,n)}`}function z9(e,t=180){let n=Jt(e).replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var Sd={empty(e){console.log(Jt(e))},list(e,t){for(let n of e)console.log(Jt(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(Jt(o)),r=o),console.log(Jt(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 ${Jt(n.title)} \u2550\u2550\u2550`),n.explanation!==void 0&&console.log(Jt(n.explanation));for(let r of n.rows){let i=n.preserveRowNewlines?r.split(`
|
|
56
|
+
`):[r];for(let o of i)console.log(Jt(o))}}},table(e,t,n){console.log(` ${e.map(Jt).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(Jt(i))}};import{availableParallelism as T5}from"os";import{fileURLToPath as qp}from"url";import{existsSync as sc,readdirSync as Fb}from"fs";import{join as Vo}from"path";var kk={files:new Set,pathPrefixes:[]},Ak={reasonsByFile:new Map},vd=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,Fk=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,Nb=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Nk=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),_k=4,Ok=Le("package-surface",{clearGroups:["whole-project"]}),Bk=Le("package-operational-surface",{clearGroups:["whole-project"]});function _b(e){return Ok.get(e,()=>jk(e.config.projectRoot))}function Bn(e,t){let n=_b(e);return n.files.has(t)?!0:n.pathPrefixes.some(r=>t.startsWith(r))}function Ob(e,t){return _b(e).files.has(t)}function $k(e){return Bk.get(e,()=>Hk(e.config.projectRoot))}function Bb(e,t){return $k(e).reasonsByFile.get(t)??[]}function jk(e){let t=new Set,n=[];for(let{manifest:r,packageRoot:i}of $b(e))for(let o of Uk(r))qb(e,i,o,t,n);return t.size===0&&n.length===0?kk:{files:t,pathPrefixes:n}}function Hk(e){let t=new Map;for(let{manifest:n,packageRoot:r}of $b(e)){let i=qk(n);for(let s of i)kb(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 Gk(a))kb(e,r,c,`package script "${s}"`,t)}}return t.size===0?Ak:{reasonsByFile:t}}function $b(e){let t=[],n=Hb(e,"");return n&&t.push({manifest:n,packageRoot:""}),jb(e,"",t,0),t}function jb(e,t,n,r){if(r>=_k)return;let i=Vo(e,t);if(sc(i))for(let o of Fb(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}),jb(e,s,n,r+1)}}function Hb(e,t){let n;try{n=ut(e,Vo(t,"package.json"),{maxBytes:8*1024*1024,inputKind:"package manifest"})}catch(r){if(!dt(r))throw r;return null}try{let r=JSON.parse(n);return r&&typeof r=="object"?r:null}catch{return null}}function Uk(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 Ub(e.exports,t),t}function qk(e){let t=e.bin;return typeof t=="string"?[t]:!t||typeof t!="object"?[]:Object.values(t).filter(n=>typeof n=="string")}function Gk(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 kb(e,t,n,r,i){let o=new Set;qb(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 Ub(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))Ub(n,t)}function qb(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 Ab(c))l!==""&&i.push(On(t,l));return}let a=o.replace(Fk,"");for(let c of Ab(a)){c===a&&c===o&&r.add(On(t,o));for(let l of Nb)zk(e,r,t,c+l)}r.add(On(t,o))}function Ab(e){let t=[e];return vd.test(e)&&(t.push(e.replace(vd,"src/")),t.push(e.replace(vd,""))),t}function zk(e,t,n,r){let i=On(n,r);if(t.add(i),!r.startsWith("src/")||sc(Vo(e,i)))return;let o=Nb.find(u=>r.endsWith(u));if(!o)return;let s=r.slice(0,-o.length);Kk(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 Gb(e,n,c,`${l}${o}`))t.add(u)}function Kk(e,t,n,r,i){let o=On(n,`${r}/index${i}`);sc(Vo(e,o))&&t.add(o)}function Gb(e,t,n,r){let i=Vo(e,t,n);if(!sc(i))return[];let o=[];for(let s of Fb(i,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...Gb(e,t,a,r)):s.isFile()&&s.name===r&&o.push(On(t,a))}return o}function On(e,t){return e?`${e}/${t}`:t}import{existsSync as Cd,readdirSync as Wk}from"fs";import{dirname as Vk,join as xd}from"path";var Yk={rootFiles:new Set,sourcePrefixes:[]},Jk=new Set([".git",".scipquery","node_modules","target"]),Xk=6,Qk=Le("rust-library-surface",{clearGroups:["whole-project"]});function zb(e,t,n){if(!n.endsWith(".rs")||!tA(Zk(e),n))return!1;let r=z(e,n).find(i=>i.symbol===t);return r?nA(Q(e,n)[r.startLine]??""):!1}function Zk(e){return Qk.get(e,()=>eA(e.config.projectRoot))}function eA(e){let t=new Set,n=new Set;for(let r of rA(e)){let i=ut(e,xd(r,"Cargo.toml"),{maxBytes:8388608,inputKind:"Cargo manifest"}),o=iA(i),s=On(r,"src/lib.rs"),a=o?On(r,o):!oA(i)&&qt(e,s)?s:null;if(!a)continue;t.add(a);let c=Vk(a).replaceAll("\\","/");n.add(c==="."?"":`${c}/`)}return t.size===0?Yk:{rootFiles:t,sourcePrefixes:[...n].sort()}}function tA(e,t){return t.endsWith(".rs")?e.rootFiles.has(t)?!0:sA(t)?!1:e.sourcePrefixes.some(n=>t.startsWith(n)):!1}function nA(e){return/^\s*pub\s+(?!\()/.test(e)}function rA(e){if(!Cd(e))return[];let t=[];return Kb(e,"",t,0),t}function Kb(e,t,n,r){let i=xd(e,t);if(Cd(i)&&(Cd(xd(i,"Cargo.toml"))&&n.push(t),!(r>=Xk)))for(let o of Wk(i,{withFileTypes:!0})){if(!o.isDirectory()||Jk.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name;Kb(e,s,n,r+1)}}function iA(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 oA(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 sA(e){return/(?:^|\/)src\/main\.rs$/.test(e)||/(?:^|\/)src\/bin\//.test(e)||/(?:^|\/)(?:examples|tests|benches)\//.test(e)}function Hi(e){return K(e)==="barrel"}function Vb(e){return aA.get(e,()=>{let n=ae(e,{includeIgnored:!1}).filter(s=>{let a=K(s);return a==="entry"||a==="worker"});if(n.length===0)return new Set;let r=qe(e),i=new Set,o=new Set;for(;n.length>0;){let s=n.shift();if(!i.has(s)){i.add(s),K(s)==="barrel"&&o.add(s);for(let a of r.get(s)??[])i.has(a)||n.push(a)}}return o})}var aA=Le("live-barrels",{clearGroups:["whole-project"]});function Rd(e,t){return Vb(e).has(Ct(t))}function Yb(e){let t=Vb(e);return ae(e,{includeIgnored:!1}).filter(n=>Hi(n)&&!t.has(n)&&!cA(e,n))}function cA(e,t){let n=Ct(t),r=tr(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 tt(e,t){let n=Ct(t),r=K(t);return r==="entry"||r==="worker"||Ed(n)||Rd(e,n)}function Ui(e,t,n){let r=Ct(n),i=[];Bn(e,r)&&i.push("package-surface-file"),dA(e,t,r)&&i.push("transitive-package-surface"),zb(e,t,r)&&i.push("rust-public-library"),EA(t,r)&&i.push("framework-entrypoint");let o=e.config.entryRoots;return o&&(o.files?.some(s=>Ct(s)===r)&&i.push("configured-file"),o.pathPrefixes?.some(s=>r.startsWith(Ct(s)))&&i.push("configured-path-prefix"),o.qualifiedVars?.some(s=>wA(t,s))&&i.push("configured-qualified-var"),o.symbolPatterns?.some(s=>{try{return Yr(s,"entryRoots.symbolPatterns entry").test(t)}catch{return!1}})&&i.push("configured-symbol-pattern")),i}function Ge(e,t,n){return Ui(e,t,n).length>0}var lA=Le("package-surface-reachability",{clearGroups:["whole-project"]}),uA=Le("explicit-package-surface-reachability",{clearGroups:["whole-project"]});function dA(e,t,n){let r=mA(e).get(n);return r===void 0?!1:r===null||r.has(W(t))}function Jb(e,t,n){let r=pA(e).get(n);return r===void 0?!1:r===null||r.has(W(t))}function mA(e){return lA.get(e,()=>Xb(e,t=>Bn(e,t)))}function pA(e){return uA.get(e,()=>Xb(e,t=>Ob(e,t)))}function Xb(e,t){let n=new Map,r=[];for(let i of ae(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 go(e,i)){if(!s.sourcePath||e.isIgnored(s.sourcePath))continue;let a=fA(o,s);a!==void 0&&gA(n,s.sourcePath,a)&&r.push(s.sourcePath)}}return n}function fA(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 gA(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 Qb=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),hA=new Set(["default","generateMetadata","generateStaticParams"]),yA=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),bA=new Set(["default","middleware","config"]),SA=new Set(["register","onRequestError"]),vA=new Set(["onRouterTransitionStart"]),CA=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),xA=new Set(["load","actions","entries",...Qb]),RA=new Set(["default"]);function EA(e,t){let n=W(e);return n===""?!1:Zb(t)?Qb.has(n):eS(t)?hA.has(n):tS(t)?yA.has(n):nS(t)?bA.has(n):rS(t)?SA.has(n):iS(t)?vA.has(n):oS(t)?CA.has(n):sS(t)?xA.has(n):IA(t)?RA.has(n):!1}function Ed(e){return Zb(e)||eS(e)||tS(e)||nS(e)||rS(e)||iS(e)||oS(e)||sS(e)}function Zb(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function eS(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function tS(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function nS(e){return Id(e,"(?:middleware|proxy)\\.(?:ts|js|mts|mjs)")}function rS(e){return Id(e,"instrumentation\\.(?:ts|js|mts|mjs)")}function iS(e){return Id(e,"instrumentation-client\\.(?:ts|js|mts|mjs)")}function Id(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 oS(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function sS(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function IA(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function wA(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(Wb(r)+"/")&&e.includes(Wb(i)+".")}function Wb(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function aS(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=ae(e,{includeIgnored:!1}),o=dn(e),s=t??He(e),a=new Set(s.map(l=>l.symbolId)),c=AA(s);return LA(e,r,i,o,a,c),PA(e,r,s,a),kA(e,r,i,o,a,c),n.semantic!==!1&&n.semanticEvidence&&NA(r,n.semanticEvidence.callerMap(e,FA(s))),r}function LA(e,t,n,r,i,o){for(let s of n){if(!de(s))continue;let a=un(e,s);if(a)for(let c of a){if(o&&!o.has(c.calleeLeaf))continue;let l=nn(s,r.get(c.calleeLeaf)??[]);if(!l||l.length===0)continue;let u=rr(e,s,l,c.memberAccess,c.calleeQualifier);u&&i.has(u.symbolId)&&u.file!==s&&wd(t,u.symbolId,s)}}}function PA(e,t,n,r){let i=MA(n);for(let o of DA(e,r))e.isIgnored(o.relative_path)||TA(o,i.get(o.symbol_id))||wd(t,o.symbol_id,o.relative_path)}function DA(e,t){return oa(e,t?[...t]:void 0)}function MA(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 TA(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function kA(e,t,n,r,i,o){for(let s of n){if(de(s)!=="rust")continue;let a=Si(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&&wd(t,u.symbolId,s)}}}function wd(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function AA(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"?W(n.symbol):"";r&&t.add(r)}return t.size>0?t:null}function FA(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 Ld(e,t,n={}){return aS(e,t,n)}function Yo(e,t,n={}){return Zf(e,t,n)}function cS(e,t,n={}){let r=Ld(e,t,{semantic:n.semantic,semanticEvidence:n.semanticEvidence});return n.sourceFallback===!1?r:$n(r,Yo(e,t))}function $n(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 lS(e,t,n){let r=t.identifierResolution==="strict"?Gl:Qf,i=t.candidateNames?Yf(t.candidateNames):null,o=0,s=0,a=0,c=0,l="";for(let u of t.paths)if(o+=1,l=u,!(!de(u)&&!(t.includeVueSfc&&Ff(u)))&&!e.isIgnored(u)&&!t.skipPath?.(u))try{if(i&&!Jf(X(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=Ei(e,u);for(let[f,g]of p)m(f,"identifier",g.length,()=>r(e,u,f));for(let f of Si(e,u,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let g=f.kind==="cross-language-dispatch"?()=>Gl(e,u,f.name):()=>r(e,u,f.name);m(f.name,f.kind,f.occurrences,g)}}finally{t.afterPath?.(u),o%10===0&&_("source-reference-scan.progress",()=>{},()=>({scannedPaths:o,currentPath:l,candidateMatchedPaths:s,visitedNames:a,visitedHits:c}))}}function ce(e){return e.endLine-e.startLine+1}function uS(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=_A(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 E=tt(e,v);return b.set(v,E),E},x=v=>{let C=S.get(v);if(C!==void 0)return C;let E=K(v);return S.set(v,E),E};for(let v of h){let C=v.relativePath;if(e.isIgnored(C)||a&&y(C)||!OA(v,{requireFunctionLikeSymbol:u,requireCallableSymbol:d})||s!==void 0&&v.symbol===s)continue;let E=ce(v);E<i||E>o||c&&BA(C)||l&&Ge(e,v.symbol,C)||m&&Ze(v.symbol)||x(C)!=="test"&&(Ci(v.symbol)||!p&&Xs(e,C,v.startLine)||g.push(v))}return f?g.sort((v,C)=>ce(C)-ce(v)):g}function _A(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=>z(e,r)):t.requireCallableSymbol?ho(e,{scope:t.scope,symbolMatches:mt,sqlPrefilter:"callable"}):t.requireFunctionLikeSymbol?ho(e,{scope:t.scope,symbolMatches:Ae,sqlPrefilter:"function-like"}):qf(e,t.scope)}function OA(e,t){return t.requireCallableSymbol?mt(e.symbol):t.requireFunctionLikeSymbol?Ae(e.symbol):e.isFunctionLike}function BA(e){return(e.split("/").pop()??"").includes("types")}var q=class{constructor(t){this.db=t}db;scopedDefinitions(t){return Uf(this.db,t)}definitionsForFile(t){return z(this.db,t)}productionCallableDefinitions(t={}){return uS(this.db,t)}calleeMap(t,n={}){return Hr(this.db,t,{...n,semanticEvidence:ue})}crossFileCallerMap(t,n={}){return Ld(this.db,t,{...n,semanticEvidence:ue})}sourceFallbackCallerFiles(t,n={}){return Yo(this.db,t,n)}callerFileMap(t,n={}){return cS(this.db,t,{...n,semanticEvidence:ue})}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 ae(this.db,{includeIgnored:!1}))if(de(i)==="rust")for(let{name:o}of Si(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 qe(this.db,t)}fileKind(t){return K(t)}hasSuppressionComment(t){return Xs(this.db,t.relativePath,t.startLine)}sourceFiles(){return bi(this.db)}scanSourceReferences(t,n){lS(this.db,t,n)}callableSignature(t){let n=tr(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 $A}from"fs";function Jr(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,...jA(e.generation.databasePath)}}function jA(e){try{let t=$A(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function HA(e,t){return Zl(e).filter(n=>UA({pattern:t,relativePath:n})).map(n=>({relativePath:n}))}function UA(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=Dn(n.pattern),i=Dn(n.relativePath);if(!/[*?]/.test(r))return i.includes(r);let o=r.includes("/")?r:`**/${r}`;return ac(o.split("/"),i.split("/"))}function ac(e,t){if(e.length===0)return t.length===0;let[n,...r]=e;return n==="**"?ac(r,t)||t.length>0&&ac(e,t.slice(1)):t.length===0||!qA(n??"",t[0]??"")?!1:ac(r,t.slice(1))}function qA(e,t){let n="^";for(let r of e)r==="*"?n+="[^/]*":r==="?"?n+="[^/]":n+=GA(r);return n+="$",new RegExp(n).test(t)}function GA(e){return/[\\^$.*+?()[\]{}|]/.test(e)?`\\${e}`:e}function mS(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 cc(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)=>dS(p,a)-dS(m,a)||r(m,p));let d=u[0]??l[0];s.push(d),c+=d.evidenceCharacters;for(let m of pS(d))a.add(m.key);o.splice(o.indexOf(d),1)}return{selected:s,omitted:o.sort(r)}}function dS(e,t){let n=pS(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 pS(e){return[...e.reasons.map(zA),...e.roles.map(t=>({key:`role:${t}`,weight:KA(t)})),{key:`file:${e.relativePath}`,weight:180},{key:`scope:${WA(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 zA(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 KA(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 WA(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}var fS=64,gS=12;function lc(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?Yr(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=ga(e,{scope:n.scope,literalBytes:s.length===1?s[0]:s},(c,l)=>{let u=Qn(c.text);if(u.length!==0)for(let d of l){let m=o[d];m&&hS(e,m,c,u,n)}});return o.map(c=>yS(c,a,r,i,n))}return o.map(s=>{let a=ga(e,{scope:n.scope},c=>{let l=Qn(c.text);l.length>0&&hS(e,s,c,l,n)});return yS(s,a,r,i,n)})}function hS(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"?z(e,s):[],c=Y(e,s)?.callables??[];for(let l of o){let u=We(a,l),d=Zn(c,l),m=u&&!Ce(u.symbol)?u:null,p=m?.startLine??d?.startLine??u?.startLine??l,f=m?.endLine??d?.endLine??u?.endLine??l,g=Do(e,s,l,p,f);t.identities.push({relativePath:s,focusLine:l,ownerSymbol:m?.symbol??null,ownerShort:m?M(m.symbol):d?.name??(u?M(u.symbol):null),ownerStartLine:g.startLine,ownerEndLine:g.endLine,fileKind:K(s),freshness:n.freshness})}t.fileCoverage.push({relativePath:s,matchingLines:o.length,returnedMatches:0,freshness:n.freshness})}function yS(e,t,n,r,i){e.identities.sort(SS);let o=e.identities.length>fS?bS(e.identities,fS):e.identities,a=(r===Number.MAX_SAFE_INTEGER?e.identities:i.ranking?bS(e.identities,r):e.identities.slice(0,r)).flatMap(u=>{let d=e.textByPath.get(u.relativePath),m=d===void 0?null:VA(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=YA(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,gS),omittedScopeHints:Math.max(0,l.length-gS),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 VA(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 YA(e){let t=new Map;for(let n of e){let r=JA(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 JA(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function bS(e,t){let n=e.map((i,o)=>({...i,priority:_e(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=>_e(a.fileKind)===i);r.push(...cc(s,o,Number.MAX_SAFE_INTEGER,SS).selected)}return r.map(({priority:i,sequence:o,evidenceCharacters:s,roles:a,reasons:c,symbols:l,behaviorSignals:u,...d})=>d)}function SS(e,t){return _e(e.fileKind)-_e(t.fileKind)||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||e.relativePath.localeCompare(t.relativePath)||e.focusLine-t.focusLine}function XA(e,t,n={}){if(t.length===0)throw new Error("The source search pattern must not be empty.");return lc(e,[t],n)[0]}function uc(e,t){return ce(e)-ce(t)||e.relativePath.localeCompare(t.relativePath)}function Pe(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function qi(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 ze(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))]}function nt(e){return e.replace(/^#/u,"").replace(/\(\)$/u,"")}var vS=new WeakMap,CS=new WeakMap,xS=new WeakMap,RS=new WeakMap,ES=new WeakMap;function IS(e,t){let n=CS.get(e);n||(n=new Map,CS.set(e,n));let r=n.get(t);if(r)return r;let i=te(e,t)?.rootNode;if(!i)return n.set(t,[]),[];let o=new Set;bn(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=pe(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"){z(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=Md([...a]).sort();return n.set(t,c),c}function br(e,t,n={}){let i=un(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=pe(e,t).filter(p=>!!p.sourcePath),s=fF(X(e,t)??""),a=te(e,t)?.rootNode??null,c=a?ZA(a):wS(),l=new Map,u=dn(e),d=[],m=0;for(let p of i){if(!p.memberAccess)continue;let f=nn(t,u.get(p.calleeLeaf)??[]);if(n.excludeIndexedTargets!==!1&&rr(e,t,f,!0,p.calleeQualifier))continue;let g=p.calleeQualifier,h=mF(e,t,p,o);if(h){d.push(h);continue}let b=QA(e,t,p,o,eF(c,p.calleeQualifier,p.line));if(b.length>0){d.push(...b);continue}let S=tF(e,t,p);if(S.length>0){d.push(...S);continue}let y=g?s.get(g)??g:null,v=(y?Md(o.filter(E=>(E.localName??E.importedName)===y).map(E=>E.sourcePath)):[]).flatMap(E=>{let R=l.get(E);return R||(R=Gt(e,E)??[],l.set(E,R)),R.filter(w=>w.name===p.calleeLeaf).map(w=>({file:E,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 QA(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=Md(r.filter(u=>u.localName===s||u.importedName===s).map(u=>u.sourcePath));if(a.length!==1)return[];let c=a[0],l=oF(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 wS(){return{declarations:new Map,callbacks:[]}}function ZA(e){let t=wS();return bn(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(bn(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;bn(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 eF(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 tF(e,t,n){let r=n.calleeQualifier;if(!r||!/^[A-Za-z_$][\w$]*$/u.test(r))return[];let i=te(e,t)?.rootNode;if(!i)return[];let o=nF(e,t,i,n.line,n.calleeLeaf,r),s=o?iF(o,r):null;if(!s)return[];if(!rF(s))return[];let a=(Gt(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=z(e,t).filter(p=>p.isFunctionLike&&p.leaf===a.name);if(c.length!==1)return[];let l=c[0],u=RS.get(e);u||(u=new Map,RS.set(e,u));let d=`${l.symbol}\0${n.calleeLeaf}`,m=u.get(d);if(!m){let p=[];for(let f of yo(e,l)){let g=te(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=>Xr(y).type==="object");if(S)for(let y of Xr(S).namedChildren){if(y.type==="shorthand_property_identifier"&&y.text===n.calleeLeaf){p.push(...dc(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);mc(x?.text)!==n.calleeLeaf||!v||p.push(...dc(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 nF(e,t,n,r,i,o){let s=xS.get(e);s||(s=new Map,xS.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 rF(e){return e.descendantsOfType("return_statement").some(t=>{let n=t.childForFieldName("argument")??t.namedChild(0);return!!(n&&Xr(n).type==="object")})}function iF(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&&bn(r,o=>{o.type==="identifier"&&o.text===t&&(i=!0)}),i)return n}n=n.parent}return null}function dc(e,t,n,r,i){if(r.type==="identifier")return(Gt(e,t)??[]).filter(c=>c.name===r.text).map(c=>({...c,file:t}));let o=Pd(e,t,r.text);if(o.length>0)return o;if(!Dd(r))return[];let a=(Gt(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 oF(e,t,n){let r=ES.get(e);r||(r=new Map,ES.set(e,r));let i=`${t}\0${n}`,o=r.get(i);if(o)return o;let s=cF(e,t).flatMap(a=>sF(e,a,t,n));return r.set(i,s),s}function sF(e,t,n,r){let i=te(e,t)?.rootNode,o=Gt(e,t)??[];if(!i)return[];let s=lF(e,t,n);if(s.size===0)return[];let a=new Set,c=[],l=[],u=[];return bn(i,m=>{if(aF(m,s)){if(m.type==="pair"){let p=m.childForFieldName("key")??m.namedChild(0),f=m.childForFieldName("value")??m.namedChild(1);if(mc(p?.text)!==r||!f)return;if(f.type==="identifier")a.add(f.text);else if(Dd(f))c.push({name:r,startLine:m.startPosition.row,endLine:m.endPosition.row});else{let g=uF(e,t,f.text),h=Pd(e,t,f.text);if(g.length>0)u.push(...g);else if(h.length>0)u.push(...h);else{let b=dF(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 aF(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 cF(e,t){let n=vS.get(e);n||(n=new Map,vS.set(e,n));let r=n.get(t);if(r)return r;let i=new Set([t]),o=z(e,t).filter(a=>a.leaf==="Service"&&a.isTypeLike);for(let a of o)for(let c of yo(e,a))i.add(c.file);let s=[...i].sort();return n.set(t,s),s}function lF(e,t,n){let r=new Set;Ke(t,n)&&r.add("Service");for(let i of pe(e,t)){if(!i.sourcePath||!Ke(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 Pd(e,t,n){let r=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!r)return[];let i=te(e,t)?.rootNode;if(!i)return[];let o=LS(i,r[1]),s=o?PS(o):null;if(!s)return[];let a=s.childForFieldName("function")??s.namedChild(0),c=a?DS(e,t,a.text):[];if(c.length!==1)return[];let l=c[0],u=te(e,l.relativePath)?.rootNode;if(!u)return[];let d=ql(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=Xr(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 Gt(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(!(mc(b?.text)!==r[2]||!S))if(S.type==="identifier")for(let y of Gt(e,l.relativePath)??[])y.name===S.text&&m.push({...y,file:l.relativePath});else Dd(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 uF(e,t,n){let r=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!r)return[];let i=te(e,t)?.rootNode;if(!i)return[];let o=LS(i,r[1]),s=o?PS(o):null,a=s?.childForFieldName("function")??s?.namedChild(0),c=a?DS(e,t,a.text):[];if(c.length!==1||!s)return[];let l=c[0],u=te(e,l.relativePath)?.rootNode;if(!u)return[];let d=ql(u,l.startLine,l.endLine);if(!d)return[];let m=new Set,p=d.childForFieldName("parameters")??d.childForFieldName("parameter");if(p&&bn(p,E=>{E.type==="identifier"&&m.add(E.text)}),m.size===0)return[];let f=Pd(e,t,n);if(f.length===0)return[];let g=(Gt(e,l.relativePath)??[]).filter(E=>E.startLine>=l.startLine&&E.endLine<=l.endLine),h=(un(e,l.relativePath)??[]).filter(E=>E.line>=l.startLine&&E.line<=l.endLine),b=new Set,S=f.map(E=>({name:E.name,startLine:E.startLine,endLine:E.endLine})),y=new Set;for(;S.length>0&&y.size<32;){let E=S.shift(),R=`${E.name}\0${E.startLine}\0${E.endLine}`;if(!y.has(R)){y.add(R);for(let w of h.filter(I=>I.line>=E.startLine&&I.line<=E.endLine)){if(w.memberAccess&&w.calleeQualifier&&m.has(w.calleeQualifier)){b.add(w.calleeLeaf);continue}if(w.memberAccess)continue;let I=g.filter(A=>A.name===w.calleeLeaf);I.length===1&&S.push(I[0])}}}if(b.size===0)return[];let v=s.childForFieldName("arguments")?.namedChildren.find(E=>Xr(E).type==="object");if(!v)return[];let C=[];for(let E of Xr(v).namedChildren){if(E.type==="shorthand_property_identifier"&&b.has(E.text)){C.push(...dc(e,t,E.text,E,E));continue}if(E.type!=="pair")continue;let R=E.childForFieldName("key")??E.namedChild(0),w=E.childForFieldName("value")??E.namedChild(1),I=mc(R?.text);!I||!b.has(I)||!w||C.push(...dc(e,t,I,w,E))}return C.filter((E,R,w)=>w.findIndex(I=>I.file===E.file&&I.name===E.name&&I.startLine===E.startLine&&I.endLine===E.endLine)===R)}function LS(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 PS(e){return e.type==="call_expression"?e:e.descendantsOfType("call_expression")[0]??null}function DS(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=pe(e,t).filter(f=>f.localName===i[1]&&f.sourcePath);if(d.length!==1||!d[0].sourcePath)return[];let m=d[0].sourcePath,p=sr(e,m,i[2]).filter(f=>f.isFunctionLike);return p.length>0?p:(Gt(e,m)??[]).filter(f=>f.name===i[2]).map(f=>({...f,relativePath:m}))}if(!/^[A-Za-z_$][\w$]*$/u.test(r))return[];let o=z(e,t).filter(d=>d.leaf===r&&d.isFunctionLike);if(o.length>0)return o;let s=(Gt(e,t)??[]).filter(d=>d.name===r).map(d=>({...d,relativePath:t}));if(s.length>0)return s;let a=pe(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=sr(e,c,l).filter(d=>d.isFunctionLike);return u.length>0?u:(Gt(e,c)??[]).filter(d=>d.name===l).map(d=>({...d,relativePath:c}))}function Dd(e){return["arrow_function","function_expression","generator_function"].includes(e.type)||e.descendantsOfType(["arrow_function","function_expression","generator_function"]).length>0}function dF(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 mc(e){return e?e.replace(/^(?:['"])(.*)(?:['"])$/u,"$1"):null}function mF(e,t,n,r){let i=/^this\.([A-Za-z_$][\w$]*)$/u.exec(n.calleeQualifier??"");if(!i)return null;let o=te(e,t)?.rootNode;if(!o)return null;let s=pF(o,n.line);if(!s)return null;let a=new Set;if(bn(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=Xr(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"?sr(e,l[0].sourcePath,c):[],m=d.length===1?d[0].leaf:u,p=z(e,l[0].sourcePath).filter(g=>g.isFunctionLike&&g.leaf===n.calleeLeaf&&Bf(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 pF(e,t){let n=[];return bn(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 Xr(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 bn(e,t){t(e);for(let n of e.namedChildren)bn(n,t)}function fF(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 Md(e){let t=[];for(let n of e)t.some(r=>Ke(r,n))||t.push(n);return t}import{existsSync as hF}from"fs";import{SymbolRole as yF}from"@c4312/scip";import{deserializeSCIP as gF}from"@c4312/scip";function MS(e,t){return gF(yi(e,{inputKind:t,maxBytes:hi}))}var Td=new WeakMap;function jn(e,t,n,r){let i=Y(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=Ad(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=TS(o.map(p=>({line:p.line,leaf:p.calleeLeaf}))),l=TS(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(AS(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 kd(e,t,n,r){let i=Ad(e);return i?{available:!0,targets:(i.byFile.get(t)??[]).filter(o=>o.sourceLine>=n&&o.sourceLine<=r)}:{available:!1,targets:[]}}function kS(e,t,n,r){let i=Ad(e);return i?{available:!0,targets:(i.byFile.get(t)??[]).filter(o=>o.sourceLine>=n&&o.sourceLine<=r&&pc(e,o.definition)).map(o=>({...o,calleeLeaf:o.definition.leaf}))}:{available:!1,targets:[]}}function Ad(e){if(Td.has(e))return Td.get(e)??null;let t=bF(e);return Td.set(e,t),t}function bF(e){if(!e.generation.indexPath||!hF(e.generation.indexPath))return null;try{let t=He(e),n=new Map(t.map(o=>[o.symbol,o])),r=MS(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&yF.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 pc(e,t){if(!t.isFunctionLike)return!1;let n=Y(e,t.relativePath);return!n||n.callables.some(r=>r.name===t.leaf&&r.startLine===t.startLine&&r.endLine===t.endLine)?!0:SF(t)}function SF(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 TS(e){let t=new Map;for(let n of e){let r=AS(n.line,n.leaf);t.set(r,(t.get(r)??0)+1)}return t}function AS(e,t){return`${e}\0${t}`}var vF=16,CF=4,Fd=3e3,xF=800,RF=new Set(["assignment","const_declaration","const_item","field_declaration","lexical_declaration","local_declaration_statement","local_variable_declaration","static_item","variable_declaration"]);function $S(e,t,n={}){let r=n.maxSteps??vF;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(D=>[D.id,D])),o=MF(n.focusLocations??[]),s=new Set,a=new Map(t.edges.map(D=>[D.id,D])),c=Hn(t.paths.flatMap(D=>D.nodeIds)),l=Hn(t.anchors.filter(D=>D.status==="matched").flatMap(D=>D.nodeIds)),u=t.nodes.filter(D=>D.disposition==="emitted"&&D.attributes.upstreamCausalPath===!0).sort((D,ie)=>Number(ie.attributes.upstreamCausalDistance??0)-Number(D.attributes.upstreamCausalDistance??0)||D.id.localeCompare(ie.id)).map(D=>D.id),d=new Set(u),m=Math.max(0,r-l.length),f=EF(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(D=>D.disposition==="emitted"&&D.kind!=="structural-membership"),y=t.edges.filter(D=>D.disposition!=="excluded"&&D.disposition!=="unsupported"&&D.kind!=="structural-membership"),x=new Set([...t.paths.flatMap(D=>D.edgeIds),...S.filter(D=>d.has(D.fromNodeId)&&d.has(D.toNodeId)).map(D=>D.id)]),v=t.paths.some(D=>D.edgeIds.length>0),C=new Set(l);for(let D of f)C.add(D);for(let D of t.paths){let ie=D.nodeIds[0],ee=a.get(D.edgeIds[0]??""),Re=D.nodeIds[1];ie&&Re&&ee?.fromNodeId===ie&&ee.toNodeId===Re&&C.add(ie)}if(t.paths.every(D=>D.nodeIds.length===0))for(let D of t.anchors)for(let ie of D.nodeIds)C.add(ie);let E=NF(l,y,i,CF),R=Hn(S.filter(D=>D.kind==="call"&&l.includes(D.fromNodeId)).map(D=>D.toNodeId)),w=new Set(Hn([...E,...v?[]:R]));for(let D of w)C.add(D);let I=Hn(S.flatMap(D=>b.has(D.fromNodeId)||b.has(D.toNodeId)?[D.fromNodeId,D.toNodeId]:[])),A=t.nodes.filter(D=>D.disposition==="emitted"&&D.kind!=="structural-region"&&S.some(ie=>ie.fromNodeId===D.id||ie.toNodeId===D.id)).map(D=>D.id),k=Hn([...u,...c,...l,...f,...w,...I,...A]).filter(D=>i.has(D)),T=[];for(let D of k)v&&!b.has(D)&&!g.has(D)&&!w.has(D)||T.length>=r&&!b.has(D)||T.push(D);let L=new Set(T),F=new Map(T.map(D=>[D,OF(D)])),N=new Set([...c,...u]),re=new Set(t.anchors.flatMap(D=>D.nodeIds)),ge=T.map((D,ie)=>{let ee=i.get(D),Re=DF(ee,o);for(let vt of Re)s.add(Gi(ee.location.file,vt));return{id:F.get(D),nodeId:D,order:ie,role:re.has(D)?"anchor":N.has(D)?"connector":"junction",kind:ee.kind,label:ee.label,location:ee.location,behavior:IF(e,ee,re.has(D),[...new Set([...Re,...PF(e,ee,y,i,x,C)])],Re,C.has(ee.id)&&(Re.length===0||re.has(ee.id)),w.has(ee.id),h.has(ee.id)&&Re.length===0)}}),Me=new Map;for(let D of t.paths)for(let ie=0;ie<D.edgeIds.length;ie+=1){let ee=a.get(D.edgeIds[ie]),Re=D.nodeIds[ie],vt=D.nodeIds[ie+1];!ee||!Re||!vt||Me.set(ee.id,ee.fromNodeId===Re&&ee.toNodeId===vt?"forward":"reverse")}let U=y.filter(D=>L.has(D.fromNodeId)&&L.has(D.toNodeId)).sort((D,ie)=>_F(D,ie,t)).map((D,ie)=>({id:BF(D.id),edgeId:D.id,order:ie,kind:D.kind,fromStepId:F.get(D.fromNodeId),toStepId:F.get(D.toNodeId),directed:!0,pathTraversal:Me.get(D.id)??"adjacent",evidence:D.evidence})),je=new Map(U.map(D=>[D.edgeId,D.id])),at=t.paths.map(D=>({id:D.id,status:D.status,stepIds:D.nodeIds.flatMap(ie=>{let ee=F.get(ie);return ee?[ee]:[]}),transitionIds:D.edgeIds.flatMap(ie=>{let ee=je.get(ie);return ee?[ee]:[]})})),Ot=ge.flatMap(D=>D.location?[`${D.location.file}:${D.location.line+1}`]:[]),St=t.anchors.some(D=>D.status==="ambiguous"),ct=at.some(D=>D.status==="connected"||D.status==="candidate"),Te=at.some(D=>D.status==="partial");return{status:ge.length===0?"unavailable":St?"ambiguous":ct&&!Te?"connected":Te?"partial":"connected",steps:ge,transitions:U,paths:at,coverage:{candidateNodes:k.length,returnedNodes:T.length,omittedNodeIds:k.filter(D=>!L.has(D)),returnedTransitions:U.length,withheldStatements:ge.reduce((D,ie)=>D+(ie.behavior?.coverage.omittedStatements??0),0),requestedFocusLocations:o,matchedFocusLocations:o.filter(D=>s.has(Gi(D.file,D.line))),unmatchedFocusLocations:o.filter(D=>!s.has(Gi(D.file,D.line)))},behaviorCommand:BS(Ot,"behavior"),exactSourceCommand:BS(Ot,"source")}}function EF(e,t,n,r){if(r<=0||n.length===0)return[];let i=new Set(t),o=new Set(n.map(s=>Gi(s.file,s.line)));return Hn(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(Gi(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 IF(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=Q(e,t.location.file),u=r.length>0?r:[t.location.line],d=t.kind==="runtime-boundary-participant"?xt(e,t.location.file,0,Math.max(0,l.length-1),[t.location.line]):xt(e,t.location.file,t.location.line,c,u),m=r.filter(w=>w>=d.startLine&&w<=d.endLine),p=Ti(e,t.location.file,d.startLine,d.endLine,m),f=p??(m.length>0?Ti(e,t.location.file,d.startLine,d.endLine,m,{requireSavings:!1}):null),g=m.length>0?TF(e,t,d.startLine,d.endLine,m,f,o):null,h=l.slice(d.startLine,d.endLine+1).join(`
|
|
66
|
+
`).length,b=Fn(e,t.location.file,d.startLine,d.endLine),S=l.slice(d.startLine,d.endLine+1).some((w,I)=>w.length>xF&&(b.get(d.startLine+I)??[]).some(A=>["binding","branch","loop","call","return","throw","mutation"].includes(A))),y=w=>wF(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<=Fd,v=n&&(m.length===0||x);if(p&&(a||v))return y(FS(p));if(!a&&!v&&g&&!S&&!x&&g.renderedCharacters<(f?.outlineCharacters??h))return y(g);if(p)return y(FS(p));let C=l.slice(d.startLine,d.endLine+1),E=C.join(`
|
|
67
|
+
`),R=Fn(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:R.get(d.startLine+I)??[],text:w,copied:!0})),coverage:{sourceStatements:C.length,representedStatements:C.length,copiedStatements:C.length,omittedStatements:0},rawCharacters:E.length,renderedCharacters:E.length})}function wF(e,t,n,r,i,o){if(!t.location)return o;let s=kd(e,t.location.file,n,r);if(!s.available)return o;let a=Fn(e,t.location.file,n,r),c=Q(e,t.location.file),l=new Set(i);for(let S of i){let y=fc(c[S]??"");if(!y)continue;let x=kn(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=pc(e,y),C=i.length>0&&v&&a.get(S.sourceLine)?.includes("return"),E=v&&l.has(S.sourceLine);return v&&!C&&!E?[]:[[y.symbol,{definition:y,kind:C?"return-value-transformer":E?"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=kd(e,y.relativePath,y.startLine,y.endLine);if(!v.available)continue;let C=Fn(e,y.relativePath,y.startLine,y.endLine),E=Q(e,y.relativePath);for(let R of v.targets){let w=R.definition,I=w.relativePath===y.relativePath&&w.startLine<=y.endLine&&w.endLine>=y.startLine;if(w.isTypeLike||I)continue;let A=pc(e,w),k=fc(E[R.sourceLine]??""),T=A&&k!==null&&kn(e,y.relativePath,k).some(F=>F>R.sourceLine&&F<=y.endLine&&(C.get(F)??[]).some(N=>["branch","return","throw"].includes(N))),L=A&&((C.get(R.sourceLine)??[]).some(F=>["branch","return","throw"].includes(F))||T);A&&!L||(f.has(w.symbol)||(f.add(w.symbol),d.push({definition:w,kind:A?"focused-causal-target":"compiler-referenced-declaration"})),A&&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"?LF(e,S.relativePath,S.startLine,S.endLine):{startLine:S.startLine,endLine:S.endLine},v=Q(e,S.relativePath).slice(x.startLine,x.endLine+1).join(`
|
|
68
|
+
`),C=y==="compiler-referenced-declaration"?null:Ti(e,S.relativePath,S.startLine,S.endLine,[]),E=C?[C.signature,...C.lines.map(k=>`${k.line+1}${k.signals.length>0?`[${k.signals.join(",")}]`:""} ${k.text}`)].join(" | "):null,R=E&&E.length<v.length?E:v,w={symbol:S.symbol,label:S.leaf,file:S.relativePath,line:x.startLine,endLine:x.endLine},I=y==="compiler-referenced-declaration"?1e3:8e3,A=y==="compiler-referenced-declaration"?12:120;if(R.length>I||x.endLine-x.startLine>A){b.push({...w,reason:"source-too-large"});continue}h.push({kind:y,...w,text:R})}return{...o,...h.length===0?{}:{supportingDeclarations:h},...b.length===0?{}:{omittedSupportingDeclarations:b}}}function LF(e,t,n,r){let i=te(e,t);if(!i)return{startLine:n,endLine:r};let o=[];jS(i.rootNode,a=>{RF.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 jS(e,t){t(e);for(let n of e.namedChildren)jS(n,t)}function FS(e){return{kind:"outline",constructKind:e.constructKind,signature:e.signature,lines:e.lines,coverage:e.coverage,rawCharacters:e.rawCharacters,renderedCharacters:e.outlineCharacters}}function PF(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(Y(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 So(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=kn(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 DF(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 MF(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(Gi(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 Gi(e,t){return`${e}\0${t}`}function TF(e,t,n,r,i,o,s){if(!t.location)return null;let a=Q(e,t.location.file),c=Fn(e,t.location.file,n,r),l=[...c].filter(([,L])=>L.length>0).map(([L])=>L).sort((L,F)=>L-F),u=i.map(L=>(c.get(L)??[]).length>0?L:l.find(F=>F>L&&F-L<=8)??L),d=new Set([...i,...u]),m=s?ou(e,t.location.file,n,r,{minimumBodyLines:0}):null,p=o?[...new Map(u.flatMap(L=>o.lines.filter(F=>F.text.length<=500&&F.signals.some(N=>["branch","loop","catch","finally"].includes(N))&&L>=F.line&&L<=F.endLine).sort((F,N)=>F.endLine-F.line-(N.endLine-N.line)||F.line-N.line).slice(0,2).map(F=>[`${F.line}\0${F.endLine}`,F]))).values()]:Ea(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,F]of c)F.includes("call")&&F.includes("shape")&&d.add(L);let f=[];for(let L of u){let F=fc(a[L]??"");if(!F)continue;let N=kn(e,t.location.file,F).filter(U=>U>L&&U<=r),re=N[0];re!==void 0&&d.add(re);let ge=N.find(U=>(c.get(U)??[]).some(je=>je==="branch"||je==="loop"));if(ge===void 0)continue;d.add(ge);let Me=(o?.lines??[]).find(U=>U.line===ge)??{line:ge,endLine:Math.min(r,ge+40),depth:0,signals:c.get(ge)??[],text:(a[ge]??"").trim(),copied:!0},ne=o?.lines??a.slice(Me.line,Me.endLine+1).map((U,je)=>{let at=Me.line+je;return{line:at,endLine:at,depth:0,signals:c.get(at)??[],text:U.trim(),copied:!0}});f.push({focusLine:L,governingUse:ge,lines:ne.filter(U=>U.line>=Me.line&&U.line<=Me.endLine&&U.text.length<=500&&U.signals.some(je=>["binding","branch","call","mutation"].includes(je)))})}for(let L of f.sort((F,N)=>N.governingUse-N.focusLine-(F.governingUse-F.focusLine)||F.focusLine-N.focusLine).slice(0,2))for(let F of L.lines.slice(0,14))d.add(F.line);let g=new Set(["binding","branch","loop","call","return","throw","mutation"]);for(let L of p)for(let F of o?.lines??[])F.line<L.line||F.line>L.endLine||F.signals.some(N=>g.has(N))&&d.add(F.line);let h=a.slice(n,r+1).flatMap((L,F)=>{let N=fc(L);return N?[{name:N,line:n+F}]:[]}),b=!0;for(;b;){b=!1;for(let L of h)if([...d].some(N=>AF(a[N]??"",L.name))){d.has(L.line)||(d.add(L.line),b=!0);for(let N of kn(e,t.location.file,L.name))N<n||N>r||d.has(N)||(c.get(N)??[]).some(re=>g.has(re))&&(d.add(N),b=!0)}}for(let L of o?.lines??[])if(L.signals.some(F=>["branch","loop","catch","finally"].includes(F))&&d.has(L.line))for(let F of o?.lines??[])F.line<L.line||F.line>L.endLine||F.signals.some(N=>g.has(N))&&d.add(F.line);let S=Y(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(F=>["branch","loop","catch","finally"].includes(F))).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,F)=>L.endLine-L.line-(F.endLine-F.line)||L.line-F.line).map(L=>[L.line,L])),E=new Map((m?.lines??[]).map(L=>[L.line,L.signals.filter(F=>F!=="lifecycle")])),R=[...d].filter(L=>L>=n&&L<=r).sort((L,F)=>L-F).map(L=>{let F=v.get(L)??C.get(L);return{line:L,endLine:F?.endLine??L,depth:F?.depth??0,signals:kF([...x.get(L)??[],...o?.lines.filter(N=>L>=N.line&&L<=N.endLine).flatMap(N=>N.signals)??[],...E.get(L)??[],...i.includes(L)?["anchor"]:[],...y.has(L)?["call"]:[]]),text:F?.text??(a[L]??"").trim(),copied:F?.copied??!0}}).filter(L=>L.text.length>0);if(R.length===0)return null;let w=m?.candidateLines??ou(e,t.location.file,n,r,{minimumBodyLines:0})?.candidateLines??0,I=Math.max(o?.coverage.sourceStatements??0,w,R.length),A=o?.signature??(a[n]??t.label).trim(),k=A.length+R.reduce((L,F)=>L+F.text.length+F.signals.join(",").length+12,0),T=a.slice(n,r+1).join(`
|
|
69
|
+
`).length;return{kind:"connector-slice",constructKind:o?.constructKind??"source construct",signature:A,lines:R,coverage:{sourceStatements:I,representedStatements:R.length,copiedStatements:R.length,omittedStatements:Math.max(0,I-R.length)},rawCharacters:T,renderedCharacters:k}}function kF(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 fc(e){return/\b(?:const|let|var)\s+([\p{L}_$][\p{L}\p{N}_$]*)\s*(?:=|\bof\b|\bin\b)/u.exec(e)?.[1]??null}function AF(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`(?:^|[^\\p{L}\\p{N}_$])${n}(?:$|[^\\p{L}\\p{N}_$])`,"u").test(e)}function FF(e,t,n){return Hn(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=NS(a.edge)-NS(s.edge);if(c!==0)return c;let l=_S(s.node,i)?0:1,u=_S(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 NS(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 _S(e,t){return!e.location||!t?.location?!1:OS(e.location.file)===OS(t.location.file)}function OS(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=Hn(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=FF(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 _F(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 OF(e){return`step:${e}`}function BF(e){return`transition:${e}`}function BS(e,t){return e.length===0?null:`scip-query inspect ${e.map(n=>`--at ${$F(n)}`).join(" ")} --view ${t}`}function $F(e){return`'${e.replace(/'/gu,`'"'"'`)}'`}function Hn(e){return[...new Set(e)]}var HS=4,jF=3,HF=12,UF=48,qF=64,ei=10,Qr=6,GF=24,zF=320,Nd=6,KF=12,WF=1,VF=4,YF=7,JF=12,jd="source-construct:",XF=96,QF=32,US=4,ZF=32,e0=8,qS=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 t0(e,t,n={}){let r=rv(t),i=j0(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 q(e),c=a.scopedDefinitions(n.scope).filter(U=>!Ce(U.symbol)),l=[...c],u=new Map(l.map(U=>[U.symbol,U])),d=new Map;for(let U of c)GS(d,U,r);let m=kg(e,{scope:n.scope});for(let U of m.files){let at=z(e,U.relativePath).filter(St=>!Ce(St.symbol));if(at.length===0)continue;let Ot=Qn(U.text);for(let St=0;St<Ot.length;St+=1){let ct=Et(Ot[St]??""),Te=r.filter(ie=>ct.has(ie));if(Te.length===0)continue;let D=We(at,St);if(!(!D||Ce(D.symbol)))for(let ie of Te)Jo(d,D,ie,"source",U.relativePath,St)}}let p=zS(d),f=[...d.values()].map(U=>gc(U,p,i)).sort(rt),g=r0(m.files,f,r),h=-1;for(let U of g){let je=z(e,U.relativePath),at=je.filter(D=>!Ce(D.symbol)),Ot=Y(e,U.relativePath)?.callables??[],St=new Map,ct=D=>{let ie=`${D.startLine}\0${D.endLine}\0${D.name}`,ee=St.get(ie);if(ee)return ee;let Re=n0(U.relativePath,je,D,()=>h--);return Re?(St.set(ie,Re),l.push(Re),u.set(Re.symbol,Re),GS(d,Re,r),Re):null};for(let D of Ot){let ie=Et(D.name);r.some(ee=>ie.has(ee))&&ct(D)}if(Ot.length===0)continue;let Te=Qn(U.text);for(let D=0;D<Te.length;D+=1){let ie=Et(Te[D]??""),ee=r.filter(pi=>ie.has(pi));if(ee.length===0)continue;let Re=Zn(Ot,D),vt=Re?ct(Re):null;if(!vt)continue;let Tr=KS(at,D);if(KS(Tr?[Tr,vt]:[vt],D)?.symbol===vt.symbol)for(let pi of ee)Jo(d,vt,pi,"source",U.relativePath,D)}}let b=zS(d),S=new Map(m.files.map(U=>[U.relativePath,U.text.split(/\r?\n/u)]));for(let U of d.values()){let je=S.get(U.definition.relativePath);je&&(U.sourceCharacters=je.slice(U.definition.startLine,U.definition.endLine+1).join(`
|
|
70
|
+
`).length)}let y=[...d.values()].map(U=>gc(U,b,i)).sort(rt),x=Math.min(y.length,Math.max(HF,o*jF)),v=s?y:zi([...y.slice(0,x),...[...y].sort(Od).slice(0,Math.max(UF,x)),...A0(y,r),...F0(y,r,b)]),C=v.length,E=v.map(U=>u.get(U.symbol)).filter(U=>U?.isFunctionLike===!0),R=i0(l),w=o0(e,a,v,E,u,R,new Set(d.keys()),n.semantic!==!1),I=c0(w,v,d,b,u),A=l0(I,b,r),k=R0(e,a,w,d,b,l,u,n.semantic!==!1),L=[...d0(e,a,I,u,b,n.semantic!==!1),...A,...I,...k].map(U=>({...U,queryPathMatches:_0(U)})).sort((U,je)=>Zr(U,je,b)),F=s?L:O0(L,o,b),N=r.filter(U=>b.has(U)),re=r.filter(U=>!b.has(U)),ge=Math.max(0,y.length-C),Me=Math.max(0,L.length-F.length)+ge,ne=s?y.length:Math.min(y.length,o+HS);return{query:t,queryPathFragments:i,normalizedTerms:r,matchedTerms:N,unmatchedTerms:re,groups:F,candidateRoots:y,candidateRootCount:y.length,analyzedRootCount:C,omittedRootCount:ge,omittedGroupCount:Me,scannedFiles:m.files.length,scannedBytes:m.scannedBytes,recoveryCommand:Me===0?null:`scip-query anchors ${Sc(t)}${n.scope?` --scope ${Sc(n.scope)}`:""} --limit ${ne}`}}function rv(e){let t=vc(e).filter(n=>!qS.has(n.toLocaleLowerCase())).map(Hd).filter(n=>n.length>=3&&!qS.has(n));return[...new Set(t)]}function GS(e,t,n){let r=Et(t.leaf),i=Et(t.relativePath),o=Et(t.documentation??"");for(let a of n)r.has(a)&&Jo(e,t,a,"symbol"),i.has(a)&&Jo(e,t,a,"path"),o.has(a)&&Jo(e,t,a,"documentation");let s=e.get(t.symbol);s&&(s.symbolPhraseLength=U0(t.leaf,n))}function Jo(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 zS(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 n0(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:`${jd}${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 r0(e,t,n){let r=new Set(t.slice(0,XF).map(s=>s.file)),i=new Set(n),o=e.map(s=>{let a=Et(s.relativePath),c=s.relativePath.slice(s.relativePath.lastIndexOf("/")+1).replace(/\.[^.]+$/u,""),l=Et(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||_e(K(s.file.relativePath))-_e(K(a.file.relativePath))||s.file.relativePath.localeCompare(a.file.relativePath)).slice(0,QF);for(let s of o)r.add(s.file.relativePath);return e.filter(s=>r.has(s.relativePath))}function i0(e){let t=new Map;for(let n of e){if(!Sn(n))continue;let r=`${n.relativePath}\0${nt(n.leaf)}`,i=t.get(r)??[];i.push(n),t.set(r,i)}return t}function KS(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,r)=>n.endLine-n.startLine-(r.endLine-r.startLine)||Number(Sn(r))-Number(Sn(n))||n.startLine-r.startLine||n.symbol.localeCompare(r.symbol))[0]}function Sn(e){return e.symbol.startsWith(jd)}function Sr(e){return Sn(e)?e.leaf:M(e.symbol)}function gc(e,t,n=[]){let r=e.definition,i=[...e.matches.entries()].map(([l,u])=>({term:l,sources:[...u.sources].sort(q0),locations:[...u.locations.values()].sort(av).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:Sr(r),leaf:r.leaf,file:r.relativePath,line:r.startLine,endLine:r.endLine,kind:r.isFunctionLike?"callable":r.isTypeLike?"type":"symbol",fileKind:K(r.relativePath),matches:i,focusLocations:K0(e,t),matchedTerms:i.map(l=>l.term),symbolMatchedTerms:s,symbolPhraseLength:e.symbolPhraseLength,identityMatchedTerms:o,rarity:a,symbolRarity:c,queryPathMatches:H0(r.relativePath,n),...e.sourceCharacters===void 0?{}:{sourceCharacters:e.sourceCharacters}}}function o0(e,t,n,r,i,o,s,a){let c=r.filter(g=>!Sn(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?Sn(h)?WS(e,h,i,o,1):hc(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||!Sn(h)||Sn(y))&&d.set(y.symbol,y)}}let m=[...d.values()],p=t.calleeMap(m.filter(g=>!Sn(g)),{additive:!1,semantic:a}),f=new Map;for(let g of m)f.set(g.symbol,Sn(g)?WS(e,g,i,o,2):hc(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=Un([...h,...b]);return{root:g,relations:S,nodeSymbols:new Set([g.symbol,...S.flatMap(y=>[y.fromSymbol,y.toSymbol])])}})}function hc(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"&&!a0(e,t,c,a.callsiteLine))continue;let l=s.get(c.symbol);(!l||$0(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:M(t.symbol),fromFile:t.relativePath,toSymbol:l.symbol,toLabel:M(l.symbol),toFile:l.relativePath,depth:i,strength:$d(c.source),evidence:c.source,callsiteLine:c.callsiteLine??s0(e,t,l)}}).sort((a,c)=>Number(o.has(c.toSymbol))-Number(o.has(a.toSymbol))||vn(a,c)).slice(0,qF)}function WS(e,t,n,r,i){let o=jn(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:Sr(t),fromFile:t.relativePath,toSymbol:a.symbol,toLabel:Sr(a),toFile:a.relativePath,depth:i,strength:"exact",evidence:"scip-occurrence-callsite",callsiteLine:s.sourceLine}]});for(let s of br(e,t.relativePath,{ranges:[{startLine:t.startLine,endLine:t.endLine}],excludeIndexedTargets:!1}).targets){let a=[...r.get(`${s.targetFile}\0${nt(s.calleeLeaf)}`)??[],...z(e,s.targetFile).filter(c=>c.isFunctionLike&&nt(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:Sr(t),fromFile:t.relativePath,toSymbol:a.symbol,toLabel:Sr(a),toFile:a.relativePath,depth:i,strength:s.strength==="exact"?"exact":"derived",evidence:"ast-member-import-candidate",callsiteLine:s.line})}for(let s of Y(e,t.relativePath)?.callSites??[]){if(s.line<t.startLine||s.line>t.endLine||s.memberAccess)continue;let a=(r.get(`${t.relativePath}\0${nt(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:Sr(t),fromFile:t.relativePath,toSymbol:c.symbol,toLabel:Sr(c),toFile:c.relativePath,depth:i,strength:"derived",evidence:"ast-callsite",callsiteLine:s.line})}return Un(o).sort(vn)}function s0(e,t,n){let r=nt(n.leaf);return Y(e,t.relativePath)?.callSites.find(i=>i.line>=t.startLine&&i.line<=t.endLine&&nt(i.calleeLeaf)===r)?.line??null}function a0(e,t,n,r){if(r===void 0)return!1;let i=nt(n.leaf);return Y(e,t.relativePath)?.callSites.some(o=>{if(o.line!==r)return!1;if(nt(o.calleeLeaf)===i)return!0;let s=vi(e,t.relativePath,o.calleeLeaf);return s!==null&&nt(s.importedName)===i&&Ke(s.sourcePath,n.relativePath)})??!1}function c0(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=Un(e.filter(y=>m.has(y.root.symbol)).flatMap(y=>y.relations)).sort(vn),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,gc(x,r));else{let v=i.get(y);v&&f.set(y,ov(v))}}let g=M0(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=D0(p,g,m,f);return{id:`anchor-set:${d+1}:${Qo(u[0])}`,kind:"connected-flow",roots:[...u].sort(rt),keyAnchors:g,candidateOwnerCount:g.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:[],matchedTerms:b,relations:S,relationCount:p.length,orchestrationRootCount:h,omittedRelations:Math.max(0,p.length-ei),systemMapCommand:es(g,p,b)}})}function l0(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=VS(s);if(a.size!==0)for(let c=o+1;c<e.length;c+=1){let l=e[c],u=VS(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=u0(s,l);if(m.length<2)continue;let p=Un([...s.relations,...l.relations]).sort(vn),f=p.slice(0,ei),g=zi([...s.roots,...l.roots]).sort(rt),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:${Qo(s.roots[0])}:${Qo(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:es(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||Zr(o.group,s.group,t)).slice(0,JF).map(o=>o.group)}function VS(e){return new Set(e.roots.flatMap(t=>t.matches.filter(n=>n.sources.includes("path")).map(n=>n.term)))}function u0(e,t){return zi([YS(e),YS(t)].filter(n=>n!==void 0))}function YS(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)||JS(i)-JS(r)||i.identityMatchedTerms.length-r.identityMatchedTerms.length||i.symbolMatchedTerms.length-r.symbolMatchedTerms.length||(n.get(i.symbol)??0)-(n.get(r.symbol)??0)||rt(r,i))[0]}function JS(e){return e.matchedTerms.length+e.identityMatchedTerms.length*2+(e.queryPathMatches?.length??0)*4}function d0(e,t,n,r,i,o){let s=pa(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)=>Zr(p,f,i)).slice(0,KF),d=s.links.filter(p=>p.strength!=="candidate").sort((p,f)=>vr(f.strength)-vr(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||!m0(p,g,r))continue;let b=p0(p,g,r);if(!b)continue;let S=c.get(h.id)??h0(e,t,h,r,o,VF);if(c.set(h.id,S),S.reachedSymbols.size===0)continue;let y=n.filter(L=>L.id!==p.id&&f0(L).some(F=>S.reachedSymbols.has(F))&&_d(b,L)>=2).sort((L,F)=>_d(b,F)-_d(b,L)||Zr(L,F,i)).slice(0,WF);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(Zo)),C=C0(Xo(h),v,S.relations);if(C.length===0)continue;let E=v0(g,h,f.joinRule,f.matchedKeyParts,f.strength),R=Un([E,...S.relations,...p.relations,...y.flatMap(L=>L.relations)]),w=x0([E,...C],R,p,y),I=zi([b,...y.flatMap(L=>L.roots)]).sort(rt),A=zi([b,...y.flatMap(L=>L.keyAnchors)]).slice(0,YF),k=[...new Set([...b.matchedTerms,...y.flatMap(L=>L.matchedTerms)])].sort(),T=g0(e,t,b,r,o);I.length===0||A.length<2||l.set(x,{id:`cross-boundary-set:${Qo(b)}:${l.size+1}`,kind:"cross-boundary-flow",roots:I,keyAnchors:A,candidateOwnerCount:A.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:T,matchedTerms:k,relations:w,relationCount:R.length,omittedRelations:Math.max(0,R.length-w.length),systemMapCommand:es(A,R,k)})}let m=new Map;for(let[p,f]of l){let g=p.slice(0,p.indexOf("\0")),h=m.get(g);(!h||Zr(f,h,i)<0)&&m.set(g,f)}return[...m.values()]}function m0(e,t,n){let r=new Set(Zo(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 p0(e,t,n){let r=zi([...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 Zo(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 f0(e){return[...new Set([...e.roots,...e.keyAnchors].map(t=>t.symbol))]}function _d(e,t){let n=Et(e.leaf),r=[...t.roots,...t.keyAnchors].map(o=>Et(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 g0(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=Et(n.leaf);return[...s].filter(c=>c!==n.file&&K(c)!=="test").flatMap(c=>{let l=Y(e,c);return(l?.callSites??[]).filter(u=>nt(u.calleeLeaf)===nt(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=[...Et(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 h0(e,t,n,r,i,o){let s=y0(e,n,r),a=s.map(({definition:m,evidence:p,line:f})=>({kind:"call",fromSymbol:Xo(n),fromLabel:yc(n),fromFile:n.source.file,toSymbol:m.symbol,toLabel:M(m.symbol),toFile:m.relativePath,depth:1,strength:p==="scip-occurrence-callsite"?"exact":"derived",evidence:p,callsiteLine:f})),c=b0(e,n);a.push(...c.relations);let l=iv([...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=hc(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:Un(a),reachedSymbols:new Set([...l.map(m=>m.symbol),...a.flatMap(m=>[m.fromSymbol,m.toSymbol])])}}function y0(e,t,n){let r=t.owner.symbol?n.get(t.owner.symbol):void 0;if(r?.isFunctionLike&&!Ce(r.symbol))return[{definition:r,evidence:"scip-occurrence-callsite",line:t.source.startLine}];let i=Q(e,t.source.file),o=xt(e,t.source.file,0,Math.max(0,i.length-1),[t.source.startLine]),s=jn(e,t.source.file,o.startLine,o.endLine).targets.map(u=>({definition:u.definition,evidence:"scip-occurrence-callsite",line:u.sourceLine})),a=Y(e,t.source.file),c=dn(e),l=(a?.callSites??[]).flatMap(u=>{if(u.line<o.startLine||u.line>o.endLine)return[];let d=nn(t.source.file,c.get(u.calleeLeaf)??[]),m=rr(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 S0([...s,...l])}function b0(e,t){let n=Q(e,t.source.file),r=xt(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine]),i=br(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:Xo(t),fromLabel:yc(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=jn(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:M(u.definition.symbol),toFile:u.definition.relativePath,depth:2,strength:"exact",evidence:"scip-occurrence-callsite",callsiteLine:u.sourceLine})}return{definitions:iv(o),relations:Un(s)}}function S0(e){return[...new Map(e.map(t=>[t.definition.symbol,t])).values()]}function iv(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function Xo(e){return e.owner.symbol??e.id}function yc(e){return e.owner.name??`${e.source.file}:${e.source.startLine+1}`}function v0(e,t,n,r,i){return{kind:"runtime-boundary",fromSymbol:Xo(e),fromLabel:yc(e),fromFile:e.source.file,toSymbol:Xo(t),toLabel:yc(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 C0(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(vn))o.has(a.toSymbol)||(o.add(a.toSymbol),i.push({symbol:a.toSymbol,path:[...s.path,a]}))}return[]}function x0(e,t,n,r){let i=Un(e),o=new Set([n,...r].flatMap(s=>[...Zo(s),...s.keyAnchors.map(a=>a.symbol)]));for(let s of t){if(i.length>=ei)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,ei)}function R0(e,t,n,r,i,o,s,a){let c=n.filter(u=>!u.root.symbol.startsWith(jd)).map(u=>({root:u.root,relations:u.relations.filter(d=>d.depth===1&&d.fromSymbol===u.root.symbol)}));return E0(c).flatMap((u,d)=>{let m=new Set(u.map(N=>N.root.symbol)),p=new Map;for(let N of u)for(let re of new Set(N.relations.map(ge=>ge.toSymbol)))p.set(re,(p.get(re)??0)+1);let f=[...p].filter(([,N])=>N>=2).sort(([N,re],[ge,Me])=>Me-re||I0(N,ge,r,i,s)).map(([N])=>s.get(N)).filter(N=>N?.isFunctionLike===!0).slice(0,GF);if(f.length===0)return[];let g=t.callerFileMap(f,{semantic:a,sourceFallback:!0}),h=new Set;for(let N of f){h.add(N.relativePath);for(let re of g.get(N.symbolId)??[])h.add(re)}let b=o.filter(N=>N.isFunctionLike&&h.has(N.relativePath)).sort(w0).slice(0,zF),S=t.calleeMap(b,{additive:!1,semantic:a}),y=new Set(f.map(N=>N.symbol)),x=Un(b.flatMap(N=>hc(e,N,S.get(N.symbolId)??[],s,1,y).filter(re=>y.has(re.toSymbol)))),v=new Map;for(let N of x){let re=v.get(N.fromSymbol)??new Set;re.add(N.toSymbol),v.set(N.fromSymbol,re)}let C=new Set([...v].filter(([N,re])=>re.size>=2||m.has(N)).map(([N])=>N)),E=x.filter(N=>C.has(N.fromSymbol));if(C.size<2||E.length===0)return[];let w=[...new Set(E.map(N=>N.toSymbol))].map(N=>bc(N,r,i,s)).filter(N=>N!==null).sort(rt),I=[...C].map(N=>bc(N,r,i,s)).filter(N=>N!==null),A=L0(I,E),k=A.slice(0,Nd),T=A.slice(Nd);if(w.length===0||k.length===0)return[];let L=[...new Set([...w.flatMap(N=>N.matchedTerms),...u.flatMap(N=>N.root.matchedTerms)])].sort(),F=P0(E,k);return[{id:`effect-owner-set:${d+1}:${Qo(w[0])}`,kind:"shared-callee-owners",roots:w,keyAnchors:k,candidateOwnerCount:A.length,omittedCandidateOwners:T,ownerRecoveryCommands:W0(T,Nd),upstreamEntries:[],matchedTerms:L,relations:F,relationCount:E.length,omittedRelations:Math.max(0,E.length-F.length),systemMapCommand:es(k,E,L)}]})}function E0(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 I0(e,t,n,r,i){let o=bc(e,n,r,i),s=bc(t,n,r,i);return o?s?rt(o,s):-1:s?1:e.localeCompare(t)}function w0(e,t){return _e(K(e.relativePath))-_e(K(t.relativePath))||e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine}function bc(e,t,n,r){let i=t.get(e);if(i)return gc(i,n);let o=r.get(e);return o?ov(o):null}function L0(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)||rt(i,o))}function P0(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(vn)),i=[],o=0;for(;i.length<ei&&r.some(s=>o<s.length);){for(let s of r){let a=s[o];if(a&&i.push(a),i.length>=ei)break}o+=1}return i.sort((s,a)=>n.get(s.fromSymbol)-n.get(a.fromSymbol)||vn(s,a))}function D0(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)||vn(a,c)}).slice(0,ei).sort((a,c)=>(i.get(a.fromSymbol)??Qr)-(i.get(c.fromSymbol)??Qr)||a.depth-c.depth||(a.callsiteLine??Number.MAX_SAFE_INTEGER)-(c.callsiteLine??Number.MAX_SAFE_INTEGER)||vn(a,c))}function ov(e){return{symbol:e.symbol,label:Sr(e),leaf:e.leaf,file:e.relativePath,line:e.startLine,endLine:e.endLine,kind:e.isFunctionLike?"callable":e.isTypeLike?"type":"symbol",fileKind:K(e.relativePath),matches:[],focusLocations:[],matchedTerms:[],symbolMatchedTerms:[],symbolPhraseLength:0,identityMatchedTerms:[],rarity:0,symbolRarity:0}}function M0(e,t,n){let r=[...e].sort(rt),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,Qr);){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)||Od(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=T0(i[0].symbol,i[1].symbol,t,n);for(let d of u?.slice(1,-1)??[]){if(i.length>=Qr)break;c(n.get(d))}if(i.length<Qr){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)||Od(f.candidate,g.candidate))[0]?.candidate;c(p)}}else for(;i.length<Math.min(3,Qr);){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||rt(d,m))[0];if(!u||u.matchedTerms.every(d=>s.has(d)))break;c(u)}for(;i.length>=2&&i.length<Qr;){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)||rt(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:k0(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||rt(m.root,p.root))[0]?.root:void 0;c(d)}return i}function T0(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 k0(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 rt(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||Ki(e.kind)-Ki(t.kind)||_e(e.fileKind)-_e(t.fileKind)||e.file.localeCompare(t.file)||e.line-t.line}function Od(e,t){return t.symbolPhraseLength-e.symbolPhraseLength||t.symbolMatchedTerms.length-e.symbolMatchedTerms.length||Ki(e.kind)-Ki(t.kind)||t.symbolRarity-e.symbolRarity||rt(e,t)}function A0(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>=US))return i;for(let s of r)if(!i.some(a=>a.symbol===s.symbol)&&(i.push(s),i.length>=US))break;return i})}function F0(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(![...Et(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=[...Et(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)=>_e(o.fileCandidates[0].fileKind)-_e(s.fileCandidates[0].fileKind)||o.sharedFrequency-s.sharedFrequency||o.file.localeCompare(s.file)).flatMap(({fileCandidates:o})=>[...o].sort(rt).slice(0,e0)).slice(0,ZF)}function N0(e,t,n){return XS(e,n)-XS(t,n)||_e(e.fileKind)-_e(t.fileKind)||t.symbolPhraseLength-e.symbolPhraseLength||Ki(e.kind)-Ki(t.kind)||rt(e,t)}function XS(e,t){let n=e.matches.find(r=>r.term===t)?.sources??[];return Math.min(...n.map(Bd),Number.MAX_SAFE_INTEGER)}function zi(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function Zr(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)||tv(e.kind)-tv(t.kind)||ZS(e)-ZS(t)||ev(e)-ev(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)||QS(t,n)-QS(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||rt(e.roots[0],t.roots[0])||t.roots.length-e.roots.length||e.relationCount-t.relationCount||e.id.localeCompare(t.id)}function QS(e,t){return e.matchedTerms.reduce((n,r)=>n+1/Math.max(1,t.get(r)??1),0)}function _0(e){return[...new Set(e.roots.flatMap(t=>t.queryPathMatches??[]))].sort()}function ZS(e){let t=e.keyAnchors.length>0?e.keyAnchors:e.roots;return Math.max(...t.map(n=>_e(n.fileKind)))}function ev(e){return e.kind==="parallel-paths"?2-(e.parallelConnectedSides??0):e.kind!=="connected-flow"||e.relationCount>0?0:1}function O0(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(Zo(o)),a=i.map(l=>({group:l,overlap:B0(l,s)})).filter(({overlap:l})=>l>0).sort(({group:l,overlap:u},{group:d,overlap:m})=>m-u||Zr(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)=>Zr(l,u,n)))}return r}function B0(e,t){return Zo(e).filter(n=>t.has(n)).length}function tv(e){switch(e){case"cross-boundary-flow":return 0;case"parallel-paths":case"connected-flow":return 1;case"shared-callee-owners":return 2}}function vn(e,t){return e.depth-t.depth||vr(t.strength)-vr(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 $0(e,t){return vr($d(t.source))-vr($d(e.source))||(e.callsiteLine??Number.MAX_SAFE_INTEGER)-(t.callsiteLine??Number.MAX_SAFE_INTEGER)||e.symbol.localeCompare(t.symbol)}function Un(e){let t=new Map;for(let n of e){let r=`${n.fromSymbol}\0${n.toSymbol}`,i=t.get(r);(!i||vn(n,i)<0)&&t.set(r,n)}return[...t.values()]}function vc(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 j0(e){let t=e.match(/[\p{L}\d_.-]+(?:\/[\p{L}\d_.-]+)+/gu)??[];return[...new Set(t.map(n=>n.replace(/[.;:!?]+$/gu,"").toLocaleLowerCase()))]}function H0(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 U0(e,t){let n=vc(e).map(Hd),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 Et(e){return new Set(vc(e).flatMap(sv).filter(t=>t.length>=3))}function sv(e){let t=Hd(e);return t.length>4&&t.endsWith("e")?[t,t.slice(0,-1)]:[t]}function Hd(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")?nv(t.slice(0,-2)):t.length>5&&t.endsWith("ing")?nv(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 nv(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 q0(e,t){return Bd(e)-Bd(t)}function Bd(e){switch(e){case"symbol":return 0;case"path":return 1;case"documentation":return 2;case"source":return 3}}function Ki(e){return e==="callable"?0:e==="type"?1:2}function $d(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function vr(e){return e==="exact"?2:1}function av(e,t){return e.file.localeCompare(t.file)||e.line-t.line}function Qo(e){return`${e.file}:${e.line+1}`}function es(e,t=[],n=[]){let r=e.map(s=>`--symbol ${Sc(`${s.file}:${s.line+1}-${s.endLine+1}`)}`),i=new Set(e.map(s=>s.symbol)),o=e.flatMap(s=>(s.sourceCharacters??0)>Fd?G0(s,t,n,i).map(a=>`--focus-at ${Sc(`${a.file}:${a.line+1}`)}`):[]);return`scip-query system-map ${[...r,...o,"--relation call","--relation runtime-boundary"].join(" ")}`}function G0(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(vc(z0(l.toLabel)).flatMap(sv).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||vr(u.strength)-vr(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 z0(e){return e.slice(Math.max(e.lastIndexOf(":"),e.lastIndexOf("."))+1)}function K0(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)||av(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 W0(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(es(e.slice(r,r+t)));return n}function Sc(e){return`'${e.replaceAll("'",`'"'"'`)}'`}import{createHash as Dv}from"crypto";function ts(e,t,n={}){let r=le(e,t);if(!r)return null;let i=n.semantic!==!1,o=An(e,r,{semantic:i,semanticEvidence:ue}).filter(l=>Ae(l.symbol)).slice(0,50),s=qi(Vt(e,r,{limit:50,additive:!0,callableOnly:!0,semantic:i,semanticEvidence:ue})),a=o.map(l=>({symbol:l.symbol,shortName:M(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:M(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:M(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 ns(e,t){let n=Mt(e,t);return n?er(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 rs(e,t){let n=Mt(e,t);return n?er(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 Ud(e,t,n={}){let r=Cc(e,t,n);return{definitions:r.definitions,referencedBy:r.referencedBy}}function Cc(e,t,n={}){let r=le(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=Ri(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:Z0(o,i?.display_name??null,r.symbol),source:Q0(e,r.relativePath,r.startLine,r.endLine)}],a=n.referenceContext??2,c=tg(e,r,{semantic:n.semantic,semanticEvidence:ue}).map(u=>{let d=ah(e,u.file,u.line,a,W(r.symbol));return{relativePath:u.file,line:u.line,enclosingSymbol:u.enclosingSymbol,enclosingShort:u.enclosingSymbol?M(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(V0);return{definitions:s,referencedBy:l,referenceEvidence:c.map(u=>({relativePath:u.relativePath,line:u.line,provenance:u.provenance,sourceKind:u.sourceKind})),claimSupport:Y0(c)}}function V0(e){return{relativePath:e.relativePath,line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort,sourceStartLine:e.sourceStartLine,sourceEndLine:e.sourceEndLine,source:e.source}}function Y0(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:J0(r)}}}function J0(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 ${X0(n)}`).join(" ")} --view behavior`}function X0(e){return`'${e.replaceAll("'","'\\''")}'`}function Q0(e,t,n,r){let i=X(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 Z0(e,t,n){let r=xi(e);if(r&&!eN(r))return r;let i=(t??"").trim();return i?Ae(n)&&!i.endsWith("()")?`${i}()`:i:M(n)}function eN(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function qd(e,t,n={}){let r=uv(e,t,n);if(r.kind!=="matched")return r;let{referenceEvidence:i,claimSupport:o,...s}=r;return s}function uv(e,t,n={}){let r=pt(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:M(r.match.symbol),relativePath:r.match.relativePath,startLine:r.match.startLine},...r.candidates]};let i=r.match,o=nN(n.parts),s=o.includes("definition")||o.includes("references")?Cc(e,i.symbol,{semantic:n.semantic,referenceContext:n.referenceContext}):{definitions:[],referencedBy:[],referenceEvidence:[],claimSupport:null},a=o.includes("callers")||o.includes("callees")?ts(e,i.symbol,{semantic:n.semantic}):null,c=n.relatedSourceLines??80;return{kind:"matched",query:t,symbol:i.symbol,shortName:M(i.symbol),file:i.relativePath,parts:o,definition:o.includes("definition")?dh(e,i.symbol):null,referenceWindows:o.includes("references")?tN(e,s.referencedBy):[],callers:o.includes("callers")?lv(e,a?.callers??[],c):[],callees:o.includes("callees")?lv(e,a?.callees??[],c):[],dependencies:o.includes("dependencies")?ns(e,i.relativePath):[],consumers:o.includes("consumers")?rs(e,i.relativePath):[],referenceEvidence:s.referenceEvidence,claimSupport:s.claimSupport}}function tN(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(cv(i)),o.source=Q(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:[cv(i)]})}return r}function cv(e){return{line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort}}function nN(e){let t=e&&e.length>0?e:["definition","references"];return[...new Set(t)]}function lv(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?z(e,o.file).find(c=>c.symbol===o.symbol):void 0)??pt(e,o.symbol).match;if(!s)continue;let a=ch(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 gv=6;function dv(e,t,n){return`${e}\0${t}\0${n??t}`}function hv(e,t,n,r={}){let i=r.limit??gv;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(R=>[R.id,R])),a=new Set(n.steps.map(R=>R.nodeId)),c=new Set(n.steps.flatMap(R=>{let w=zd(s.get(R.nodeId));return w?[w]:[]})),l=new Set;for(let R of n.steps)for(let w of R.behavior?.supportingDeclarations??[])c.add(w.symbol),l.add(dv(w.file,w.line,w.endLine));let u=R=>R.symbol!==null&&c.has(R.symbol)||l.has(dv(R.file,R.line,R.endLine)),d=new Map(n.steps.flatMap(R=>{if(!R.location)return[];let w=zd(s.get(R.nodeId));if(!w)return[];let I=z(e,R.location.file).find(A=>A.symbol===w);return I?[[R.id,I]]:[]})),m=new q(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,E=0;for(let R of n.steps){if(!R.location||!R.behavior)continue;let w=rN(R,{db:e,topology:t,nodeById:s,returnedNodeIds:a,sourceAllowed:o,alternativeAlreadyReturned:u});p.push(...w.candidates),v+=w.upstreamCandidates,E+=w.runtimeCandidates,C+=w.resultCandidates;let I=iN(R,{db:e,topology:t,nodeById:s,returnedNodeIds:a,sourceAllowed:o,alternativeAlreadyReturned:u},f);p.push(...I);let A=oN(R,{db:e,topology:t,nodeById:s,returnedNodeIds:a,sourceAllowed:o,alternativeAlreadyReturned:u},{evidencedCallsiteKeys:f,consideredCandidateKeys:g,calleeMap:m,stepDefinition:d.get(R.id)});p.push(...A.candidates),h+=A.scannedBehaviorSteps,b+=A.visibleCallsites,S+=A.identityCandidateCallsites,y+=A.ambiguousCallsites,x+=A.unresolvedCallsites}return vv(e,p,n.steps,i,{scannedBehaviorSteps:h,visibleCallsites:b,graphEvidencedCallsites:f.size,identityCandidateCallsites:S,ambiguousCallsites:y,unresolvedCallsites:x,upstreamCandidates:v,resultCandidates:C,runtimeCandidates:E},r.selectionTerms)}function rN(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"?Kd(t.db,d):Yd(d);if(!m||t.alternativeAlreadyReturned(m))continue;let p=Wd(c,d.location.file)??d.location,f=Q(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=Vd(c.evidence),S=os(d);n.push({anchor:{id:Cr(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=Kd(t.db,l);if(!u||t.alternativeAlreadyReturned(u))continue;let d=os(l),m=Wd(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=bv(p.signals),g=Vd(c.evidence);n.push({anchor:{id:Cr(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 iN(e,t,n){let r=[];if(!e.location)return r;let i=jn(t.db,e.location.file,e.location.line,e.location.endLine??e.location.line),o=Q(t.db,e.location.file),s=Fn(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=ti(e.location.file,a.sourceLine,a.calleeLeaf);if(n.has(c))continue;n.add(c);let l=Gd(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:Cr(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 oN(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=(Y(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=os(g);d.set(h,(d.get(h)??0)+1)}let m=aN(t.db,n.stepDefinition?n.calleeMap.get(n.stepDefinition.symbolId)??[]:[]),p=cN(m);for(let f of m){if(!t.sourceAllowed(f.alternative.file)||t.alternativeAlreadyReturned(f.alternative))continue;let g=nt(f.alternative.label),h=pv(l,i,g,f.row.callsiteLine,p.get(g)===1);if(!h)continue;let b=is(i,h.line,g);if(!b)continue;let S=ti(e.location.file,h.line,g);if(n.evidencedCallsiteKeys.has(S))continue;n.evidencedCallsiteKeys.add(S);let y=xv(f.row.source);o.push({anchor:{id:Cr(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=os(g),b=f.evidence.find(E=>{let R=E.location;return R!==null&&R.file===e.location?.file&&R.line>=0})?.location?.line,S=pv(l,i,h,b,d.get(h)===1);if(!S)continue;let y=is(i,S.line,h);if(!y)continue;let x=ti(e.location.file,S.line,h);if(n.evidencedCallsiteKeys.has(x))continue;n.evidencedCallsiteKeys.add(x);let v=Yd(g);if(!v||t.alternativeAlreadyReturned(v))continue;let C=Vd(f.evidence);o.push({anchor:{id:Cr(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=ti(e.location.file,f.line,f.calleeLeaf);if(n.evidencedCallsiteKeys.has(g))continue;let h=is(i,f.line,f.calleeLeaf);if(!h)continue;let b=nn(e.location.file,dn(t.db).get(f.calleeLeaf)??[]).flatMap(v=>z(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=Rc(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:Cr(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 yv(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||!Kd(e,s))continue;let a=os(s),c=Wd(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||bv(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 bv(e){return e.includes("call")&&e.some(t=>["return","mutation","shape","spread","binding"].includes(t))?"result-callback":"callable-reference"}function Sv(e,t,n={}){let r=n.limit??gv;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=Q(e,p.file),h=(Y(e,p.file)?.callSites??[]).filter(C=>C.line>=p.startLine&&C.line<=p.endLine);c+=h.length;let b=Fn(e,p.file,p.startLine,p.endLine),S=jn(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 E=ti(p.file,C.sourceLine,C.calleeLeaf);y.add(E);let R=Gd(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:Cr(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:R,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=br(e,p.file,{ranges:[{startLine:p.startLine,endLine:p.endLine}]}),v=new Map;for(let C of x.targets){let E=h.find(I=>I.line===C.line)?.calleeLeaf??C.calleeLeaf,R=ti(p.file,C.line,E),w=v.get(R)??[];w.push(C),v.set(R,w)}for(let[C,E]of v){if(y.has(C))continue;y.add(C);let R=E.filter(L=>i(L.targetFile)&&!a.some(F=>F.file===L.targetFile&&F.startLine<=L.targetStartLine&&F.endLine>=L.targetEndLine));if(R.length===0)continue;let w=R[0],I=h.find(L=>L.line===w.line)?.calleeLeaf??w.calleeLeaf,A=Gd(b.get(w.line)),k=Rc(R.map(L=>({symbol:L.targetSymbol??null,label:L.calleeLeaf,file:L.targetFile,line:L.targetStartLine,endLine:L.targetEndLine}))),T=R.some(L=>(L.resolutionAlternativeCount??0)>1)?"candidate":R.every(L=>L.strength==="exact")?"exact":"derived";o.push({anchor:{id:Cr(p.id,w.line,k.map(L=>`${L.file}:${L.line}`).join("|")),status:k.length>1?"ambiguous":T,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:A,calleeLeaf:I},alternatives:k.slice(0,3),alternativeCount:k.length,evidence:R.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:T,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 E=ti(p.file,C.line,C.calleeLeaf);y.has(E)||(m+=1)}}return vv(e,o,s,r,{scannedBehaviorSteps:t.length,visibleCallsites:c,graphEvidencedCallsites:l,identityCandidateCallsites:u,ambiguousCallsites:d,unresolvedCallsites:m,upstreamCandidates:0,resultCandidates:0,runtimeCandidates:0})}function vv(e,t,n,r,i,o=[]){let s=lN(t).sort(Cv),a=s.filter(f=>sN(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=Rc(u.flatMap(f=>f.alternativeCount===1?f.alternatives:[])),p=Rc(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(fv).join(" ")} --view behavior`,remainingInspectCommands:dN(p,8).map(f=>`scip-query inspect ${f.map(fv).join(" ")} --view behavior`)}}function Cv(e,t){let n=e.anchor.alternatives[0],r=t.anchor.alternatives[0];return xc(e.anchor.status)-xc(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 sN(e,t){if(t.anchor.alternativeCount!==1)return!0;let n=t.anchor.alternatives[0],r=n.endLine??n.line;return Q(e,n.file).slice(n.line,r+1).join(`
|
|
74
|
+
`).length<=2e4}function Gd(e){return e?.includes("call")?[...e]:["call",...e??[]]}function aN(e,t){let n=new Map;for(let r of t){let i=z(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||mv(r.source)>mv(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 cN(e){let t=new Map;for(let n of e){let r=nt(n.alternative.label);t.set(r,(t.get(r)??0)+1)}return t}function xv(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function mv(e){return xv(e)==="exact"?2:1}function is(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 pv(e,t,n,r,i){if(r!==void 0)return e.find(s=>s.line===r&&s.calleeLeaf===n&&is(t,s.line,n)!==null)??null;let o=e.filter(s=>s.calleeLeaf===n&&is(t,s.line,s.calleeLeaf)!==null);return i&&o.length===1?o[0]:null}function os(e){let t=e.attributes.leaf;if(typeof t=="string"&&t.length>0)return nt(t);let n=e.label.slice(e.label.lastIndexOf(":")+1);return nt(n)}function zd(e){if(e?.kind!=="symbol"||!e.id.startsWith("symbol:"))return null;try{return decodeURIComponent(e.id.slice(7))}catch{return null}}function Yd(e){return e.location?{symbol:zd(e),label:e.label,file:e.location.file,line:e.location.line,endLine:e.location.endLine??null}:null}function Kd(e,t){let n=Yd(t);return n?.symbol&&z(e,n.file).some(i=>i.symbol===n.symbol&&i.isFunctionLike)?n:null}function Wd(e,t){return e.evidence.find(n=>n.location?.file===t)?.location??e.evidence.find(n=>n.location!==null)?.location??null}function Vd(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 lN(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||uN(n,o)<0)&&t.set(i,n)}return[...t.values()]}function uN(e,t){return xc(e.anchor.status)-xc(t.anchor.status)||e.anchor.alternativeCount-t.anchor.alternativeCount||Cv(e,t)}function xc(e){return{exact:0,derived:1,mixed:2,candidate:3,unknown:4,ambiguous:5}[e]}function Rc(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 fv(e){return`--at ${mN(`${e.file}:${e.line+1}`)}`}function dN(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function mN(e){return`'${e.replaceAll("'","'\\''")}'`}function ti(e,t,n){return`${e}\0${t}\0${n}`}function Cr(e,t,n){return["next-anchor",e,String(t),n].map(encodeURIComponent).join(":")}var Mv=6,pN=12,fN=48,gN=2e4,Rv=12,ni=Number.MAX_SAFE_INTEGER,hN=["definition","callers","callees"],Zd={search:12,"exact-source":24,definition:24,caller:8,callee:8,"production-reference":6,"test-reference":2,dependency:6,consumer:6};function yN(e,t){if(t.cursor)throw new Error("Inspect no longer accepts semantic packet cursors. Run the original inspect selectors again.");let n=SN(t),r=xN(e,n),i=r.candidates.sort((k,T)=>Jd(k,T));n.view==="behavior"&&IN(e,i),wN(e,i),n.view==="behavior"&&RN(e,i);let o=mS(i.map(k=>Xd(k,n.view)),n.evidenceBudgets,(k,T)=>Jd(k.candidate,T.candidate)),{selected:s,omitted:a}=cc(o.selected,n.maxUnits,n.maxCharacters,(k,T)=>Jd(k.candidate,T.candidate),n.view==="source"),c=s.map(k=>k.candidate),l=[...o.omitted,...a].map(k=>k.candidate),u=c.map(NN),d=ya(c.map(k=>k.kind==="source"?k.bindingClosure:void 0),c.filter(k=>k.kind==="source").map(k=>({relativePath:k.relativePath,startLine:k.startLine,endLine:k.endLine}))),m=u.reduce((k,T)=>k+(T.kind==="source"?BN(T.source):0),0),p=u.reduce((k,T)=>k+(T.kind==="source"?T.source.length:0),0),f=u.reduce((k,T)=>k+Av(T,n.view),0),g=u.filter(k=>k.kind==="source"&&(k.roles.includes("search")||k.roles.includes("location"))).map(_N),h=i.filter(k=>k.kind==="source"&&(k.roles.includes("search")||k.roles.includes("location"))).length,b=u.filter(k=>k.kind==="source"&&(k.roles.includes("search")||k.roles.includes("location"))).length,S=r.searches.map(k=>DN(k,i,c)),y=MN(l),x=r.locations.every(k=>k.matched)&&r.evidence.every(k=>k.kind==="matched")&&r.searches.every(k=>kN(k.textCoverage))&&l.every(k=>!k.roles.some(T=>T==="location"||T==="definition")),v=S.reduce((k,T)=>k+T.omittedMatches,0),C=l.length===0&&v===0,E=C?void 0:kv(n,!0),R=LN(n,l),w=bN(C,x,l.length+v,R,S,E),I=i.filter(k=>n.view==="behavior"&&k.kind==="source"&&k.roles.some(T=>T==="location"||T==="definition"||T==="search")).map(k=>({id:`inspect:${k.relativePath}:${k.startLine}-${k.endLine}`,label:k.ownerShort??`${k.relativePath}:${k.startLine+1}`,file:k.relativePath,startLine:k.startLine,endLine:k.endLine})),A=I.length>0?Sv(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:R,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:TN(i,c,n.evidenceBudgets,n.view),...E?{expansionCommand:E}:{}},stoppingSummary:w,...A&&A.candidateAnchors>0?{causalFrontier:A}:{},bindingClosure:d,continuation:null}}function bN(e,t,n,r,i,o){let s=It([...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 SN(e){let t=ze(e.searches),n=ze(e.symbols),r=ze(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&&xr(e.unitLines,"unitLines"),e.totalLines!==void 0&&xr(e.totalLines,"totalLines"),e.sliceLimit!==void 0&&xr(e.sliceLimit,"sliceLimit"),e.maxCharacters!==void 0&&xr(e.maxCharacters,"maxCharacters"),e.maxUnits!==void 0&&xr(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:Pv(e.context??Mv,"context"),searchLimit:xr(e.searchLimit??(s?ni:pN),"searchLimit"),maxUnits:xr(s?ni:e.maxUnits??fN,"maxUnits"),maxCharacters:xr(s?ni:e.maxCharacters??gN,"maxCharacters"),evidenceBudgets:s?CN():vN(e.evidenceBudgets??Zd),view:e.view??"source",evidence:{...o.parts?{parts:[...o.parts]}:n.length>0?{parts:[...hN]}:{},...o.referenceContext!==void 0?{referenceContext:Pv(o.referenceContext,"referenceContext")}:{},relatedSourceLines:o.relatedSourceLines??60,...o.semantic!==void 0?{semantic:o.semantic}:{}}}}function vN(e){let t={...Zd};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 CN(){return Object.fromEntries(Object.keys(Zd).map(e=>[e,ni]))}function xN(e,t){let n=[],r=0,i=lc(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=cr(e,d.relativePath,d.focusLine,ni,t.context);m&&Wi(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?Tv(l,t.scope):void 0,m=u.fileCoverage??[],p=AN(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,Rv),omittedScopeHints:Math.max(0,p.length-Rv),textCoverage:u.textCoverage,...d?{exactFollowup:d}:{}}}),a=t.locations.map(l=>{let u=ON(l),d=u?Lg(e,u.path):null,m=d?cr(e,d,u.line-1,ni,t.context):null;return m&&Wi(e,n,m,"location",`at:${l}`,null,null,0,r++),{target:l,matched:m!==null}}),c=t.symbols.map(l=>qd(e,l,t.evidence));for(let l of c)if(l.kind==="matched"){if(l.definition){let u=cr(e,l.definition.relativePath,l.definition.startLine,ni,t.context);u&&Wi(e,n,u,"definition",`definition:${l.shortName}`,l.symbol,l.shortName,0,r++)}for(let u of l.referenceWindows){let d=u.references[0];Wi(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,K(u.relativePath)==="test"?5:4,r++,u.references.map(m=>m.line),l.symbol)}for(let u of l.callers)Ev(e,n,u,"caller",l,2,r++);for(let u of l.callees)Ev(e,n,u,"callee",l,3,r++);for(let u of l.dependencies)Iv(e,n,"dependency",l.file,u.relativePath,l.symbol,t.context,6,r++);for(let u of l.consumers)Iv(e,n,"consumer",u.relativePath,l.file,l.symbol,t.context,7,r++)}return{searches:s,evidence:c,locations:a,candidates:n}}function Jd(e,t){return e.priority-t.priority||t.roles.length-e.roles.length||t.reasons.length-e.reasons.length||_e(K(e.relativePath))-_e(K(t.relativePath))||e.sequence-t.sequence}function Xd(e,t){return{candidate:e,priority:e.priority,sequence:e.sequence,relativePath:e.relativePath,fileKind:K(e.relativePath),evidenceCharacters:Av(e,t),roles:e.roles,reasons:e.reasons,symbols:e.symbols,behaviorSignals:e.kind==="source"?e.behavior?.signals??[]:[],channel:Qd(e)}}function Qd(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")?K(e.relativePath)==="test"?"test-reference":"production-reference":t.includes("dependency")?"dependency":t.includes("consumer")?"consumer":"search"}function RN(e,t){let n=t.filter(i=>i.kind==="source"),r=So(e,{files:It(n.map(i=>i.relativePath))});for(let i of n){i.behavior=Ti(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=>!EN(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 EN(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 IN(e,t){for(let n of t){if(n.kind!=="source")continue;let r=xt(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=Q(e,n.relativePath).slice(r.startLine,r.endLine+1).join(`
|
|
75
|
+
`),n.unitStartLine=r.startLine,n.unitEndLine=r.endLine,n.omittedLines=0)}}function wN(e,t){for(let n of t)n.kind==="source"&&(n.bindingClosure=Mi(e,n.relativePath,n.startLine,n.endLine))}function LN(e,t){let n=new Map;for(let r of t){let i=Ec(r.relativePath),o=Qd(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=It(i.flatMap(c=>[...c.roles])).sort(),a=It(i.flatMap(c=>c.kind==="source"?c.behavior?.signals??[]:[])).sort();return{id:`g-${Dv("sha256").update(r).digest("hex").slice(0,8)}`,scope:Ec(o.relativePath),channel:Qd(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:PN(e,i)}}).sort((r,i)=>i.candidateUnits-r.candidateUnits||i.sourceCharacters-r.sourceCharacters||r.scope.localeCompare(i.scope)||r.id.localeCompare(i.id))}function PN(e,t){let n=It(t.flatMap(o=>o.reasons.filter(s=>s.startsWith("search:")).map(s=>s.slice(7)))),r=Ec(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 ${Xt(s)}`);return o.push(`--scope ${Xt(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 ${Xt(`${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:kv(e,!0)}function DN(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 MN(e){let t={};for(let n of e)for(let r of n.roles)t[r]=(t[r]??0)+1;return t}function TN(e,t,n,r){let i=e.map(s=>Xd(s,r).channel),o=t.map(s=>Xd(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 kN(e){return!!(e&&e.skippedUnreadablePaths.length===0&&e.skippedOversizedPaths.length===0)}function AN(e,t,n){let r=new Map;for(let i of t){let o=Ec(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:Tv(e,i||n)})).sort((i,o)=>o.matchingLines-i.matchingLines||o.returnedMatches-i.returnedMatches||i.scope.localeCompare(o.scope))}function Ec(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function Tv(e,t){return`scip-query inspect --search ${Xt(e)}${t?` --scope ${Xt(t)}`:""} --full`}function kv(e,t){let n=["scip-query inspect"];for(let r of e.searches)n.push(`--search ${Xt(r)}`);for(let r of e.symbols)n.push(`--symbol ${Xt(r)}`);for(let r of e.locations)n.push(`--at ${Xt(r)}`);return e.scope&&n.push(`--scope ${Xt(e.scope)}`),e.context!==Mv&&n.push(`--context ${e.context}`),e.evidence.parts&&n.push(`--include ${Xt(e.evidence.parts.join(","))}`),t&&n.push("--full"),e.view==="behavior"&&n.push("--view behavior"),n.join(" ")}function Ev(e,t,n,r,i,o,s){Wi(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 Iv(e,t,n,r,i,o,s,a,c){let l=`${r} -> ${i}`,u=pe(e,r).filter(h=>h.sourcePath===i),d=Q(e,r),m=FN(d,u,i),p=m===null?null:La(e,r,m,Math.min(s,4));if(p){Wi(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 ${Xt(Fv(i))} --scope ${Xt(r)}`,g=t.find(h=>h.kind==="path"&&h.relativePath===r&&h.relationship===l);if(g){g.roles=It([...g.roles,n]),g.reasons=It([...g.reasons,`${n}:${l}`]),g.symbols=It([...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 FN(e,t,n){let r=It(t.flatMap(c=>[c.importedName,c.localName??""]).filter(c=>c.length>1)),i=Fv(n).replace(/\.[^.]+$/u,""),o=It([...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 Wi(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=Q(e,n.relativePath).slice(m,p+1).join(`
|
|
76
|
+
`),d.focusLine=Math.min(d.focusLine,n.focusLine),d.focusLines=Lv([...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=It([...d.reasons,i]),d.roles=It([...d.roles,r]),d.symbols=It([...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:Lv(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:wv(a)}}let{priority:t,sequence:n,bindingClosure:r,...i}=e;return{...i,id:wv(i),omittedCharacters:0}}function _N(e){let{kind:t,id:n,roles:r,symbols:i,omittedCharacters:o,behavior:s,runtimeFacts:a,...c}=e;return c}function wv(e){return Dv("sha256").update(JSON.stringify(e)).digest("hex").slice(0,16)}function ON(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 It(e){return[...new Set(e)]}function Lv(e){return It(e).sort((t,n)=>t-n)}function BN(e){return e.length===0?0:e.split(`
|
|
77
|
+
`).length}function Av(e,t){if(e.kind==="path")return e.relationship.length+e.exactFollowup.length;let n="bindingClosure"in e?Ug(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 Fv(e){return e.split("/").at(-1)??e}function Xt(e){return`'${e.replaceAll("'","'\\''")}'`}function xr(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new RangeError(`${t} must be a positive safe integer; received ${e}`);return e}function Pv(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 $N}from"path";function jN(e,t){let n=t.className,r=pt(e,n);return r.match?r.total>1?{kind:"ambiguous",query:n,total:r.total,candidates:[Nv(r.match),...r.candidates]}:{kind:"matched",query:n,owner:UN(r.match),methods:HN(e,r.match)}:{kind:"missing",query:n,suggestions:ia(e,n,5)}}function HN(e,t){let n=W(t.symbol),i=new q(e).definitionsForFile(t.relativePath).filter(c=>mt(c.symbol)),o=i.filter(c=>c.parentTypeName===n||c.symbol.includes(n)),a=(o.length>0?o:qN($N(t.relativePath))===n?i.filter(c=>c.symbol.includes("<invalid-global-code>")):[]).map(c=>({startLine:c.startLine,endLine:c.endLine,name:W(c.symbol)}));return de(t.relativePath)!=="clojure"?a:zN(a,GN(e,t))}function Nv(e){return{symbol:e.symbol,shortName:M(e.symbol),relativePath:e.relativePath,startLine:e.startLine}}function UN(e){return{...Nv(e),endLine:e.endLine}}function qN(e){return e.replace(/\.[^.]+$/,"")}function GN(e,t){let n=W(t.symbol);return n?(Y(e,t.relativePath)?.clojureMembers??[]).filter(r=>r.ownerName===n).map(r=>({startLine:r.startLine,endLine:r.endLine,name:r.memberName})):[]}function zN(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 JB}from"crypto";var Ene={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."},KN=[{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 WN(e){let t=new Set(e);return KN.filter(n=>n.families.some(r=>t.has(r)))}function _v(e){return WN(e).map(t=>`[${t.id}] ${t.capability} ${t.consequence} Recover selected paths with: ${t.recoverWith.map(n=>`scip-query ${n}`).join(", ")}.`)}var VN=["incoming","outgoing","both"];function we(e,t,n,r={}){return{family:e,subtype:t,...r.match?{match:r.match}:{},directions:VN,evidenceStrengths:r.strengths??["exact","derived","mixed"],supportCeiling:r.supportCeiling??"partial",establishes:n,nonClaims:r.nonClaims??[],recoverWith:r.recoverWith??["inspect","code"]}}var YN=["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"],JN=["captured-value-to-state","constant-to-state","expression-to-state","property-to-state","return-to-state","value-to-state"],XN=["await-completion-before","awaits-completion","inside-lock-scope","lexical-successor"],QN=[{id:"indexed-program-identity",label:"SCIP/compiler identity and source ownership",requirements:["indexed-graph"],relations:[we("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"]}),we("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"]}),we("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"]}),we("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"]}),we("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"]}),we("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"]}),we("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"]}),we("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"]}),we("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:[we("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"]}),we("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"]}),we("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"]}),we("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:[...YN.map(e=>we("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"]})),we("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"]}),we("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=>we("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:[we("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"]}),we("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"]}),we("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"]}),we("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"]}),we("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:[...JN.map(e=>we("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=>we("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"]})),...XN.map(e=>we("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 Ic(e,t){let n=QN.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 on=["execution","runtime","dataflow","state","temporal","contract","identity","ownership","dependencies"];function Ve(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 Vi(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 Ov(e,t){return Vi(e.origins)-Vi(t.origins)||e.depth-t.depth||e.startLine-t.startLine||e.shortName.localeCompare(t.shortName)}var Bv=["call","contract-symbol","import","reference","runtime-boundary"],ZN={call:[{family:"control",subtype:"call"}],"contract-symbol":[{family:"contract",subtype:"uses-contract-symbol"}],import:[{family:"identity",subtype:"imports"}],reference:[{family:"identity",subtype:"references"}]},e_={"structural-membership":[{family:"identity",subtype:"contains"}],"boundary-observation":[{family:"identity",subtype:"owns-runtime-observation"}],"external-import":[{family:"identity",subtype:"imports-external"}]};function $v(e){if(e.kind!=="runtime-boundary")return jv(ZN[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 wc(e){return jv(e_[e])}function jv(e){return e.map(t=>({...t,...t.context?{context:{...t.context}}:{},...t.attributes?{attributes:{...t.attributes}}:{}}))}import{join as w_}from"path";import{createRequire as t_}from"module";import{resolve as as}from"path";var n_=t_(import.meta.url),ss;function Uv(e,t,n){let r=r_();if(!r)return em("The TypeScript compiler runtime is unavailable.");let i=i_(r,e,t),o=i.getSourceFile(as(t))??i.getSourceFile(t);if(!o)return em(`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=s_(r,o,n);if(a.length===0)return em("No function-like construct intersects the selected source range.");let c=new Map(a.map(d=>[d,a_(o,d)])),l=a.map(d=>l_(s,d,c_(r,d,c),c.get(d)));for(let d of l)u_(s,d),f_(s,d),y_(s,d);S_(s,l);let u=[...s.unsupported].sort();return{points:[...s.points.values()].map(({node:d,...m})=>m).sort(I_),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 r_(){if(ss!==void 0)return ss;try{ss=n_("typescript")}catch{ss=da()?.ts??null}return ss}function i_(e,t,n){let r=as(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,o_(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)=>as(u)===r?o:a(u,d,m,p),s.readFile=u=>as(u)===r?t:c(u),s.fileExists=u=>as(u)===r||l(u),e.createProgram([r],i,s)}function o_(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 s_(e,t,n){let r=[],i=o=>{if(qv(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 qv(e,t){return e.isFunctionLike(t)&&"body"in t&&t.body!==void 0}function a_(e,t){return`callable:${encodeURIComponent(e.fileName)}:${t.getStart(e)}:${t.getEnd()}`}function c_(e,t,n){for(let r=t.parent;r;r=r.parent)if(qv(e,r)&&n.has(r))return n.get(r);return null}function l_(e,t,n,r){let i=new Map,o=it(e,i,"exit",null),s=t.body,a=o.id;if(s&&e.ts.isBlock(s))a=tm(e,i,[...s.statements],o.id,{breakTarget:null,continueTarget:null});else if(s){let l=it(e,i,"statement",s);Fe(i,l.id,o.id),a=l.id}let c=it(e,i,"entry",t);return Fe(i,c.id,a),{id:r,node:t,parentId:n,cfg:i,entryId:c.id,exitId:o.id}}function tm(e,t,n,r,i){let o=r;for(let s=n.length-1;s>=0;s-=1)o=ri(e,t,n[s],o,i);return o}function ri(e,t,n,r,i){let o=e.ts;if(o.isBlock(n))return tm(e,t,[...n.statements],r,i);if(o.isIfStatement(n)){let a=it(e,t,"predicate",n.expression),c=ri(e,t,n.thenStatement,r,i),l=n.elseStatement?ri(e,t,n.elseStatement,r,i):r;return Fe(t,a.id,c),Fe(t,a.id,l),a.id}if(o.isWhileStatement(n)){let a=it(e,t,"predicate",n.expression),c=ri(e,t,n.statement,a.id,{breakTarget:r,continueTarget:a.id});return Fe(t,a.id,c),Fe(t,a.id,r),a.id}if(o.isDoStatement(n)){let a=it(e,t,"predicate",n.expression),c=ri(e,t,n.statement,a.id,{breakTarget:r,continueTarget:a.id});return Fe(t,a.id,c),Fe(t,a.id,r),c}if(o.isForStatement(n)){let a=it(e,t,"predicate",n.condition??n),c=n.incrementor?it(e,t,"statement",n.incrementor):null;c&&Fe(t,c.id,a.id);let l=c?.id??a.id,u=ri(e,t,n.statement,l,{breakTarget:r,continueTarget:l});if(Fe(t,a.id,u),n.condition&&Fe(t,a.id,r),!n.initializer)return a.id;let d=it(e,t,"statement",n.initializer);return Fe(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=it(e,t,"predicate",n.expression),c=it(e,t,"statement",n.initializer),l=ri(e,t,n.statement,a.id,{breakTarget:r,continueTarget:a.id});return Fe(t,a.id,c.id),Fe(t,a.id,r),Fe(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=it(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=tm(e,t,[...d.statements],c,{...i,breakTarget:r}),l.push(c)}for(let u of l)Fe(t,a.id,u);return Fe(t,a.id,r),a.id}if(o.isReturnStatement(n)||o.isThrowStatement(n)){let a=it(e,t,"statement",n),c=[...t.values()].find(l=>l.kind==="exit");return Fe(t,a.id,c.id),a.id}if(o.isBreakStatement(n)){let a=it(e,t,"statement",n);return i.breakTarget||e.unsupported.add("A break statement could not be attached to a structured target."),Fe(t,a.id,i.breakTarget??r),a.id}if(o.isContinueStatement(n)){let a=it(e,t,"statement",n);return i.continueTarget||e.unsupported.add("A continue statement could not be attached to a structured target."),Fe(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=it(e,t,"statement",n);return a.invalidatesAllDefinitions=!0,Fe(t,a.id,r),a.id}let s=it(e,t,"statement",n);return Fe(t,s.id,r),s.id}function it(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 Fe(e,t,n){e.get(t).successors.add(n),e.get(n).predecessors.add(t)}function u_(e,t){let n=t.cfg.get(t.entryId);for(let r of t.node.parameters){let i=ii(e,r.name);if(!i){e.unsupported.add("Destructured parameter definition-use is not implemented.");continue}n.definitions.push({point:oi(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=oi(e,r.ast,"predicate",null,"predicate",t.id)),d_(e,t,r,r.ast),!r.displayPoint&&r.definitions.length===0&&r.uses.length===0&&(r.displayPoint=oi(e,r.ast,"statement",null,C_(e,r.ast),t.id)))}function d_(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?Lc(e,t.id,s.initializer,n):[];n.uses.push(...a);let c=ii(e,s.name);c?n.definitions.push({point:oi(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)&&Kv(i,s.operatorToken.kind)){let a=Lc(e,t.id,s.right,n);s.operatorToken.kind!==i.SyntaxKind.EqualsToken&&a.push(...Lc(e,t.id,s.left,n)),n.uses.push(...a);let c=ii(e,s.left);c?n.definitions.push({point:oi(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=Lc(e,t.id,s.operand,n);n.uses.push(...a);let c=ii(e,s.operand);c&&n.definitions.push({point:oi(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(Gv(e,s)){let a=zv(e,t.id,s);a&&n.uses.push(a),i.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}}};o(r),n.uses=Wv(n.uses)}function Lc(e,t,n,r){let i=[],o=s=>{if(!e.ts.isFunctionLike(s)){if(e.ts.isBinaryExpression(s)&&Kv(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(Gv(e,s)){let a=zv(e,t,s);a&&i.push(a),e.ts.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}};return o(n),Wv(i)}function Gv(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&&m_(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)||p_(e.ts,t))}function m_(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 p_(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 zv(e,t,n){let r=ii(e,n);return r?{point:oi(e,r.node,"use",r.symbolKey,r.name,t),property:e.ts.isPropertyAccessExpression(n)}:null}function ii(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)?ii(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 oi(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 f_(e,t){let n=[...t.cfg.values()].flatMap(c=>c.definitions),r=new Map(n.map(c=>[c.point.id,c])),i=g_(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=R_([...c.predecessors].map(m=>s.get(m))),u=new Set(l);c.invalidatesAllDefinitions&&u.clear();let d=h_(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)}nm(o.get(c.id),l)||(o.set(c.id,l),a=!0),nm(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&&cs(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)cs(e,"value-source",d,u.point.id,"exact","This right-hand-side use supplies the new definition.")}}function g_(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 h_(e){let t=new Map;for(let n of e)n.point.symbolKey&&t.set(n.point.symbolKey,n);return[...t.values()]}function y_(e,t){let n=b_(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 x_(c))cs(e,"control-dependence",r.displayPoint.id,l.id,"exact","The target postdominates a branch successor but does not postdominate the predicate.")}}}function b_(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,...E_(s)]);nm(r.get(o.id),a)||(r.set(o.id,a),i=!0)}}return r}function S_(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)v_(l.callableId,a.point.callableId,n)?cs(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&&cs(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 v_(e,t,n){for(let r=n.get(t)??null;r;r=n.get(r)??null)if(r===e)return!0;return!1}function cs(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 Kv(e,t){return t>=e.SyntaxKind.FirstAssignment&&t<=e.SyntaxKind.LastAssignment}function C_(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 Wv(e){return[...new Map(e.map(t=>[t.point.id,t])).values()]}function x_(e){return[...new Map(e.map(t=>[t.id,t])).values()]}function R_(e){return new Set(e.flatMap(t=>[...t]))}function E_(e){return e.length===0?new Set:new Set([...e[0]].filter(t=>e.slice(1).every(n=>n.has(t))))}function nm(e,t){return e.size===t.size&&[...e].every(n=>t.has(n))}function I_(e,t){return e.start-t.start||e.kind.localeCompare(t.kind)||e.id.localeCompare(t.id)}function em(e){return{points:[],edges:[],coverage:{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:[e]}}}var L_=Xn("typescript-local-flow",{clearGroups:["whole-project","source-file","semantic-provider"]});function rm(e,t,n,r){if(!or(t))return null;let i=`${t}\0${n}\0${r}`;return L_.get(e,i,()=>{let o=X(e,t);return o?Uv(o,w_(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 P_(e,t=new Map){let n=new Map,r=new Map,i=[];for(let o of e.transfers){if(!e.caller)continue;let s=Pc(e.caller,o.callerPosition),a=Pc(e.callee,o.calleePosition);ls(n,s),ls(n,a),om(r,e.caller,s),om(r,e.callee,a);let c=yt("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=Pc(e.callee,o.calleePosition);ls(n,a),om(r,e.callee,a);let c=t.get(o.calleePosition);if(c&&$_(c)){B_(r,n,e,o.calleePosition,o.argumentText,c);return}let l=__(e,o.calleePosition,o.argumentText);ls(n,l);let u=yt("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:yt("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 Yv(e,t,n=[]){let r=Jv(),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=pg(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=fg(e,u),p=te(e,u.file)?.rootNode,f=new Map;if(p)for(let g of m.unknown){let h=mg({db:e,file:u.file,root:p},u.arguments[g.calleePosition]);h&&f.set(g.calleePosition,h)}Vv(r,P_(m,f)),m.caller&&A_(u.callNode)&&F_(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=rm(e,s.location.file,s.location.line,a);if(c){Vv(r,D_(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 D_(e,t,n){let r=Jv(),i=new Map,o=new Map,s=new Map,a=e.location.file;for(let c of t){let l=M_(e,a,c);s.set(c.id,l.id),i.set(l.id,l),T_(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=k_(c),m=yt("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 M_(e,t,n){return{id:yt("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 T_(e,t,n){let r=yt("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 k_(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 A_(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 F_(e,t,n){if(!t.caller)return;let r={id:yt("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=yt("edge","return-to-call-result",t.callee.symbol,r.id),o=yt("edge","call-result-owner",t.caller.symbol,r.id);e.nodes.push(r),e.edges.push({id:i,kind:"data-transfer",fromNodeId:sm(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:sm(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 Jv(){return{nodes:[],edges:[],frontiers:[],blindSpots:[]}}function Vv(e,t){im(e.nodes,t.nodes),im(e.edges,t.edges),im(e.frontiers,t.frontiers),e.blindSpots.push(...t.blindSpots)}function im(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=z(t,n).find(a=>a.symbol===r)??null;return e.set(i,s),s}function Pc(e,t){return{id:U_(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 __(e,t,n){return{id:yt("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 O_(e,t,n){return{id:yt("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 B_(e,t,n,r,i,o){let s=O_(n,r,o),a=Pc(n.callee,r);ls(t,s);let c=yt("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:j_(o),attributes:{argumentText:i,calleePosition:r,value:o.value,precision:o.precision,derivationRule:o.derivation.rule}}],evidence:H_(o,n)})}function $_(e){return e.derivation.kind!=="heuristic"&&e.precision!=="symbolic"&&e.precision!=="unknown"}function j_(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 H_(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 ls(e,t){e.has(t.id)||e.set(t.id,t)}function om(e,t,n){let r=yt("edge","parameter-owner",t.symbol,n.id);e.has(r)||e.set(r,{id:r,kind:"parameter-owner",fromNodeId:sm(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 U_(e,t){return yt("parameter",e,String(t))}function sm(e){return yt("symbol",e)}function yt(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function Xv(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=Yg(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=am(s,l.controller),d=am(s,l.outcome);n.set(u.id,u),n.set(d.id,d),q_(r,s,u);let m=si("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=am(s,l);n.set(u.id,u);let d=l.label.startsWith("throw")||l.label.startsWith("raise")?"throw":"return",m=si("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=si("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=si("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=si("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 am(e,t){let n=e.location.file;return{id:si(`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 q_(e,t,n){let r=si("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 si(...e){return e.map(t=>encodeURIComponent(t)).join(":")}var Dc=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"]),ds=new Set(["block","body","compound_statement","declaration_list","statement_block"]),G_=new Set(["assignment","assignment_expression","augmented_assignment_expression"]),lm=new Set(["update_expression"]),tC=new Set(["array_access","element_access_expression","subscript_expression"]),nC=new Set(["attribute","field_access","field_expression","member_access_expression","member_expression","selector_expression"]),z_=new Set(["false","null","null_literal","number","number_literal","string","string_literal","template_string","true"]),K_=new Set(["call_expression","method_invocation","object_creation_expression"]),W_=new Set(["comment","else_clause","formal_parameters","parameters","type_parameters"]);function rC(e,t,n,r){let i=te(e,t);if(!i)return null;let o=tO(i.rootNode,n,r);if(!o)return null;let s=[],a=[],c=[];return ai(o,l=>{if(G_.has(l.type)||lm.has(l.type)||oC(l)){let u=V_(l);u?s.push(u):c.push({family:"state",startLine:l.startPosition.row,endLine:l.endPosition.row,reason:`Mutation target ${Cn(l.text)} could not be resolved to an exact source resource.`})}}),ai(o,l=>{if(!ds.has(l.type))return;let u=Z_(l);for(let d=0;d<u.length-1;d+=1)a.push({from:us(u[d]),to:us(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=rO(m).filter(f=>f.type==="await_expression");for(let f of p){let g=ms("event",`await ${Cn(f.text.replace(/^await\s+/u,""))}`,f);a.push({from:us(m),to:g,subtype:"awaits-completion",synchronizationScope:null,attributes:{completionRequired:!0}});let h=u[d+1];h&&a.push({from:g,to:us(h),subtype:"await-completion-before",synchronizationScope:null,attributes:{continuationOnly:!0}})}}}),ai(o,l=>{if(l.type!=="synchronized_statement")return;let u=l.childForFieldName("object")??l.childForFieldName("condition")??l.namedChildren.find(g=>!ds.has(g.type)),d=l.childForFieldName("body")??l.namedChildren.find(g=>ds.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=Cn(u.text).replace(/^\(|\)$/gu,""),p=ms("lock",m,u),f=nO(d).filter(g=>g.parent!==null&&sC(g));for(let g of eO(f))a.push({from:p,to:us(g),subtype:"inside-lock-scope",synchronizationScope:m,attributes:{syntaxNative:!0}})}),{mutations:s,temporal:a,unsupported:c}}function V_(e){let t=oC(e),n=e.childForFieldName("left")??e.childForFieldName("argument")??(t?e.namedChildren.at(-1)??null:e.namedChildren[0]??null);if(!n)return null;let r=Y_(n);if(!r)return null;let i=t?"delete":lm.has(e.type)||!Q_(e,n).startsWith("=")?"update":"assign",o=t||lm.has(e.type)?null:e.childForFieldName("right");return{event:ms("event",Cn(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?ms("value",Cn(o.text),o):null,dataSubtype:o?J_(o,e):null}}function Y_(e){if(tC.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:`${Cn(t.text)}[]`,recordIdentity:Cn(n.text)}}return nC.has(e.type)?{name:Cn(e.text),recordIdentity:null}:/^(?:identifier|property_identifier|field_identifier)$/u.test(e.type)?{name:Cn(e.text),recordIdentity:null}:null}function J_(e,t){return z_.has(e.type)||/(?:integer|float|decimal|boolean|character)_literal$/u.test(e.type)?"constant-to-state":K_.has(e.type)?"return-to-state":nC.has(e.type)||tC.has(e.type)?"property-to-state":/identifier$/u.test(e.type)?X_(e.text,t)?"captured-value-to-state":"value-to-state":"expression-to-state"}function X_(e,t){let n=cm(t.parent);if(!n||Qv(n,e))return!1;let r=cm(n.parent);for(;r;){if(Qv(r,e))return!0;r=cm(r.parent)}return!1}function cm(e){let t=e;for(;t;){if(Dc.has(t.type))return t;t=t.parent}return null}function Qv(e,t){let n=e.childForFieldName("parameters")??e.namedChildren.find(o=>["formal_parameters","parameters"].includes(o.type));if(n&&Zv(n,t))return!0;let r=e.childForFieldName("body")??e.namedChildren.find(o=>ds.has(o.type));if(!r)return!1;let i=!1;return iC(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&&Zv(s,t)&&(i=!0)}),i}function Zv(e,t){let n=!1;return ai(e,r=>{/identifier$/u.test(r.type)&&r.text===t&&(n=!0)}),n}function iC(e,t,n){n(e);for(let r of e.namedChildren)r!==t&&Dc.has(r.type)||iC(r,t,n)}function Q_(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 oC(e){return(e.type==="delete_expression"||e.type==="unary_expression")&&/^delete\b/u.test(e.text.trim())}function Z_(e){return e.namedChildren.filter(t=>sC(t))}function sC(e){return W_.has(e.type)||ds.has(e.type)?!1:/(?:statement|declaration)$/u.test(e.type)||e.type==="expression_statement"||e.type==="local_variable_declaration"}function eO(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 us(e){return ms("event",Cn(e.text),e)}function ms(e,t,n){return{kind:e,label:t,startLine:n.startPosition.row,endLine:n.endPosition.row}}function tO(e,t,n){let r=[];return ai(e,o=>{o.startPosition.row<=t&&o.endPosition.row>=n&&r.push(o)}),r.filter(o=>Dc.has(o.type)).sort(eC)[0]??r.sort(eC)[0]??null}function eC(e,t){return e.endIndex-e.startIndex-(t.endIndex-t.startIndex)||e.startIndex-t.startIndex}function nO(e){let t=[];return ai(e,n=>t.push(n)),t}function rO(e){let t=[],n=r=>{t.push(r);for(let i of r.namedChildren)i!==e&&Dc.has(i.type)||n(i)};return n(e),t}function ai(e,t){t(e);for(let n of e.namedChildren)ai(n,t)}function Cn(e){return e.trim().replace(/\s+/gu," ")}function lC(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=rC(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=Tc(a,u.event),m=lO(a,u.resource,u.durabilityClass);if(r.set(d.id,d),r.set(m.id,m),kc(i,a,d,"contains-state-effect"),Ac(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=Tc(a,u.value);r.set(p.id,p),Ac(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=Tc(a,u.from),m=Tc(a,u.to);r.set(d.id,d),r.set(m.id,m),kc(i,a,d,u.from.kind==="lock"?"contains-lock-scope":"contains-event"),kc(i,a,m,"contains-event"),Ac(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=qn(`${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=qn("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=qn("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=Mc(a,"protocol"),l=Mc(a,"action"),u=Mc(a,"address")??a.label;!c||!l||!cC(c,l)||aC(r,i,a,{observationId:a.id,action:l,strength:"exact",file:a.location?.file??"",line:a.location?.line??0,address:u,protocol:c,role:Mc(a,"role")??void 0,resolution:"locally-linked"})}for(let a of n){if(!a.protocol||!cC(a.protocol,a.action))continue;let c=aO(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}aC(r,i,c,a)}return{nodes:[...r.values()],edges:[...i.values()],frontiers:[...o.values()],blindSpots:[...s].sort()}}function aC(e,t,n,r){let i=oO(r),s={id:qn("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:qn("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),kc(t,n,s,"contains-runtime-state-effect");let l=iO(r.action);Ac(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:sO(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 iO(e){return e==="database.read"?"reads-resource":e==="queue.send"?"enqueues-resource":e==="queue.consume"?"consumes-resource":"writes-resource"}function oO(e){return(e.keyParts?.find(n=>["address","resource"].includes(n.name))?.value??e.address)||e.observationId}function sO(e){return e.keyParts?.find(n=>/^(?:id|key|record)$/u.test(n.name))?.value??null}function cC(e,t){return e==="database"&&["database.read","database.write"].includes(t)||e==="queue"&&["queue.consume","queue.send"].includes(t)}function Mc(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function aO(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(cO)[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 cO(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 Tc(e,t){let n=e.location.file;return{id:qn(`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 lO(e,t,n){let r=e.location.file;return{id:qn("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 kc(e,t,n,r){let i=qn("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 Ac(e,t){let n=qn("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 qn(...e){return e.map(t=>encodeURIComponent(t)).join(":")}var uO=new Set(["control","data","state","temporal"]),Fc=new Set(["contains-control","contains-event","contains-lock-scope","contains-state-effect","contains-runtime-state-effect","contains","owns-parameter","owns-runtime-observation"]),pC=new Set(["discriminator-dispatch","result-callback","returns","runtime-handoff","throws"]);function fC(e,t={}){let n=new Map(e.nodes.map(R=>[R.id,R])),r=yO(e.nodes,t.focusLocations),i=bO(e.edges,t.focusLocations),o=SO(e.edges,i),s=new Set(e.paths.flatMap(R=>R.edgeIds)),a=Gn(e.anchors.filter(R=>R.status==="matched").flatMap(R=>R.nodeIds)),l=e.edges.filter(mC).filter(R=>dO(R,r,i,s)),u=l.filter(R=>gO(R,r,i,o,n,s)),d=uC(a,u,"forward"),m=fO(d,u),p=uC(m,u,"backward"),f=new Set([...d].filter(R=>p.has(R)));for(let R of a)f.add(R);let g=new Set(u.filter(R=>f.has(R.fromNodeId)&&f.has(R.toNodeId)).map(R=>R.id)),h=new Set(f),b=new Set(g);mO(l,h,b,r,i);let S=e.frontiers.filter(R=>CO(R,h)),y=Gn(S.filter(R=>R.disposition==="unsupported").map(R=>R.id)),x=Gn(e.edges.filter(R=>!mC(R)&&hC(R)&&vO(R,h)).map(R=>R.id)),v=Gn(S.map(R=>R.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 E=C.length===0?"complete":"incomplete";return{schemaVersion:1,status:E,startNodeIds:a,outcomeNodeIds:m,baseNodeIds:Gn([...f]),baseEdgeIds:Gn([...g]),nodeIds:Gn([...h]),edgeIds:Gn([...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:E==="complete"?"Every proved anchor-to-outcome path is closed over its material causal facts within reported coverage.":C.join(" ")}}function dO(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"&&Fc.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(yC(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 mO(e,t,n,r,i){let o=!0;for(;o;){o=!1;for(let s of e)pO(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 pO(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"?Fc.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"?gC(s)||["returns","throws"].includes(s.subtype)&&!o&&n!==null&&!n.has(e.toNodeId)?!1:pC.has(s.subtype)||yC(s)||s.subtype==="completion-callback":!1)}function fO(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"&&pC.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 Gn([...n])}function uC(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 gO(e,t,n,r,i,o){return(e.semantics??[]).some(s=>e.disposition==="emitted"||o.has(e.id)?!0:s.family==="identity"&&Fc.has(s.subtype)?t===null||t.has(e.toNodeId)||r?.has(e.toNodeId)===!0:!uO.has(s.family)||gC(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"?hO(e,i)&&(t.has(e.fromNodeId)||t.has(e.toNodeId)):!1)}function gC(e){return e.family==="control"&&["call","discriminator-dispatch","result-callback","runtime-handoff"].includes(e.subtype)}function hO(e,t){let n=t.get(e.fromNodeId),r=t.get(e.toNodeId);if(!n||!r)return!1;let i=dC(n,"ownerNodeId")??(n.kind==="symbol"?n.id:null),o=dC(r,"ownerNodeId")??(r.kind==="symbol"?r.id:null);return i!==null&&i===o}function yO(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 bO(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 SO(e,t){return t===null?null:new Set(e.filter(n=>t.has(n.id)).flatMap(n=>[n.fromNodeId,n.toNodeId]))}function dC(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function mC(e){return e.disposition==="excluded"||e.disposition==="unsupported"||!hC(e)?!1:e.evidence.some(t=>t.strength==="exact"||t.strength==="derived")}function hC(e){return(e.semantics??[]).some(t=>t.family!=="identity"||Fc.has(t.subtype))}function yC(e){return e.subtype.startsWith("predicate-")||e.subtype.startsWith("loop-")||e.subtype.startsWith("exception-")||e.subtype.startsWith("finally-")||e.subtype.startsWith("handler-")}function vO(e,t){return t.has(e.fromNodeId)||t.has(e.toNodeId)}function CO(e,t){return[...e.fromNodeIds,...e.memberNodeIds].some(n=>t.has(n))}function Gn(e){return[...new Set(e)].sort()}import{createHash as xO}from"crypto";var Nc=["identity","contract","control","data","state","temporal"],RO=new Set(Nc);function Oc(e){let t=Ji(e.anchors,"anchor"),n=Ji(e.nodes,"node"),r=Ji(e.edges,"edge"),i=Ji(e.paths??[],"path"),o=Ji(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:Ji(e.routeCatalog.routes,"route"),selectedRouteIds:wt(e.routeCatalog.selectedRouteIds)}:void 0;for(let p of t)At(`anchor ${p.id}`,[...p.nodeIds,...p.candidateNodeIds],a,"node");for(let p of n)At(`node ${p.id}`,p.anchorIds,s,"anchor");for(let p of r){if(At(`edge ${p.id}`,[p.fromNodeId,p.toNodeId],a,"node"),p.evidence.length===0)throw new Error(`Exploration edge ${p.id} has no evidence source.`);wO(p)}for(let p of i)At(`path ${p.id}`,[p.fromAnchorId,p.toAnchorId],s,"anchor"),At(`path ${p.id}`,p.nodeIds,a,"node"),At(`path ${p.id}`,p.edgeIds,c,"edge");for(let p of o)if(At(`frontier ${p.id}`,p.fromNodeIds,a,"node"),At(`frontier ${p.id}`,p.edgeIds,c,"edge"),At(`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??[])At(`route ${p.id}`,p.nodeIds,a,"node"),At(`route ${p.id}`,p.edgeIds,c,"edge"),At(`route ${p.id}`,[p.anchorNodeId,p.endpointNodeId],a,"node");l&&At("route catalog selection",l.selectedRouteIds,new Set(l.routes.map(p=>p.id)),"route");let u=wt(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:wC(n),edges:wC(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:IO(r),blindSpots:wt(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:DO(d,i,e.scope),...l?{routeCatalog:l}:{}}}function EO(e){return e.flatMap(t=>LO(t.semantics??[]).map(n=>({id:PO(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 IO(e){let t=EO(e),n=new Set(t.map(s=>s.sourceEdgeId)),r=new Map(Nc.map(s=>[s,new Set])),i=new Map(Nc.map(s=>[s,new Set])),o=new Map(Nc.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:wt(e.filter(s=>!n.has(s.id)).map(s=>s.kind)),families:{identity:Yi("identity",r,o,i),contract:Yi("contract",r,o,i),control:Yi("control",r,o,i),data:Yi("data",r,o,i),state:Yi("state",r,o,i),temporal:Yi("temporal",r,o,i)}}}function Yi(e,t,n,r){return{sourceEdges:t.get(e)?.size??0,projectedEdges:n.get(e)??0,subtypes:[...r.get(e)??[]].sort()}}function wO(e){let t=new Set;for(let n of e.semantics??[]){if(!RO.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=um(n);if(t.has(r))throw new Error(`Exploration edge ${e.id} repeats program edge semantic ${r}.`);t.add(r)}}function LO(e){return[...e].sort((t,n)=>um(t).localeCompare(um(n)))}function um(e){return`${e.family}:${e.subtype}`}function PO(e,t){return`program:${encodeURIComponent(e)}:${t.family}:${encodeURIComponent(t.subtype)}`}function DO(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 LC(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 A=I+1;A<o.length;A+=1){let k=o[I],T=o[A],L=xC(e,k,T,!1),N=L??xC(e,k,T,!0);N?(N.nodeIds.forEach(re=>r.add(re)),i.push({id:_c("path",k.id,T.id),fromAnchorId:k.id,toAnchorId:T.id,status:!L||k.status==="ambiguous"||T.status==="ambiguous"?"candidate":"connected",nodeIds:N.nodeIds,edgeIds:N.edgeIds})):i.push({id:_c("path",k.id,T.id),fromAnchorId:k.id,toAnchorId:T.id,status:"partial",nodeIds:[],edgeIds:[]})}let s=wt(t.routeIds??[]),a=MO(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(A=>r.add(A));let m=i.length===0||i.some(I=>I.edgeIds.length>0);m&&EC(e,r,n);let p=IC(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(A=>r.add(A));m&&EC(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 A=0;A<I.nodeIds.length;A+=1){let k=I.nodeIds[A],T=A;y.set(k,Math.max(y.get(k)??0,T))}let x=e.nodes.map(I=>{let A=b.get(I.id),k=S.has(I.id)?{upstreamCausalPath:!0,upstreamCausalDistance:y.get(I.id)??0,...A?{upstreamCausalEndpoint:A}:{}}:{};return{...I,attributes:{...I.attributes,...k},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"})),E=Oc({anchors:e.anchors,nodes:x,edges:C,paths:i,frontiers:[...e.frontiers.filter(I=>I.disposition!=="folded"),...IC({...e,nodes:x,edges:C},r)],scope:e.coverage.scope,blindSpots:e.coverage.blindSpots,incompleteReasons:e.coverage.status==="incomplete"?[e.coverage.explanation]:[],routeCatalog:a}),R=new Set(E.frontiers.flatMap(I=>I.edgeIds)),w=E.edges.filter(I=>I.disposition==="folded"&&!R.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 E}var bC=10;function MO(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(!TO(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(ps(S))-Number(ps(b))||CC(S)-CC(b)||b.fromNodeId.localeCompare(S.fromNodeId)||b.id.localeCompare(S.id));let o=wt(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(),E=[...b.edgeIds].reverse(),R=new Set(C),w=E.flatMap(L=>{let F=r.get(L);return F?[F]:[]}),I=e.edges.filter(L=>L.disposition!=="excluded"&&L.disposition!=="unsupported"&&(R.has(L.fromNodeId)||R.has(L.toNodeId))),A={id:_c("route",h,y,S,...E),status:"proved",anchorNodeId:h,anchorLabel:v.label,endpointNodeId:y,endpointLabel:x.label,endpointLocation:{...x.location},endpointKind:S,nodeIds:C,edgeIds:E,evidenceStrengths:wt(w.flatMap(L=>L.evidence.map(F=>F.strength))),spineEdgeFamilies:SC(w,!0),relatedEdgeFamilies:SC(I,!1),crossesRuntimeBoundary:w.some(ps)},k=`${h}\0${y}\0${S}`,T=s.get(k);(!T||vC(A,T)<0)&&s.set(k,A)};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>=bC){C.some(E=>!x.nodeIds.includes(E.fromNodeId))&&a.add(h);continue}for(let E of C){if(x.nodeIds.includes(E.fromNodeId))continue;let R=x.edgeIds.length+1,w=S.get(E.fromNodeId);if(w!==void 0&&w<=R)continue;let I={nodeIds:[...x.nodeIds,E.fromNodeId],edgeIds:[...x.edgeIds,E.id]};if(S.set(E.fromNodeId,R),ps(E)&&n.get(E.fromNodeId)?.location){c(h,I,"runtime-boundary");continue}b.push(I)}}}let l=[...s.values()].sort(vC),u=new Set(l.map(h=>h.id)),d=wt(t.filter(h=>u.has(h))),m=wt(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:bC,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 SC(e,t){let n=e.flatMap(r=>r.semantics?.map(i=>i.family)??[]);return t&&e.length>0&&n.length===0&&n.push("control"),wt(n)}function vC(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 TO(e){return e.disposition!=="excluded"&&e.disposition!=="unsupported"&&kO(e)&&e.evidence.some(t=>["exact","derived","mixed"].includes(t.strength))}function kO(e){return ps(e)||e.kind==="boundary-observation"||e.kind==="call"||e.kind==="compiler:call"}function ps(e){return e.kind==="runtime-boundary"||e.kind.startsWith("runtime:")}function CC(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 xC(e,t,n,r){return RC(e,t,n,r)??RC(e,n,t,r)}function RC(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||AO(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 AO(e,t,n,r){let i=e.get(t)??[];i.push({nodeId:n,edgeId:r}),e.set(t,i)}function FO(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 EC(e,t,n){let r=-1;for(;t.size!==r&&t.size<n;)r=t.size,FO(e,t,n)}function IC(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=wt(l.map(f=>a.has(f.fromNodeId)?f.toNodeId:f.fromNodeId)),d=new Set(l.map(f=>a.has(f.toNodeId)?"outgoing":"incoming")),m=wt(c.map(f=>f.id)),p=wt(l.map(f=>f.kind));return{id:_c("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 _c(e,...t){let n=xO("sha256").update(t.join("\0")).digest("hex").slice(0,16);return`${e}:${n}`}function Ji(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 At(e,t,n,r){let i=wt(t.filter(o=>!n.has(o)));if(i.length>0)throw new Error(`Exploration ${e} references missing ${r}(s): ${i.join(", ")}`)}function wC(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 wt(e){return[...new Set(e)].sort()}var NO=5,_O=12,OO=8,BO=3,PC=8,$O=6,jO=12,DC=12,HO=12,UO=2,qO=new Set(["branch","loop","call","await","return","throw","mutation","catch","finally"]),GO=9e3,MC=Bv,TC=new WeakMap;function zO(e,t){return UC(e,t,"full")}function HC(e,t){return UC(e,t,"topology")}function UC(e,t,n){let r=ze(t.searches??[]),i=ze(t.symbols??[]),o=ze(t.relations&&t.relations.length>0?t.relations:MC),s=o.filter(P=>!MC.includes(P));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=ze(t.sourceScopes&&t.sourceScopes.length>0?t.sourceScopes:["production"]),u=["production","test","fixture","example","generated","script","unknown"],d=l.filter(P=>!u.includes(P));if(d.length>0)throw new Error(`Unsupported system-map source scope(s): ${d.join(", ")}`);let m=new Set(l),p=P=>m.has(Vl(P));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??GO;if(!Number.isSafeInteger(g)||g<=0)throw new RangeError(`maxTopologyCharacters must be a positive safe integer; received ${g}`);let h=new q(e),{fileGraph:b,reverseFileGraph:S,workspaces:y,runtimeBoundaries:x}=_B(e,h),v=new Map((x?.observations??[]).map(P=>[P.id,P])),C=new Set((x?.observations??[]).map(P=>`${P.source.file}\0${P.source.startLine}`)),E=new Set,R=new Map,w=new Map,I=new Map,A=new Map,k=[],T=new Map,L=new Map,F=[],N=0,re=0,ge=0,Me=0,ne=0,U=0,je=new Set,at=new Map,Ot=new Map,St=P=>{let j=Ot.get(P);if(j)return j;let V=br(e,P,{excludeIndexedTargets:!1});return Ot.set(P,V),V},ct=(P,j,V,Se,$=!1)=>{let O=w.get(P);if(O)return O.depth=Math.min(O.depth,j),O.primary||=Se,O.promoteBoundaryImports||=$,O.origins.add(V),O;let G={file:P,depth:j,primary:Se,promoteBoundaryImports:$,origins:new Set([V]),processed:!1};return w.set(P,G),G},Te=(P,j,V,Se,$="none",O=!1)=>{let G=I.get(P.symbol);if(G)return G.depth=Math.min(G.depth,j),G.origins.add(V),Se&&G.anchorQueries.add(Se),G.referenceScope=NB(G.referenceScope,$),ct(P.relativePath,j,V,!0,O),G;let Z={definition:P,depth:j,origins:new Set([V]),anchorQueries:new Set(Se?[Se]:[]),referenceScope:$,processed:!1};return I.set(P.symbol,Z),ct(P.relativePath,j,V,!0,O),Z},D=(P,j,V,Se,$=!1,O=!0)=>{let G=xn(P),Z=A.get(G);if(Z)return Z.depth=Math.min(Z.depth,j),Z.origins.add(V),Se&&Z.anchorQueries.add(Se),Z.reverseCallExpansion||=$,Z.traversalEligible||=O,ct(P.file,j,V,Z.traversalEligible,!0),Z;let H={...P,depth:j,origins:new Set([V]),anchorQueries:new Set(Se?[Se]:[]),reverseCallExpansion:$,traversalEligible:O};return A.set(G,H),ct(P.file,j,V,O,!0),H},ie=(P,j,V)=>{ct(P.source.file,j,V,!0,!0),P.owner.file!==P.source.file&&ct(P.owner.file,j,`${V}:owner`,!0,!0);let Se=z(e,P.owner.file),$=P.owner.symbol?Rr(e,h,P.owner.symbol).matches.find(Z=>Z.relativePath===P.owner.file):null,O=($&&!Ce($.symbol)?$:null)??We(Se,P.source.startLine);if(O&&!Ce(O.symbol))return Te(O,j,V,void 0,"none",!0),O.symbol;P.owner.name&&D({file:P.owner.file,name:P.owner.name,startLine:P.owner.startLine,endLine:P.owner.endLine},j,`${V}:source-owner`,void 0,!0);let G=h.definitionsForFile(P.source.file).filter(Z=>!!Z.leaf&&kn(e,P.source.file,Z.leaf).some(H=>H>=P.source.startLine&&H<=P.source.endLine));if(G.length===1){let Z=G[0];Te(Z,j,`${V}:handler-identifier`,void 0,"none",!0),Ft(T,{kind:"runtime-boundary",evidence:"runtime-boundary:handler-identifier",fromFile:P.source.file,fromSymbol:null,toFile:Z.relativePath,toSymbol:Z.symbol,fromBoundaryParticipant:Xi(P),line:P.source.startLine,strength:"derived"})}return null};for(let P of r){let j=bB(e,h,P,C),V=j.filter(G=>RB(G,p)),Se=!t.fullLiteralTraversal&&(j.length>_O||V.length>OO),$=Se?[]:j,O=new Set((Se?[]:t.fullLiteralTraversal?V:[...V].sort(SB).slice(0,BO)).map(_C));Se&&(re+=1,ge+=j.length);for(let G of $){let Z=O.has(_C(G)),H=Z&&!G.ownerSymbol&&G.ownerStartLine!==null&&G.ownerEndLine!==null;if(ct(G.relativePath,0,`${Z?"literal-anchor":"literal-match"}:${P}`,H,H),H&&D({file:G.relativePath,name:G.ownerShortName??`${G.relativePath}:${G.ownerStartLine+1}`,startLine:G.ownerStartLine,endLine:G.ownerEndLine},0,`literal-source-owner:${P}`,P,!0),Z&&G.ownerSymbol){let oe=Rr(e,h,G.ownerSymbol).matches[0];oe&&!Ce(oe.symbol)&&Te(oe,0,"literal-owner",P,"all",!0)}k.push({query:P,file:G.relativePath,line:G.line,ownerSymbol:G.ownerSymbol,ownerShortName:G.ownerShortName,ownerStartLine:G.ownerStartLine,ownerEndLine:G.ownerEndLine,sourceLine:G.sourceLine.trim(),matchKind:G.matchKind,traversalSeed:Z})}F.push({kind:"literal",query:P,status:j.length>0?"matched":"missing",matchedRegionIds:[],matchingLines:j.length,seedMatchingLines:Se?0:O.size,matchOnlyLines:j.length-O.size,eligibleSeedMatchingLines:V.length,materializedMatchingLines:$.length,withheldMatchingLines:Se?j.length:0,literalTraversal:Se?"withheld-broad":"materialized",representativeMatches:Se?EB(P,j):void 0,narrowingCommands:Se?wB(P,j):void 0,exhaustiveTraversalCommand:Se||O.size<V.length?`scip-query system-map --search ${De(P)} --full-literal-traversal`:void 0,seedRegionIds:[],matchOnlyRegionIds:[]})}for(let P of i){let j=Rr(e,h,P);N+=j.omitted;let V=vB(e,P),Se=j.matches.filter(H=>!Ce(H.symbol)),$=V!==null&&Se.length===0;$&&D(V,0,"source-construct-anchor",P,!0);let O=$?Se:j.matches;for(let H of O)Te(H,0,"symbol-anchor",P,"all",!0);let G=$?CB(V):null,Z=$?1:j.total;F.push({kind:"symbol",query:P,status:Z===0?"missing":Z===1?"matched":"ambiguous",matchedRegionIds:[],symbolCandidates:[...G?[G]:[],...O.map(TB)],totalSymbolCandidates:Z,omittedSymbolCandidates:j.omitted})}for(let P=0;P<f;P+=1){if(a.has("call")){let $=[...A.values()].filter(O=>O.traversalEligible&&O.reverseCallExpansion&&O.depth<=P&&!je.has(xn(O)));for(let O of $){je.add(xn(O));let G=Y(e,O.file);if((G?.callables??[]).filter(oe=>oe.name===O.name&&oe.startLine<=O.endLine&&oe.endLine>=O.startLine).length===1){let oe=(G?.callSites??[]).filter(he=>he.calleeLeaf===O.name&&!he.memberAccess);for(let he of oe){let Ie=P+1,me=We(z(e,O.file),he.line),Ee=null,Je=null;if(me&&!Ce(me.symbol)){if(me.relativePath===O.file&&me.startLine<=O.endLine&&me.endLine>=O.startLine)continue;Te(me,Ie,"reverse-local-call-owner",void 0,"forward-regions",!0),Ee=me.symbol}else{let B=dm(e,O.file,he.line);B&&xn(B)!==xn(O)&&(Je=D(B,Ie,"reverse-local-call-source-owner",void 0,!0))}!Ee&&!Je||Ft(T,{kind:"call",evidence:"ast-callsite",fromFile:O.file,fromSymbol:Ee,toFile:O.file,toSymbol:null,fromSourceConstruct:Je?Lt(Je):void 0,toSourceConstruct:Lt(O),line:he.line,strength:"derived"})}}let H=new Set([...S.get(O.file)??[],...at.get(xn(O))??[],...IS(e,O.file).flatMap(oe=>[...S.get(oe)??[]])]);for(let oe of H){if(!p(oe))continue;let Ie=St(oe).targets.filter(me=>me.targetFile===O.file&&me.targetStartLine<=O.endLine&&me.targetEndLine>=O.startLine);for(let me of Ie){let Ee=P+1,Je=We(z(e,oe),me.line),B=null,ve=null;if(Je&&!Ce(Je.symbol))Te(Je,Ee,"reverse-member-call-owner",void 0,"cross-workspace-or-forward",!0),B=Je.symbol;else{let J=dm(e,oe,me.line);J&&(ve=D(J,Ee,"reverse-member-call-source-owner",void 0,!0))}!B&&!ve||Ft(T,{kind:"call",evidence:"ast-service-member-callsite",fromFile:oe,fromSymbol:B,toFile:O.file,toSymbol:null,fromSourceConstruct:ve?Lt(ve):void 0,toSourceConstruct:Lt(O),line:me.line,strength:me.strength==="exact"?"exact":"derived"})}}}}let j=[...I.values()].filter($=>!$.processed&&$.depth<=P),V=a.has("call")?h.calleeMap(j.map($=>$.definition),{additive:!1,semantic:!1}):new Map;for(let $ of j){$.processed=!0;let O=$.definition;if($.referenceScope!=="none"&&(a.has("call")||a.has("reference")||a.has("contract-symbol"))){let G=PB(e,h,O).filter(H=>p(H.file)&&FB($,H.file,w,y)),Z=new Set(G.flatMap(H=>{if(!(a.has("call")&&Y(e,H.file)?.callSites.some(Ie=>Ie.line===H.line&&kC(e,H.file,Ie,O))===!0)||!H.enclosingSymbol)return[];let he=Rr(e,h,H.enclosingSymbol).matches[0];return he&&!Ce(he.symbol)?[{owner:he,site:H}]:[]}).sort((H,oe)=>{let he=Nt(O.relativePath,y).relativeDir,Ie=Nt(H.owner.relativePath,y).relativeDir===he,me=Nt(oe.owner.relativePath,y).relativeDir===he,Ee=AC(e,H.owner),Je=AC(e,oe.owner),B=H.owner.endLine-H.owner.startLine,ve=oe.owner.endLine-oe.owner.startLine;return Number(me)-Number(Ie)||Je-Ee||B-ve||H.owner.symbol.localeCompare(oe.owner.symbol)}).filter((H,oe,he)=>he.findIndex(Ie=>Ie.owner.symbol===H.owner.symbol)===oe).reduce((H,oe)=>{if(H.length>=UO)return H;let he=Nt(oe.owner.relativePath,y).relativeDir;return H.some(Ie=>Ie.workspace===he)||H.push({symbol:oe.owner.symbol,workspace:he}),H},[]).map(H=>H.symbol));for(let H of G){let oe=P+1;ct(H.file,oe,`reference:${M(O.symbol)}`,!0);let he=a.has("call")&&Y(e,H.file)?.callSites.some(Ee=>Ee.line===H.line&&kC(e,H.file,Ee,O))===!0,Ie=null,me=null;if(H.enclosingSymbol){let Ee=Rr(e,h,H.enclosingSymbol).matches[0];Ee&&!Ce(Ee.symbol)&&(Te(Ee,oe,"reference-owner",void 0,he&&Z.has(Ee.symbol)?$.referenceScope:"none"),Ie=Ee.symbol)}if(!Ie&&H.line!==null){let Ee=dm(e,H.file,H.line);Ee&&(me=D(Ee,oe,"reference-source-owner",void 0,he))}a.has("reference")&&Ft(T,{kind:"reference",evidence:"indexed-or-source-reference",fromFile:H.file,fromSymbol:Ie,toFile:O.relativePath,toSymbol:O.symbol,fromSourceConstruct:me?Lt(me):void 0,line:H.line,strength:"mixed"}),he&&Ft(T,{kind:"call",evidence:"ast-callsite",fromFile:H.file,fromSymbol:Ie,toFile:O.relativePath,toSymbol:O.symbol,fromSourceConstruct:me?Lt(me):void 0,line:H.line,strength:"derived"}),a.has("contract-symbol")&&Nt(H.file,y).relativeDir!==Nt(O.relativePath,y).relativeDir&&Ft(T,{kind:"contract-symbol",evidence:"compiler-cross-workspace-symbol",fromFile:H.file,fromSymbol:Ie,toFile:O.relativePath,toSymbol:O.symbol,fromSourceConstruct:me?Lt(me):void 0,line:H.line,strength:"exact"})}}for(let G of V.get(O.symbolId)??[]){let Z=Rr(e,h,G.symbol).matches.find(oe=>oe.relativePath===G.file);if(!Z||!p(Z.relativePath))continue;if(!(Z.relativePath===O.relativePath||(b.get(O.relativePath)??new Set).has(Z.relativePath))){Me+=1;continue}Te(Z,P+1,`call:${M(O.symbol)}`,void 0,"none",!0),Ft(T,{kind:"call",evidence:G.source,fromFile:O.relativePath,fromSymbol:O.symbol,toFile:Z.relativePath,toSymbol:Z.symbol,line:null,strength:dB(G.source)})}}let Se=[...w.values()].filter($=>!$.processed&&$.primary&&$.depth<=P);for(let $ of Se){$.processed=!0;let O=[...A.values()].filter(B=>B.traversalEligible&&B.file===$.file&&B.depth<=P),G=[...I.values()].filter(B=>B.definition.relativePath===$.file&&B.depth<=P).map(B=>{let ve=Ai(e,$.file,B.definition.startLine);return{startLine:ve?.startLine??B.definition.startLine,endLine:ve?.endLine??B.definition.endLine}}),Z=B=>[...I.values()].filter(ve=>ve.definition.relativePath===$.file&&ve.definition.startLine<=B&&ve.definition.endLine>=B).sort((ve,J)=>ve.definition.endLine-ve.definition.startLine-(J.definition.endLine-J.definition.startLine)||ve.definition.startLine-J.definition.startLine)[0],H=[...v.values()].filter(B=>B.source.file===$.file&&R.has(B.id)),oe=[...O.map(B=>({startLine:B.startLine,endLine:B.endLine})),...H.map(B=>({...Bc(e,B)}))],he=[...G,...oe],Ie=(Y(e,$.file)?.callSites??[]).filter(B=>he.some(ve=>B.line>=ve.startLine&&B.line<=ve.endLine)),me=new Set;if(a.has("call"))for(let B of he){let ve=jn(e,$.file,B.startLine,B.endLine);for(let J of ve.targets){if(!p(J.definition.relativePath))continue;let Xe=Z(J.sourceLine),en=O.find($t=>$t.startLine<=J.sourceLine&&$t.endLine>=J.sourceLine),Pt=H.find($t=>{let ht=Bc(e,$t);return ht.startLine<=J.sourceLine&&ht.endLine>=J.sourceLine});Te(J.definition,P+1,`scip-occurrence-call:${$.file}:${J.sourceLine+1}`,void 0,"none",!0),Ft(T,{kind:"call",evidence:"scip-occurrence-callsite",fromFile:$.file,fromSymbol:Xe?.definition.symbol??null,toFile:J.definition.relativePath,toSymbol:J.definition.symbol,fromBoundaryParticipant:Pt?Xi(Pt):void 0,fromSourceConstruct:en?Lt(en):void 0,line:J.sourceLine,strength:"exact"}),me.add(`${J.sourceLine}\0${J.calleeLeaf}`)}}if(a.has("reference"))for(let B of he){let ve=kS(e,$.file,B.startLine,B.endLine);for(let J of ve.targets){if(!p(J.definition.relativePath)||me.has(`${J.sourceLine}\0${J.calleeLeaf}`))continue;let Xe=Z(J.sourceLine);if(Xe?.definition.symbol===J.definition.symbol)continue;let en=O.find($t=>$t.startLine<=J.sourceLine&&$t.endLine>=J.sourceLine),Pt=H.find($t=>{let ht=Bc(e,$t);return ht.startLine<=J.sourceLine&&ht.endLine>=J.sourceLine});Te(J.definition,P+1,`scip-occurrence-reference:${$.file}:${J.sourceLine+1}`,void 0,"none",!0),Ft(T,{kind:"reference",evidence:"scip-occurrence-reference",fromFile:$.file,fromSymbol:Xe?.definition.symbol??null,toFile:J.definition.relativePath,toSymbol:J.definition.symbol,fromBoundaryParticipant:Pt?Xi(Pt):void 0,fromSourceConstruct:en?Lt(en):void 0,line:J.sourceLine,strength:"exact"})}}let Ee=a.has("call")?br(e,$.file,{ranges:he,excludeIndexedTargets:!1}):{targets:[],unresolvedCallsites:0};U+=Ee.unresolvedCallsites;let Je=Ee.targets.filter(B=>!me.has(`${B.line}\0${B.calleeLeaf}`));ne+=Je.filter(B=>B.strength!=="exact"&&(B.resolution!=="imported-service-object-member"||(B.resolutionAlternativeCount??0)>1)).length;for(let B of Je){let ve=(B.resolutionAlternativeCount??1)===1,J=B.targetSymbol?z(e,B.targetFile).find(ht=>ht.symbol===B.targetSymbol):void 0,Xe=J?null:D({file:B.targetFile,name:B.calleeLeaf,startLine:B.targetStartLine,endLine:B.targetEndLine},P+1,`member-call:${$.file}`,void 0,B.resolution==="imported-service-object-member"&&ve,ve);if(Xe&&B.serviceFile){let ht=xn(Xe),mo=at.get(ht)??new Set;for(let Nw of S.get(B.serviceFile)??[])mo.add(Nw);at.set(ht,mo)}J&&Te(J,P+1,`member-call:${$.file}`,void 0,"none",!0);let en=O.find(ht=>ht.startLine<=B.line&&ht.endLine>=B.line),Pt=Z(B.line),$t=H.find(ht=>{let mo=Bc(e,ht);return mo.startLine<=B.line&&mo.endLine>=B.line});Ft(T,{kind:"call",evidence:B.resolution==="constructed-member-receiver"?"ast-constructed-member-callsite":B.resolution==="factory-callback-member"?"ast-factory-callback-callsite":B.resolution==="imported-service-object-member"?"ast-service-member-callsite":"ast-member-import-candidate",fromFile:$.file,fromSymbol:Pt?.definition.symbol??null,toFile:B.targetFile,toSymbol:J?.symbol??null,fromBoundaryParticipant:$t?Xi($t):void 0,fromSourceConstruct:en?Lt(en):void 0,toSourceConstruct:Xe?Lt(Xe):void 0,line:B.line,strength:B.resolution==="imported-service-object-member"?(B.resolutionAlternativeCount??0)===1?"derived":"candidate":B.strength??"candidate"})}for(let B of a.has("import")||a.has("call")?DB(e,$.file):[]){if(!B.fromFile){if(a.has("import")){let J=L.get(B.shortName)??{name:B.shortName,fromFiles:new Set};J.fromFiles.add($.file),L.set(B.shortName,J)}continue}if(!p(B.fromFile))continue;if(a.has("import")&&(ct(B.fromFile,P+1,`import:${$.file}`,!1),Ft(T,{kind:"import",evidence:"indexed-or-source-import",fromFile:$.file,fromSymbol:null,toFile:B.fromFile,toSymbol:B.symbol,line:null,strength:"mixed"})),a.has("call")&&Ie.length>0){let J=(B.source==="compiler"?Rr(e,h,B.symbol).matches:sr(e,B.fromFile,B.importedName)).filter(Xe=>!Ce(Xe.symbol));for(let Xe of J){let en=Ie.filter(Pt=>Pt.calleeLeaf===B.localName).map(Pt=>Pt.line);if(en.length!==0){Te(Xe,P+1,`source-call:${$.file}`,void 0,"none",!0);for(let Pt of en)Ft(T,{kind:"call",evidence:"ast-callsite",fromFile:$.file,fromSymbol:null,toFile:Xe.relativePath,toSymbol:Xe.symbol,line:Pt,strength:"derived"})}}}if(!$.promoteBoundaryImports||!kB($.file,B.fromFile,y))continue;let ve=Rr(e,h,B.symbol);for(let J of ve.matches)if(AB(J.relativePath,B.fromFile,y)&&!Ce(J.symbol)){let Xe=Nt($.file,y).relativeDir!==Nt(J.relativePath,y).relativeDir;Te(J,P+1,`boundary-import:${$.file}`,void 0,Xe?"cross-workspace-or-forward":"forward-regions")}}}for(let $ of a.has("runtime-boundary")?x?.links??[]:[]){if($.strength==="candidate"||c==="exact"&&$.strength!=="exact"||E.has($.id))continue;let O=v.get($.from),G=v.get($.to);if(!O||!G||!p(O.source.file)||!p(G.source.file))continue;let Z=$C(O,P,R,I,A),H=$C(G,P,R,I,A);if(Z===null&&H===null)continue;let oe=P+1,he=ie(O,Z??oe,`runtime-boundary:${$.joinRule}`),Ie=ie(G,H??oe,`runtime-boundary:${$.joinRule}`),me=he?null:BC(A,O),Ee=Ie?null:BC(A,G);R.set(O.id,Z??oe),R.set(G.id,H??oe),Ft(T,{kind:"runtime-boundary",evidence:`runtime-boundary:${$.joinRule}`,fromFile:O.source.file,fromSymbol:he,toFile:G.source.file,toSymbol:Ie,fromBoundaryParticipant:Xi(O),toBoundaryParticipant:Xi(G),fromSourceConstruct:me?Lt(me):void 0,toSourceConstruct:Ee?Lt(Ee):void 0,runtimeBoundaryKey:$.matchedKeyParts.map(Je=>`${Je.name}=${Je.value}`).join(" "),line:O.source.startLine,strength:$.strength}),E.add($.id)}}let ee=new Map;for(let P of w.keys())ee.set(P,fs(P,y));let Re=[...T.values()].filter(P=>ee.has(P.fromFile)&&ee.has(P.toFile)).map(P=>({...P,fromRegionId:ee.get(P.fromFile).id,toRegionId:ee.get(P.toFile).id})).sort(KC),vt=GB(Re),Tr=new Set(t.expand??[]),Jn=jB(w,I,k,Re,vt,ee,Tr),pi=new Set([...w.values()].filter(P=>[...P.origins].some(j=>j.startsWith("literal-anchor:")||j==="literal-owner"||j==="symbol-anchor")).map(P=>ee.get(P.file).id)),Qp=gB(Jn),Ew=new Set(Jn.map(P=>P.id)),Iw=[...Tr].filter(P=>!Ew.has(P)).sort();for(let P of F)if(P.matchedRegionIds=KB(P,k,I,ee),P.kind==="literal"){let j=k.filter(V=>V.query===P.query);P.seedRegionIds=xe(j.filter(V=>V.traversalSeed).map(V=>ee.get(V.file).id)),P.matchOnlyRegionIds=xe(j.filter(V=>!V.traversalSeed).map(V=>ee.get(V.file).id))}let Zp=[...I.values()].filter(P=>!P.processed).length,ef=[...w.values()].filter(P=>P.primary&&!P.processed).length,tf=[...w.values()].filter(P=>!P.primary&&!P.processed).length,nf=[...I.values()].filter(P=>P.processed),Hs=(x?.frontiers??[]).flatMap(P=>{let j=v.get(P.observationId);return!j&&P.source&&P.action&&P.strength?!a.has("runtime-boundary")||!p(P.source.file)||c==="exact"||!w.has(P.source.file)?[]:[{observationId:P.observationId,action:P.action,strength:P.strength,file:P.source.file,line:P.source.startLine,ownerShortName:P.ownerShortName??null,address:P.address??P.missingKeyParts.join(", "),reason:P.reason}]:!a.has("runtime-boundary")||!j||!p(j.source.file)||c==="exact"&&j.strength!=="exact"||!w.has(j.source.file)?[]:[{observationId:j.id,action:j.action,strength:j.strength,file:j.source.file,line:j.source.startLine,ownerShortName:j.owner.name,address:zC(j),reason:P.reason,protocol:j.protocol,role:j.role,modality:j.modality,resolution:j.resolution,sourceScope:j.sourceScope,keyParts:j.keyParts.map(V=>({name:V.name,value:V.value,evidence:V.evidence}))}]}).sort((P,j)=>P.file.localeCompare(j.file)||P.line-j.line),Dl=(x?.links??[]).filter(P=>{if(!a.has("runtime-boundary")||c==="exact"&&P.strength!=="exact")return!1;let j=v.get(P.from),V=v.get(P.to);return!!(j&&V&&p(j.source.file)&&p(V.source.file)&&(w.has(j.source.file)||w.has(V.source.file)))}),ww=Dl.filter(P=>P.strength==="exact").length,Lw=Dl.filter(P=>P.strength==="derived").length,Pw=Dl.filter(P=>P.strength==="candidate").length,Dw=x?.links.filter(P=>P.strength==="exact").length??0,Mw=x?.links.filter(P=>P.strength==="derived").length??0,Tw=x?.links.filter(P=>P.strength==="candidate").length??0,Ml=zB(L,ee),Tl=N===0?"accounted":"incomplete",rf=[...re>0?[`${re} broad literal anchor(s) withheld ${ge} 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 (${l.join(", ")}) remain visible as match-only evidence and do not seed traversal.`,x?"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 ${f}; nonzero frontier counts identify evidence that was discovered but not traversed.`,"Region labels are structural path groupings, not inferred runtime or architectural boundaries."],Bt=iB({db:e,anchors:F,regions:Jn,symbolStates:I,sourceConstructStates:A,literalHits:k,relations:Re,externalBoundaries:Ml,boundaryFrontiers:Hs,regionForFile:ee,closureStatus:Tl,omittedSymbolCandidates:N,maxDepth:f,requestedRelationKinds:o,evidenceFloor:c,includedSourceScopes:l,blindSpots:rf,topologyFrontiers:t.topologyFrontiers??[],routeIds:t.routeIds??[],expandedRegionIds:[...Tr],maxTopologyCharacters:g,fullLiteralTraversal:t.fullLiteralTraversal??!1});if(n==="topology")return Bt;let of=(t.behaviorFocusLocations?.length??0)>0?new Set([...Bt.anchors.flatMap(P=>P.nodeIds),...Bt.paths.flatMap(P=>P.nodeIds)]).size:void 0,Us=$S(e,Bt,{focusLocations:t.behaviorFocusLocations,...of?{maxSteps:of}:{}});yv(e,Bt,Us);let kw=KO(e,Bt,Us,t.behaviorFocusLocations??[]);Bt.corridor=fC(Bt,{focusLocations:kw});let sf=hv(e,Bt,Us,{sourceAllowed:p,selectionTerms:t.selectionTerms}),af=lB(Bt),Aw=pB(r,i,f,o,c,l,t.fullLiteralTraversal??!1,g,Jn,vt,pi,Tr,af),Fw=mB(r,i,f,Jn.filter(P=>af.has(P.id)),pi,o,c,l,t.fullLiteralTraversal??!1,g);return{anchors:F,regions:Jn,regionRelations:vt,externalBoundaries:Ml,boundaryFrontiers:Hs,unmatchedExpansions:Iw,expansion:Fw,drilldown:Qp,presentation:Aw,topology:Bt,behavior:Us,nextAnchors:sf,closure:{status:Tl,emitted:{regions:Jn.length,relations:Re.length,runtimeLinks:E.size},withheld:{symbols:Zp,files:ef+tf,regions:Bt.nodes.filter(P=>P.kind==="structural-region"&&P.disposition==="folded").length,drillAnchors:(Qp?.omittedAnchors??0)+sf.omittedAnchors,literalMatches:ge},ambiguous:{anchors:F.filter(P=>P.status==="ambiguous").length,omittedSymbolCandidates:N},external:Ml.length,unresolved:Hs.length,explanation:Tl==="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:F.length,requestedRelationKinds:o,evidenceFloor:c,includedSourceScopes:l,matchedAnchorCount:F.filter(P=>P.status!=="missing").length,literalSearchesComplete:!0,broadLiteralAnchors:re,withheldLiteralMatches:ge,symbolCandidateSetsComplete:N===0,omittedSymbolCandidates:N,maxTraversalDepth:f,frontierSymbols:Zp,frontierFiles:ef,supportFilesNotTraversed:tf,filteredUnverifiedCallEdges:Me,memberCallCandidateEdges:ne,unresolvedMemberCallsites:U,runtimeBoundaryEvidenceAvailable:x!==null,runtimeBoundaryObservations:x?.observations.length??0,runtimeBoundaryExactLinks:ww,runtimeBoundaryDerivedLinks:Lw,runtimeBoundaryCandidateLinks:Pw,repositoryRuntimeBoundaryExactLinks:Dw,repositoryRuntimeBoundaryDerivedLinks:Mw,repositoryRuntimeBoundaryCandidateLinks:Tw,runtimeBoundaryTraversedLinks:E.size,runtimeBoundaryFrontiers:Hs.length,referenceExpansionEligibleSymbols:nf.filter(P=>P.referenceScope!=="none").length,referenceExpansionSkippedSymbols:nf.filter(P=>P.referenceScope==="none").length,dynamicDispatchRepresented:x?.links.some(P=>P.joinRule==="carrier.discriminator"&&E.has(P.id))??!1,runtimeGeneratedLinksRepresented:x!==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:rf}}}function KO(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=>qO.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=Ea(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 WO(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 xn(e){return`${e.file}\0${e.startLine}\0${e.endLine}\0${e.name}`}function Lt(e){return{file:e.file,name:e.name,startLine:e.startLine,endLine:e.endLine}}function kC(e,t,n,r){if(n.calleeLeaf===r.leaf)return!0;let i=vi(e,t,n.calleeLeaf);return i!==null&&i.importedName===r.leaf&&i.sourcePath!==null&&Ke(i.sourcePath,r.relativePath)}function $c(e,t){let n=Zn(Y(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=GC(e,t.file,t.startLine);return r&&r.endLine>=t.endLine?{file:t.file,name:r.name,startLine:r.startLine,endLine:r.endLine}:Lt(t)}function Qi(e){return _t("source-construct",e.file,String(e.startLine),String(e.endLine),e.name)}function jc(e,t){let n=Ui(e,t.symbol,t.relativePath),r=new Set(["package-surface-file","transitive-package-surface"]),i=n.filter(s=>!r.has(s)||Tt(e,t)),o=i.some(s=>!r.has(s));return{evidence:i,priority:o||Jb(e,t.symbol,t.relativePath)?2:1}}function AC(e,t){let n=jc(e,t);return n.evidence.length>0?n.priority:0}function VO(e,t){let n=z(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=jc(e,i);if(o.evidence.length>0)return o}for(let i of YO(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=jc(e,s);if(a.evidence.length>0)return a}return{evidence:[],priority:0}}return{evidence:[],priority:0}}function YO(e,t,n){let r=te(e,t)?.rootNode;if(!r||r.startPosition.row>n||r.endPosition.row<n)return[];let i=[],o=fm(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 JO(e){return[...new Map([...e.sourceConstructStates.values()].map(t=>$c(e.db,t)).map(t=>[xn(t),t])).values()].sort((t,n)=>t.file.localeCompare(n.file)||t.startLine-n.startLine||t.endLine-n.endLine)}function XO(e,t){return e.anchors.map((n,r)=>{let i=_t("anchor",String(r),n.kind,n.query),o=[...e.symbolStates.values()].filter(u=>u.anchorQueries.has(n.query)).flatMap(u=>{if(!Ce(u.definition.symbol))return[Er(u.definition.symbol)];let d=t.filter(m=>m.file===u.definition.relativePath).map(m=>Qi(m));return d.length>0?d:[Er(u.definition.symbol)]}),s=[...e.sourceConstructStates.values()].filter(u=>u.anchorQueries.has(n.query)).map(u=>Qi($c(e.db,u))),a=e.literalHits.filter(u=>u.query===n.query&&u.traversalSeed===!0&&u.ownerSymbol&&e.symbolStates.has(u.ownerSymbol)).map(u=>Er(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=>Qi($c(e.db,WO(u)))),l=xe(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 QO(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 ZO(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:xe(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=Er(s.definition.symbol),l=jc(e.db,s.definition);i.push({id:c,kind:"symbol",label:M(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:xe(n.get(c)??[]),attributes:{regionId:a,depth:s.depth,leaf:s.definition.leaf??M(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=Qi(s),u=r.find(m=>m.file===s.file&&m.line>=s.startLine&&m.line<=s.endLine)?.ownerName??s.name,d=VO(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:xe(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:gm(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 eB(e,t,n,r,i,o,s,a,c,l=!1){let u=r?Er(r):null;if(u&&t.has(u)&&!Ce(r))return u;let d=i?gm(i.observationId):null;if(l&&d&&t.has(d))return d;let m=o?Qi($c(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?Qi(p):u&&t.has(u)?u:s}function tB(e,t,n){let r=new Set(t.map(l=>l.id)),i=Ve(n,l=>l.file),o=(l,u,d,m,p,f,g=!1)=>eB(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=Er(l.definition.symbol);s.push({id:_t("edge","structural-membership",u,d),kind:"structural-membership",fromNodeId:u,toNodeId:d,directed:!0,disposition:"folded",semantics:wc("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=Ve(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=gm(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:_t("edge","boundary-observation",g,f),kind:"boundary-observation",fromNodeId:g,toNodeId:f,directed:!0,disposition:"folded",semantics:wc("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:_t("edge",u.kind,d,m),kind:u.kind,fromNodeId:d,toNodeId:m,directed:!0,disposition:"folded",semantics:$v(u),evidence:uB(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 nB(e,t,n){for(let i of e.externalBoundaries){let o=_t("external",i.kind,i.name),s=xe(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:_t("edge",i.kind,a,o),kind:i.kind,fromNodeId:a,toNodeId:o,directed:!0,disposition:"folded",semantics:wc("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=_t("unsupported","runtime-boundary",i.observationId,String(o)),c=_t("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:_t("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 rB(e,t){let n=t.topologyFrontiers.some(f=>f==="frontier:program-facts"),r=LC(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=>oB(f,g))),s=t.boundaryFrontiers.filter(f=>i.some(g=>sB(f,g))),a=Yv(t.db,o,i),c=Xv(t.db,i),l=lC(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:aB(i,u,d),p=Oc({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=cB(t,f.id)));return p}function iB(e){let t=JO(e),n=XO(e,t),r=ZO(e,t,QO(n)),i=tB(e,r,t),o=nB(e,r,i);return rB(Oc({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 oB(e,t){if(e.fromSymbol&&t.id===Er(e.fromSymbol)||e.toSymbol&&t.id===Er(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 sB(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 aB(e,t,n){let r=xe(t.filter(o=>o.disposition==="folded").map(o=>o.id)),i=xe(n.filter(o=>o.disposition==="folded").map(o=>o.id));return r.length===0&&i.length===0?null:{id:_t("frontier","program-facts"),kind:"program-facts",direction:"outgoing",fromNodeIds:xe(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 cB(e,t){return`scip-query system-map ${[...e.anchors.flatMap(r=>r.kind==="literal"?[`--search ${De(r.query)}`]:[`--symbol ${De(r.query)}`]),`--depth ${e.maxDepth}`,...e.requestedRelationKinds.map(r=>`--relation ${De(r)}`),`--evidence-floor ${De(e.evidenceFloor)}`,...e.includedSourceScopes.map(r=>`--source-scope ${De(r)}`),...e.fullLiteralTraversal?["--full-literal-traversal"]:[],`--topology-characters ${e.maxTopologyCharacters}`,...e.expandedRegionIds.map(r=>`--expand ${De(r)}`),...e.topologyFrontiers.map(r=>`--frontier ${De(r)}`),...e.routeIds.map(r=>`--route ${De(r)}`),`--frontier ${De(t)}`].join(" ")}`}function lB(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 uB(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 _t(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function Er(e){return _t("symbol",e)}function dB(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function mB(e,t,n,r,i,o,s,a,c,l){let u=[...r].sort((g,h)=>qC(g,h,i)),m=u.slice(0,DC).map(g=>g.id),p=u.slice(DC).map(g=>g.id),f=[...e.map(g=>`--search ${De(g)}`),...t.map(g=>`--symbol ${De(g)}`),`--depth ${n}`,...o.map(g=>`--relation ${De(g)}`),`--evidence-floor ${De(s)}`,...a.map(g=>`--source-scope ${De(g)}`),...c?["--full-literal-traversal"]:[],`--topology-characters ${l}`,...m.map(g=>`--expand ${De(g)}`)];return{command:m.length===0?null:`scip-query system-map ${f.join(" ")}`,regionCount:m.length,regionIds:m,candidateRegionCount:r.length,omittedRegionIds:p}}function pB(e,t,n,r,i,o,s,a,c,l,u,d,m){let p=[...c].sort((I,A)=>qC(I,A,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 A=FC(I);!d.has(I.id)&&h.size>0&&b+A>g||(h.add(I.id),b+=A)}let S=l.filter(I=>h.has(I.fromRegionId)&&h.has(I.toRegionId)).sort(fB),y=[];for(let I of S){let A=NC(I);y.length>0&&b+A>a||(y.push(Hc(I)),b+=A)}let x=c.filter(I=>!h.has(I.id)).map(I=>I.id).sort(),v=new Set(y),C=l.filter(I=>!v.has(Hc(I))).length,E=c.reduce((I,A)=>I+FC(A),0)+l.reduce((I,A)=>I+NC(A),0),R=p.every(I=>h.has(I.id))&&y.length===S.length,w=[...e.map(I=>`--search ${De(I)}`),...t.map(I=>`--symbol ${De(I)}`),`--depth ${n}`,...r.map(I=>`--relation ${De(I)}`),`--evidence-floor ${De(i)}`,...o.map(I=>`--source-scope ${De(I)}`),...s?["--full-literal-traversal"]:[],`--topology-characters ${Math.max(a,E)}`];return{maxCharacters:a,estimatedCharacters:b,totalEstimatedCharacters:E,regionIds:[...h],omittedRegionIds:x,relationKeys:y,omittedRelations:C,complete:R,expansionCommand:R?null:`scip-query system-map ${w.join(" ")}`}}function FC(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 NC(e){return 70+e.fromRegionId.length+e.toRegionId.length+e.kinds.join(",").length+e.evidence.join(",").length}function fB(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||Hc(e).localeCompare(Hc(t))}function Hc(e){return`${e.fromRegionId}\0${e.toRegionId}`}function qC(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 gB(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=Ve(i.symbols,c=>c.file),s=Ve(i.literalHits,c=>c.file),a=[...i.files].sort((c,l)=>yB(c,l,o,s));for(let c of a){let l=(o.get(c.file)??[]).sort(Ov)[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(WC)[0];u&&t.push({kind:"literal",regionId:i.id,file:u.file,line:u.line,endLine:null,label:u.ownerShortName??u.query})}}let r=hB(t,n);return{command:r.length===0?null:`scip-query inspect ${r.map(i=>`--at ${De(`${i.file}:${i.line+1}`)}`).join(" ")} --view behavior`,definitionCommand:null,candidateAnchors:t.length,selectedAnchors:r.length,omittedAnchors:t.length-r.length,anchors:r}}function hB(e,t){let n=[...Ve(e,s=>s.regionId).values()],r=[],i=new Set,o=Math.min(HO,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 yB(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=>Vi(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 De(e){return`'${e.replaceAll("'","'\\''")}'`}function bB(e,t,n,r){let i=[];for(let o of ae(e,{includeIgnored:!1})){let s=Q(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=Y(e,o)?.callables??[];for(let{line:u,sourceLine:d}of a){let m=We(c,u),p=Zn(l,u),f=m&&!Ce(m.symbol)?m:null,g=f?.startLine??p?.startLine??m?.startLine??u,h=f?.endLine??p?.endLine??m?.endLine??u,b=Do(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?M(f.symbol):p?.name??(m?M(m.symbol):null),ownerStartLine:b.startLine,ownerEndLine:b.endLine,matchKind:xB(d,n),seedPriority:S?0:y?1:2})}}return i}function SB(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 _C(e){return`${e.relativePath}\0${e.line}`}function dm(e,t,n){let i=Zn(Y(e,t)?.callables??[],n)??GC(e,t,n);if(!i)return null;let o=Do(e,t,n,i.startLine,i.endLine);return{file:t,name:i.name,startLine:o.startLine,endLine:o.endLine}}function GC(e,t,n){let r=te(e,t)?.rootNode;if(!r||r.startPosition.row>n||r.endPosition.row<n)return null;let i=fm(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&&mm(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)&&mm(a,n))return{name:c,startLine:i.startPosition.row,endLine:i.endPosition.row}}i=i.parent}let o=Ai(e,t,n);return o?{name:`source@${n+1}`,startLine:o.startLine,endLine:o.endLine}:null}function mm(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&&mm(n,t))}function fm(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?fm(n,t):e}function vB(e,t){let n=t.match(/^(.+):(\d+)(?:-(\d+))?$/u);if(!n)return null;let r=gi(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=(Y(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 CB(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 xB(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 pm(e){return K(e)==="test"?!1:!/(?:^|[/._-])(?:fixtures?|mocks?|previews?|demos?|examples?|stories)(?:[/._-]|$)/iu.test(e)}function RB(e,t){return e.matchKind!=="embedded"&&t(e.relativePath)&&(Vl(e.relativePath)!=="production"||pm(e.relativePath))}function EB(e,t){let n=[...t].sort(IB),r=[],i=new Set;for(let o of n)if(!i.has(o.relativePath)&&(r.push(o),i.add(o.relativePath),r.length>=PC))break;for(let o of n){if(r.length>=PC)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 IB(e,t){let n={"exact-value":0,boundary:1,embedded:2};return n[e.matchKind]-n[t.matchKind]||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||+!pm(e.relativePath)-+!pm(t.relativePath)||e.relativePath.localeCompare(t.relativePath)||e.line-t.line}function wB(e,t){let n=new Map;for(let r of t){let i=LB(r.relativePath);n.set(i,(n.get(i)??0)+1)}return[...n].sort(([r,i],[o,s])=>s-i||r.localeCompare(o)).slice(0,$O).map(([r])=>`scip-query search ${De(e)} --scope ${De(r)}`)}function LB(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 PB(e,t,n){let r=t.callerFileMap([n],{semantic:!1}).get(n.symbolId)??new Set,i=[];for(let o of[...r].sort()){let s=pe(e,o).filter(u=>u.importedName===n.leaf&&u.sourcePath!==null&&Ke(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=>kn(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:We(l,u)?.symbol??null})}return i}function DB(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:M(r.symbol),importedName:OC(M(r.symbol)),localName:OC(M(r.symbol)),fromFile:r.from_file,source:"compiler"})):pe(e,t).map(r=>{let i=MB(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 OC(e){return e.slice(e.lastIndexOf(":")+1).replace(/\(\)$/u,"")||e}function MB(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 Rr(e,t,n){let r=pt(e,n);if(!r.match)return{matches:[],total:0,omitted:0};let i=[r.match,...r.candidates.map(s=>pt(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 TB(e){return{symbol:e.symbol,shortName:M(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function Ft(e,t){let n=[t.kind,t.fromFile,t.fromSymbol??"",t.toFile,t.toSymbol??"",t.fromBoundaryParticipant?.observationId??"",t.toBoundaryParticipant?.observationId??"",t.fromSourceConstruct?xn(t.fromSourceConstruct):"",t.toSourceConstruct?xn(t.toSourceConstruct):"",t.runtimeBoundaryKey??"",t.line??""].join("\0");e.set(n,t)}function Xi(e){return{observationId:e.id,action:e.action,protocol:e.protocol,role:e.role,address:zC(e),file:e.source.file,line:e.source.startLine,endLine:e.source.endLine,ownerName:e.owner.name,ownerSymbol:e.owner.symbol}}function Bc(e,t){let n=Q(e,t.source.file);return xt(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine])}function BC(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 $C(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;jC(c,e)&&o.push(a.depth)}for(let a of i.values())a.depth>t||jC(a,e)&&o.push(a.depth);return o.length>0?Math.min(...o):null}function jC(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 gm(e){return _t("runtime-boundary-participant",e)}function kB(e,t,n){let r=Nt(e,n),i=Nt(t,n);return r.relativeDir!==i.relativeDir?!0:/(?:^|\/)(?:contracts?|schemas?|db\/schema)(?:\/|$)/u.test(t)}function AB(e,t,n){return fs(e,n).id===fs(t,n).id}function FB(e,t,n,r){if(e.referenceScope==="all")return!0;let i=fs(t,r).id;return[...n.values()].some(s=>s.promoteBoundaryImports&&fs(s.file,r).id===i)?!0:e.referenceScope!=="cross-workspace-or-forward"?!1:Nt(t,r).relativeDir!==Nt(e.definition.relativePath,r).relativeDir}function NB(e,t){let n={none:0,"forward-regions":1,"cross-workspace-or-forward":2,all:3};return n[e]>=n[t]?e:t}function _B(e,t){let n=TC.get(e);if(n)return n;let r=t.fileDependencyGraph(),i={fileGraph:r,reverseFileGraph:OB(r),workspaces:BB(t.sourceFiles()),runtimeBoundaries:pa(e)};return TC.set(e,i),i}function OB(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 Nt(e,t){return t.find(n=>e===n.relativeDir||e.startsWith(`${n.relativeDir}/`))??{name:"root",relativeDir:""}}function BB(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 fs(e,t){let n=Nt(e,t),i=(n.relativeDir?e.slice(n.relativeDir.length+1):e).split("/").filter(Boolean);i[0]==="src"&&i.shift();let o=$B(i);return{id:`region:${n.relativeDir||"root"}:${o}`,label:`${n.name}:${o}`,workspace:n.name,structuralPath:o}}function $B(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 jB(e,t,n,r,i,o,s){let a=Ve([...e.values()],p=>o.get(p.file).id),c=Ve([...t.values()],p=>o.get(p.definition.relativePath).id),l=Ve(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=Ve(i,p=>p.toRegionId),m=Ve(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(qB).sort(WB).slice(0,jO),v=f.filter(C=>K(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:xe([...b.map(C=>C.query),...h.flatMap(C=>[...C.anchorQueries])]),relationKinds:xe(S.map(C=>C.kind)),incomingRegionIds:xe((d.get(p)??[]).map(C=>C.fromRegionId)),outgoingRegionIds:xe((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(HB).sort(VB):[],symbols:y?h.map(UB).sort(YB):[],literalHits:y?[...b].sort(WC):[],relations:y?[...S].sort(KC):[]}}).sort((p,f)=>p.minDepth-f.minDepth||p.label.localeCompare(f.label))}function HB(e){return{file:e.file,kind:K(e.file),depth:e.depth,origins:xe([...e.origins])}}function UB(e){return{symbol:e.definition.symbol,shortName:M(e.definition.symbol),file:e.definition.relativePath,startLine:e.definition.startLine,endLine:e.definition.endLine,depth:e.depth,origins:xe([...e.origins]),anchorQueries:xe([...e.anchorQueries]),referenceExpansion:e.referenceScope!=="none",referenceScope:e.referenceScope}}function qB(e){return{shortName:M(e.definition.symbol),file:e.definition.relativePath,origins:xe([...e.origins])}}function GB(e){return[...Ve(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:xe(n.map(r=>r.kind)),relationCount:n.length,fromFiles:xe(n.map(r=>r.fromFile)),toFiles:xe(n.map(r=>r.toFile)),fromSymbols:xe(n.flatMap(r=>r.fromSymbol?[M(r.fromSymbol)]:[])),toSymbols:xe(n.flatMap(r=>r.toSymbol?[M(r.toSymbol)]:[])),evidence:xe(n.map(r=>r.evidence)),strengths:xe(n.map(r=>r.strength??"unknown"))})).sort((n,r)=>n.fromRegionId.localeCompare(r.fromRegionId)||n.toRegionId.localeCompare(r.toRegionId))}function zB(e,t){return[...e.values()].map(n=>({kind:"external-import",name:n.name,fromRegionIds:xe([...n.fromFiles].flatMap(r=>{let i=t.get(r);return i?[i.id]:[]})),fromFiles:xe([...n.fromFiles])})).sort((n,r)=>n.name.localeCompare(r.name))}function KB(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 xe(i.map(o=>r.get(o)?.id).filter(o=>!!o))}function zC(e){return e.keyParts.map(t=>`${t.name}=${t.value}`).join(" ")}function xe(e){return[...new Set(e)].sort()}function KC(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 WB(e,t){return Vi(e.origins)-Vi(t.origins)||e.shortName.localeCompare(t.shortName)}function VB(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)}function YB(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function WC(e,t){return e.file.localeCompare(t.file)||e.line-t.line||e.query.localeCompare(t.query)}var XB=["causal","structure","complete"],QB={causal:["execution","runtime","dataflow","state","temporal"],structure:["contract","identity","ownership","dependencies"],complete:on},ZB=2,e$=48,VC=64,t$=5e4;function gs(e,t,n={}){let r=ze([...t.symbols??[],...t.locations??[]]),i=ze(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=n$(n.families,o),a=n.direction??"both",c=ze(n.subtypes??[]),l=n.connecting??!1,u=n.inventoryOnly??!1,d=ze(n.foldIds??[]),m=n.maxDepth??ZB,p=n.maxEdges??e$;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:t$,relations:r$(s)}),g=new Map(f.nodes.map(ne=>[ne.id,ne])),h=f.edges.filter(ne=>ne.disposition==="emitted"||ne.disposition==="folded").flatMap(ne=>i$(ne,g)),b=h.filter(ne=>s.includes(ne.family)).filter(ne=>c.length===0||c.includes(ne.subtype)),S=new Set(f.anchors.flatMap(ne=>ne.nodeIds));if(l&&S.size<2)throw new Error("Connecting evidence requires at least two resolved root nodes.");let y=new Set(b.map(ne=>ne.id)),x=hm(h,S,"incoming").filter(ne=>y.has(ne.id)),v=hm(h,S,"outgoing").filter(ne=>y.has(ne.id)),C=hm(h,S,"both").filter(ne=>y.has(ne.id)),E=l$(s,c,x,v,C),R=a==="incoming"?x:a==="outgoing"?v:C,w=l?h$(R,[...S],a):R,I=b$(w,S,a),A=[...w].sort((ne,U)=>S$(ne,U,I)),k=u$(A,p),T=m$(k,d),L=u?[]:d.length>0?A.filter(ne=>T.has(ne.id)):A,F=d.length>0?L:L.slice(0,p),N=d.length>0||u?[]:k,re=Math.max(0,L.length-F.length),ge=f.frontiers.filter(ne=>ne.disposition==="unsupported").length,Me=f.coverage.status==="incomplete"?"incomplete":re>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(ne=>({kind:ne.kind,query:ne.query,status:ne.status,nodeIds:[...ne.nodeIds],omittedCandidates:ne.omittedCandidates})),inventory:E,edges:F,folds:N,coverage:{status:Me,topologyStatus:f.coverage.status,scope:f.coverage.scope,maxDepth:m,maxEdges:p,matchedEdges:A.length,eligibleEdges:L.length,returnedEdges:F.length,omittedEdges:re,frontierGroups:f.frontiers.length,unsupportedFrontiers:ge,blindSpots:ze([...f.coverage.blindSpots,..._v(s)]),explanation:u?`${A.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.`:Me==="accounted"?"Every selected relationship in the bounded topology was emitted.":Me==="bounded"?`${re} selected relationship(s) were withheld by the explicit edge budget.`:f.coverage.explanation}}}function n$(e,t){let n=e&&e.length>0?e:QB[t],r=n.filter(i=>!on.includes(i));if(r.length>0)throw new Error(`Unsupported graph evidence family: ${r.join(", ")}.`);return ze(n)}function r$(e){return["call","contract-symbol","import","reference","runtime-boundary"]}function i$(e,t){let n=t.get(e.fromNodeId),r=t.get(e.toNodeId);return!n||!r?[]:(e.semantics??[]).flatMap((i,o)=>{let s=s$(i);if(!s)return[];let a=Ic(s,i.subtype);if(!a)throw new Error(`No graph relation provider contract is registered for ${s}/${i.subtype}.`);let c=c$(e);return a.relation.evidenceStrengths.includes(c)?[{id:`${e.id}:${o}:${s}`,family:s,semanticFamily:i.family,subtype:i.subtype,from:YC(n),to:YC(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:ze(e.evidence.map(l=>l.method)),evidenceConstituents:o$(e.evidence),context:i.context?{...i.context}:null,attributes:i.attributes?{...i.attributes}:null}]:[]})}function o$(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 s$(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 YC(e){let t=a$(e);return{id:e.id,kind:e.kind,label:t?M(t):e.label,symbol:t,location:e.location?{...e.location}:null}}function a$(e){return e.kind!=="symbol"||!e.id.startsWith("symbol:")?null:decodeURIComponent(e.id.slice(7))}function c$(e){let t=ze(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 hm(e,t,n){let r=ym(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 ym(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 l$(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)=>on.indexOf(u.family)-on.indexOf(d.family)||u.subtype.localeCompare(d.subtype))}function u$(e,t){let n=e.slice(t),r=new Map;for(let s of n){let a=d$(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+=VC){let m=u.slice(d,d+VC),p=m.map(b=>b.id),f=ze(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:g$(c,f.join("\0"),p),mode:p$(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)=>on.indexOf(s.family)-on.indexOf(a.family)||(s.region??"").localeCompare(a.region??"")||s.id.localeCompare(a.id))}function d$(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 m$(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 p$(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 f$(r,t)?"scc":[...r].every(o=>(n.get(o)?.size??0)<=1&&(t.get(o)?.size??0)<=1)?"linear":"topology"}function f$(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 g$(e,t,n){return`fold:${JB("sha256").update([e,t,...n].join("\0")).digest("hex").slice(0,16)}`}function h$(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 y$(e,i[o],i[s],n))r.set(a.id,a);return[...r.values()]}function y$(e,t,n,r){let i=ym(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 b$(e,t,n){let r=ym(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 S$(e,t,n){return JC(e,n)-JC(t,n)||XC(e)-XC(t)||QC(e.evidenceStrength)-QC(t.evidenceStrength)||on.indexOf(e.family)-on.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 JC(e,t){return Math.min(t.get(e.from.id)??Number.MAX_SAFE_INTEGER,t.get(e.to.id)??Number.MAX_SAFE_INTEGER)}function XC(e){let t=[e.from,e.to].filter(n=>n.kind==="structural-region").length;return t===2?2:t}function QC(e){switch(e){case"exact":return 0;case"mixed":return 1;case"derived":return 2;case"candidate":return 3;case"unknown":return 4}}function bm(e,t){let n=$r(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=na(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:l,...u})=>u),a=er(e,"forward",n).filter(l=>!e.isIgnored(l)),c=er(e,"reverse",n).filter(l=>!e.isIgnored(l));return{files:o,symbols:s,dependsOn:a,dependedOnBy:c}}function Sm(e,t){let n=$r(e,t);return n.length===0?[]:ex([...ZC(e,n),...C$(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(tx)}function v$(e,t){let n=$r(e,t);return n.length===0?[]:ex(ZC(e,n)).filter(r=>!e.isIgnored(r.relative_path)).map(r=>({...tx(r),basis:"external-reference"}))}function ZC(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 C$(e,t){let n=new q(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>mt(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function ex(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 tx(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:M(e.symbol)}}var hs=new WeakMap,nx=Dt({kind:"definition-exclusions",invalidation:Qe("definition-exclusions"),serialize:e=>JSON.stringify(e),deserialize:x$});function ix(e,t){let n=de(t);if(!(n==="rust"||n==="typescript"||n==="tsx"||n==="javascript"))return[];let i=X(e,t);if(!i)return[];let o=Ht(e,t,i),s=nx.read(e,t,o);if(s)return s;let a=n==="rust"?M$(e,t):w$(e,t);return nx.write(e,t,o,a),a}function x$(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=t.map(R$);return n.some(r=>r===null)?null:n}catch{return null}}function R$(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?U$(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 ox=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),E$=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,I$=/\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 w$(e,t){let n=X(e,t);if(!n||!L$(n))return[];let r=te(e,t);if(!r)return[];let i=hs.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&&ox.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(...sx(r,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),hs.set(r,a),a}function L$(e){if(e.includes("scip-query"))return!0;let t=!1;for(let n of ox)if(e.includes(n)){t=!0;break}return t&&E$.test(e)?!0:e.includes("use")&&I$.test(e)}var P$=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function D$(e){return P$.test(e)}function sx(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(D$(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 M$(e,t){let n=te(e,t);if(!n)return[];let r=hs.get(n);if(r)return r;let i=[],o=T$(n);return o?(hs.set(n,o),o):(ax(n.rootNode,i,!1,!1),i.push(...sx(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(...j$(n.rootNode)),hs.set(n,i),i)}function T$(e){return q$(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)",disposition:"exclude"}]:null}function ax(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"?k$(e,t,n,r):r&&$$(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"?A$(e,t,n):e.type==="mod_item"&&vm(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)ax(s,t,i,o)}function k$(e,t,n,r){let i=vm(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(cx(s)){o={reason:"#[allow(dead_code)]",disposition:"exclude"};break}let a=O$(s);if(a){o=a;break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o.reason,disposition:o.disposition})}function A$(e,t,n){let r=vm(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(B$)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(...)] - generated impl may access fields",disposition:"implicit-usage",containerName:i}),r.some(cx)&&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 vm(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 F$=new Set(["test","bench","tokio::test","async_std::test"]),N$=new Set(["no_mangle","export_name","link_name","used","macro_export","proc_macro","proc_macro_derive","proc_macro_attribute"]),_$=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 O$(e){if(/#\[\s*cfg\s*\(\s*test\s*\)/.test(e))return{reason:"#[cfg(test)]",disposition:"exclude"};let t=H$(e);return t?F$.has(t)?{reason:`#[${t}]`,disposition:"exclude"}:N$.has(t)?{reason:`Rust ABI/export attribute #[${t}]`,disposition:"implicit-usage"}:_$.has(t)?null:{reason:`Rust attribute macro #[${t}]`,disposition:"implicit-usage"}:null}function B$(e){return/#\[\s*derive\s*\(/.test(e)}function cx(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function $$(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function j$(e){let t=G$(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 H$(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 U$(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 q$(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 rx=/\bwith\s*=\s*"([^"]+)"/g;function G$(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){rx.lastIndex=0;let r;for(;(r=rx.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function lx(e){let t=Cm(e);return(n,r,i,o)=>t(n,r,i,o)?.disposition==="exclude"}function Cm(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=ix(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 ra(o))l.add(u);for(let u of l){let d=a.containers.get(u);d&&c.push(...d)}return z$(c)}}function z$(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 xm(e,t={}){Al(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function ux(e,t,n={}){Al(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function dx(e,t){if(t.isIgnoredPath(e.relativePath))return bt("ignored-file");if(Ce(e.symbol))return bt("module-like-symbol");if(!Uc(e.symbol))return bt("non-value-symbol");if(!e.isFunctionLike&&e.enclosingSymbol&&Uc(e.enclosingSymbol))return bt("nested-non-callable-value");if(!t.includeTests&&!K$(e.relativePath))return bt("test-file");if(!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName))return bt("excluded-file-region");let n=W(e.symbol);if(n==="<constructor>")return bt("implicit-constructor");if(e.symbol.startsWith("scip-python ")){if(n==="__all__")return bt("python-runtime-metadata");if(/^__[^_].*__$/.test(n))return bt("python-protocol-member")}return t.isDeclarationOnlyCallable()?bt("declaration-only-callable"):t.isFrameworkContractCallable()?bt("framework-contract-member"):Ze(e.symbol)?bt("rust-trait-impl-member"):Ci(e.symbol)?bt("rust-test-module"):!t.includeMembers&&!W$(e)?bt("member"):e.endLine-e.startLine+1<t.minLoc?bt("below-min-loc"):{accepted:!0}}function K$(e){return K(e)!=="test"}function bt(e){return{accepted:!1,rejectionReason:e}}function Uc(e){return Ae(e)||e.endsWith("().")||e.endsWith(".")}function W$(e){return mt(e.symbol)||ra(e.symbol).length===0}function mx(){return new Map}function px(e,t,n){let r=new Map;for(let i of Kf(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||Gc(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function fx(e,t,n,r={}){let i=new Set;if(r.conservative||n.size===0){for(let o of Vf(e,t))i.add(o.symbol_id);return i}for(let o of Wf(e,t))e.isIgnored(o.relative_path)||n.has(o.relative_path)||i.add(o.symbol_id);return i}function Rm(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 qc(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 gx(e){return e?.occurrences??0}function Gc(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=yx(e,t,n);o.occurrences+=r,o.sources.add(i)}function hx(e,t,n,r,i){if(r<=0)return;let o=yx(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function yx(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 V$=new Set(["componentDidCatch","componentDidMount","componentDidUpdate","componentWillUnmount","getDerivedStateFromError","getDerivedStateFromProps","getSnapshotBeforeUpdate","render","shouldComponentUpdate","UNSAFE_componentWillMount","UNSAFE_componentWillReceiveProps","UNSAFE_componentWillUpdate"]);function Zi(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=te(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:V$.has(t.leaf)&&/\bextends\s+(?:React\.)?(?:Component|PureComponent)\b/.test(o)}var Y$=1e3,J$=300;function ci(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=_("dead.candidates",()=>{let v=Pe(X$(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c);return u=v.length,v},()=>({definitions:u})),m=0,p=o?_("dead.inactive-barrels",()=>{let v=new Set(Yb(e));return m=v.size,v},()=>({paths:m})):new Set,f=0,g=a?mx():_("dead.mention-reference-counts",()=>{let v=px(e,p,d.map(C=>C.symbolId));return f=v.size,v},()=>({definitions:d.length,symbolsWithReferences:f})),h=0,b=a?_("dead.mentioned-symbol-ids",()=>{let v=fx(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=>!qc(g,v.symbolId,v.relativePath));a?_("dead.source-fallback.dead-code-only",()=>ij(e,S,g,{inactiveBarrelPaths:p}),()=>({definitions:S.length,testReferencesIncluded:!0})):_("dead.source-fallback.ast",()=>rj(e,S,g,{inactiveBarrelPaths:p}),()=>({definitions:S.length,testReferencesIncluded:!0}));let y=a?S.filter(v=>!Rm(g,v.symbolId)):S.filter(v=>!qc(g,v.symbolId,v.relativePath));_("dead.caller-map-supplement",()=>cj(e,y,g,{inactiveBarrelPaths:p,includeSemantic:!a&&l}),()=>({definitions:y.length,semantic:!a&&l}));let x=a?S.filter(v=>!Rm(g,v.symbolId)):d;return nj(e,ej(x,g))}function X$(e,t){let n=lx(e),r=[];for(let i of ho(e,{scope:t.scope,symbolMatches:Uc,sqlPrefilter:"function-like"}))dx(i,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n,isDeclarationOnlyCallable:()=>Z$(e,i),isFrameworkContractCallable:()=>Zi(e,i)}).accepted&&r.push(i);return r}var Q$=["method_signature","abstract_method_signature","call_signature","construct_signature"];function Z$(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=te(e,t.relativePath);if(n)return n.rootNode.descendantsOfType([...Q$]).some(i=>i.startPosition.row<=t.startLine&&i.endPosition.row>=t.endLine);let r=Q(e,t.relativePath).slice(t.startLine,t.endLine+1).join(`
|
|
121
|
+
`).trim();return r.endsWith(";")&&!r.includes("=>")&&!r.includes("{")}function ej(e,t){return e.map(n=>tj(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 tj(e,t){let n=t.get(e.symbolId)??new Map,r=gx(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 nj(e,t){let n=Cm(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(tt(e,u.relative_path)){a++;continue}if(Ge(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:M(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 rj(e,t,n,r){if(t.length===0)return;let i=new q(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 ae(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)&&(sj(e,c)||Gc(n,c.target.symbolId,c.sourceFile,aj(c),"source-fallback"))})}function ij(e,t,n,r){if(t.length===0)return;let i=new q(e),o=Hf(t),s=new Set(i.sourceFiles());for(let u of ae(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=Xf(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?oj(u,d,p,()=>l(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),ux(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&bx(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||Gc(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function oj(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=>Ke(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=>Ke(l,d.relativePath));if(u.length>0&&u.length===n.length)return u}return i.permissive?[...n]:[]}function sj(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&bx(e,t)}function aj(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function bx(e,t){return t.occurrences>1?!1:pe(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function cj(e,t,n,r){let i=r.includeSemantic!==!1,o=i&&t.length>=Y$&&ae(e).length>=J$,s=(u,d)=>{d===u.relativePath||e.isIgnored(d)||r.inactiveBarrelPaths.has(d)||hx(n,u.symbolId,d,1,"caller-map")};if(o?_("dead.caller-map.per-symbol-non-semantic",()=>{for(let u of t){let d=An(e,u,{semantic:!1,semanticEvidence:ue});for(let m of d)s(u,m.file)}},()=>({definitions:t.length,semantic:!1})):_("dead.caller-map.per-symbol",()=>{for(let u of t){let d=An(e,u,{semantic:i,semanticEvidence:ue});if(d.length!==0)for(let m of d)s(u,m.file)}},()=>({definitions:t.length,semantic:i})),!o)return;let a=0,c=_("dead.caller-map.semantic-candidates",()=>{let u=t.filter(d=>!qc(n,d.symbolId,d.relativePath));return a=u.length,u},()=>({definitions:t.length,semanticCandidates:a}));if(c.length===0)return;let l=Wy(e,c);for(let u of c){let d=l.get(u.symbolId);if(d)for(let m of d)s(u,m)}}function lj(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:M(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:uj(e,r,n)}function uj(e,t,n){return He(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>dj(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function dj(e,t){let r=An(e,t,{limit:500,semanticEvidence:ue}).filter(i=>i.file!==t.relativePath);return{symbol:t.symbol,shortName:M(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 mj(e,t,n={}){return xj(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function pj(e,t){let n=le(e,t),r=hj(e,t);if(r.length>0&&!bj(n))return r;let i=yj(e,t,n);return Em(t)&&i.length>0?i:Sj([...r,...i])}function fj(e,t,n={}){let r=Mt(e,t);if(!r)return[];let i=vx(e,r),o=n.semantic===!1?null:Sx(e,r);return(o?gj(o,i):i).filter(a=>!a.used).map(a=>({symbol:a.symbol,shortName:a.shortName,importedIn:a.importer}))}function gj(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 hj(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:M(r.symbol),fromFile:r.importer}))}function yj(e,t,n=le(e,t)){let r=n?.relativePath??null,i=n?W(n.symbol):t.replace(/\(\)$/,""),o=n?Ce(n.symbol):!1,s=new Set;for(let c of ae(e,{includeIgnored:!1}))for(let l of pe(e,c))vj(l,c,{targetFile:r,targetLeaf:i,targetIsModule:o,targetPattern:t})&&s.add(c);let a=Em(t)?t.trim():null;return[...s].sort().map(c=>({symbol:a??n?.symbol??i,shortName:a??(n?M(n.symbol):i),fromFile:c}))}function bj(e){return!!(e&&(e.symbol.startsWith("scip-clojure ")||de(e.relativePath)==="clojure"))}function Sj(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 vj(e,t,n){return!e.sourcePath||n.targetFile&&Ct(e.sourcePath)!==Ct(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&wj(t)||e.kind==="namespace"&&Cj(e,n.targetPattern)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function Cj(e,t){let n=t.trim().replace(/\(\)$/,"");return Em(n)?e.importedName===n||e.localName===n:!1}function Em(e){let t=e.trim().replace(/\(\)$/,"");return t.includes(".")&&!t.includes("/")&&!t.includes(":")}function xj(e,t,n={}){let r=Mt(e,t);return r?Rj(e,r,n)??(n.semantic===!1?null:Sx(e,r))??vx(e,r):null}function Rj(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?[]:Go(e,t);return i.map(s=>({symbol:s.symbol,shortName:M(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 Sx(e,t){let n=Go(e,t);return n.length>0?n.map(r=>{let i=Cx(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 vx(e,t){let n=Ej(t,X(e,t));return pe(e,t).map(r=>{let i=Cx(r.importedName,r.localName,r.kind),o=r.kind==="side-effect"||Ij(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 Ej(e,t){let n=new Set;if(de(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 Ij(e,t){if(de(e)!=="rust"||t.used||t.kind==="side-effect")return!1;let n=t.localName??t.importedName;return n==="_"||/^[A-Z]/.test(n)}function Cx(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 wj(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function Lj(e,t){let n=le(e,t);if(!n)return[];let i=new q(e).definitionsForFile(n.relativePath).filter(o=>o.symbol!==n.symbol).filter(o=>$f(n.symbol,o.symbol)).sort((o,s)=>o.startLine-s.startLine||o.endLine-s.endLine).map(o=>({symbol:o.symbol,shortName:M(o.symbol),startLine:o.startLine,endLine:o.endLine,kind:Kt(o.symbol)??"unknown"}));return de(n.relativePath)!=="clojure"?i:Dj(i,Pj(e,n))}function Pj(e,t){let n=W(t.symbol);if(!n)return[];let r=M(t.symbol);return(Y(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 Dj(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 Mj(e,t){let n=le(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:M(n.symbol),count:r?.file_count??0,symbol:n.symbol,definedIn:n.relativePath}]}function Tj(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 kj(e,t={}){return Aj(e,t).map(n=>({name:M(n.symbol),count:n.file_count,symbol:n.symbol,definedIn:n.defined_in}))}function Aj(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 Fj(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 xx=`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 Nj(e,t,n){let r=Mt(e,t)??t,i=Mt(e,n)??n,o=e.get(xx,r,i,i,r);return{...Rx(r,i,o?.shared??0)}}function _j(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=>Rx(a.file1,a.file2,a.shared))}function Rx(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 li(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 ys(e,t={}){return wx(e,t).cycles}function wx(e,t={}){return Lx(e,t)}function Lx(e,t={}){let{scope:n,maxDepth:r=10,edgeBasis:i="symbol-references"}=t,o=qe(e,n,i==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-only"}:void 0),{components:s}=li(o),a=s.filter(c=>Oj(o,c)).map(c=>{let l=[...c].sort(),u=Bj(o,l),d=jj(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 Oj(e,t){if(t.length>1)return!0;let n=t[0];return n!==void 0&&e.get(n)?.has(n)===!0}function Bj(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=$j(e,i,n,r);if(o)return[n,...o]}throw new Error(`Cyclic component did not contain a witness path from ${n}.`)}function $j(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 jj(e){for(let r of e){let i=K(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":Hi(t)||Hi(n)||Ex(t,n)||Ex(n,t)||Ix(t,n)||Ix(n,t)||K(t)==="entry"||K(n)==="entry"?"module-hierarchy":"real"}function Ex(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 Ix(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}import{readdirSync as Hj}from"fs";import{join as Mx}from"path";function Dx(e,t){let n=Px(e),r=Px(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 Px(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}function Ir(e,t){return Dx(e,t)}function Uj(e){return Tx(e).replace(/\/\*\*?$/,"")}function zc(e,t){let n=Tx(t),r=Uj(n),i=n.endsWith("/**"),o=[],s=(a,c)=>{let l;try{l=Hj(a,{withFileTypes:!0})}catch{return}for(let u of l){if(u.name.startsWith("."))continue;let d=c?`${c}/${u.name}`:u.name;Ir(n,d)&&o.push(d),i&&u.isDirectory()&&s(Mx(a,u.name),d)}};return s(Mx(e,r),r),o.sort()}function Tx(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}var qj=/\.(test|spec)\.(ts|tsx|js|jsx|mts|cts)$/,kx=new Map;function Ax(e,t,n,r){if(!t?.testPaths?.length)return[];let i=Gj(t),o=[];for(let s of zj(e,t.testPaths)){let a=Kj(e,s,r),c=a?n(a):null;if(c)for(let l of pe(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 Wj(o)}function Gj(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 zj(e,t){let n=`${e.config.projectRoot}\0${t.join("\0")}`,r=kx.get(n);if(r)return r;let i=new Set;for(let s of t)for(let a of zc(e.config.projectRoot,s))qj.test(a)&&i.add(a);let o=[...i].sort();return kx.set(n,o),o}function Kj(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=pe(e,t).map(s=>s.sourcePath).filter(s=>!!s&&n(s)&&s.split("/").pop()===i);return o.length===1?o[0]:null}function Wj(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 Fx(e,t){let n=(e?.boundaries??[]).filter(r=>r.paths.some(i=>Ir(i,t)));return n.length===1?n[0].name:null}var zn="architecture:";function Nx(e,t,n,r={}){let i=Yj(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=>Ir(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 E=o.get(C);if(!E||v===E)continue;let R=eo(v,E),w=l.get(R);w||(w={from:v,to:E,fileEdges:[],importers:new Set,importedFiles:new Set},l.set(R,w)),w.fileEdges.push({fromFile:y,toFile:C}),w.importers.add(y),w.importedFiles.add(C)}}let u=[...l.values()].map(y=>Jj(y,n)).sort(i1),d=u,m=new Map(d.map(y=>[eo(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(eo(y.to,y.from));x&&f.push({boundaries:[y.from,y.to],forward:y,reverse:x})}let{components:g}=li(p),h=g.filter(y=>y.length>1).map(y=>Qj(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:e1(n,d),boundaryLimits:t1(n,d,s),fragileEdges:d.filter(y=>y.fragile),testBoundaryViolations:r.testBoundaryViolations??[],coarseBoundaries:Zj(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 bs(e,t={}){let n=qe(e,t.scope,{scipEdges:"imports-only",sourceEdges:"imports-and-reexports"}),r=ae(e,{includeIgnored:!1}).filter(o=>!t.scope||o.includes(t.scope)),i=new Set(r);return Nx(n,r,e.config.architecture,{isModuleHierarchyFile:o=>Vj(e,o),testBoundaryViolations:Ax(e,e.config.architecture,o=>Fx(e.config.architecture,o),o=>i.has(o))})}function Vj(e,t){let n=K(t);return n==="test"||n==="entry"?!0:n!=="barrel"?!1:z(e,t).length===0}function Im(e){let t=e.forbiddenEdges.map(r=>`${zn}forbidden-edge:${encodeURIComponent(r.from)}:${encodeURIComponent(r.to)}`);if(e.policyCoverage.requiresCompletePolicy)for(let r of e.policyCoverage.missingRows)t.push(`${zn}missing-policy-row:${encodeURIComponent(r)}`);if(e.policyCoverage.requiresCompleteCoverage){for(let r of e.coverage.unmappedFiles)t.push(`${zn}unmapped-file:${encodeURIComponent(r)}`);for(let r of e.coverage.ambiguousFiles)t.push(`${zn}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(`${zn}stale-allowance:${encodeURIComponent(r.from)}:${encodeURIComponent(r.to)}`);for(let r of e.testBoundaryViolations)t.push(`${zn}test-boundary:${encodeURIComponent(r.testFile)}:${encodeURIComponent(r.importedBoundary)}`);for(let r of e.boundaryLimits)t.push(`${zn}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=`${zn}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(`${zn}cycle:${r.boundaries.map(i=>encodeURIComponent(i)).sort().join("|")}`);return[...new Set(t)].sort()}function Yj(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 Jj(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:Xj(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 Xj(e,t,n){return!e.allowedDependencies||!Object.hasOwn(e.allowedDependencies,t)?"undeclared":e.allowedDependencies[t].includes(n)?"allowed":"forbidden"}function Qj(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 Zj(e,t,n=n1,r=!1,i=()=>"directory"){let o=[];for(let[s,a]of t){let c=i(s)==="file"?f=>f:r1,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=eo(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}=li(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 e1(e,t){let n=new Set(t.map(s=>eo(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(eo(s,c))||o.push({from:s,to:c});return o.sort((s,a)=>s.from.localeCompare(a.from)||s.to.localeCompare(a.to))}function t1(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 n1(e){let t=K(e);return t==="test"||t==="entry"}function r1(e){let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)}function eo(e,t){return`${e}\0${t}`}function i1(e,t){return e.from.localeCompare(t.from)||e.to.localeCompare(t.to)}function o1(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:o=2,scanLimit:s}=t,a=new q(e),c=Pe(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s),l=t.semantic!==!1,u=jr(e,c,{limit:500,semantic:l,semanticEvidence:ue});return c.map(m=>s1(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 s1(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 Vt(e,t,{limit:500,semantic:n,semanticEvidence:ue})){if(m.file===t.relativePath)continue;let p=`${m.symbol}|${m.file}`;s.has(p)||s.set(p,{symbol:m.symbol,shortName:M(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:M(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 Ss(e,t={}){let{scope:n,minLoc:r=3,scanLimit:i}=t,o=new q(e),s=t.semantic!==!1,a=0,c=_("isolated.candidates",()=>{let C=Pe(o.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:typeof i=="number"&&i>0}),i).filter(E=>!Zi(e,E));return a=C.length,C},()=>({definitions:a})),l=0,u=_("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=_("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 mr(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=_("isolated.source-fallback-callers",()=>{let v=o.sourceFallbackCallerFiles(g,{skipPath:C=>K(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=_("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)=>ce(C)-ce(v)||v.relativePath.localeCompare(C.relativePath)||v.startLine-C.startLine).map(v=>({symbol:v.symbol,shortName:M(v.symbol),relativePath:v.relativePath,startLine:v.startLine,endLine:v.endLine,loc:ce(v)}))}import{SymbolInformation_Kind as ot}from"@c4312/scip";var _x=500;function a1(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=Bg.get(n);if(r!==void 0)return r;for(let[i,o]of ha)if(o.toLowerCase().includes(n))return i;return null}function c1(e,t,n={}){let{scope:r,limit:i=100}=n,o=a1(t);return o===null?[]:u1(e,r).map(a=>({row:a,resolvedKind:Bx(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:M(a.symbol),kind:c,kindName:vo(c),relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function l1(e,t={}){let n=d1(e,t.scope);for(let r of m1(e,t.scope)){let i=Bx(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:vo(r),count:i}))}function u1(e,t){return He(e,{scope:t}).map(p1)}function d1(e,t){let n=new Map;for(let r of Ox(ae(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 m1(e,t){let n=[];for(let r of Ox(ae(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 Ox(e){let t=[];for(let n=0;n<e.length;n+=_x)t.push(e.slice(n,n+_x));return t}function p1(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 Bx(e){return e.kind!==null&&e.kind!==0?f1(e.kind,e.symbol,e.documentation):g1(e.symbol,e.documentation,e.enclosing_symbol)}function f1(e,t,n){let r=(n??"").toLowerCase();if(Kt(t)==="type"){if(r.includes("type "))return ot.TypeAlias;if(r.includes("interface "))return ot.Interface;if(r.includes("struct "))return ot.Struct;if(r.includes("trait "))return ot.Trait;if(r.includes("class "))return ot.Class}return e}function g1(e,t,n){let r=nr(e);if("kind"in r)return null;let i=r.descriptors,o=i[i.length-2]??null,s=Kt(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?ot.TypeAlias:a.includes("interface ")?ot.Interface:a.includes("struct ")?ot.Struct:a.includes("trait ")?ot.Trait:a.includes("class ")?ot.Class:ot.Class:s==="method"?o?.suffix==="type"?ot.Method:ot.Function:s==="namespace"?ot.Module:s!=="term"?null:a.includes("async def ")||a.includes("def ")?ot.Function:(n?Kt(n):o?.suffix??null)==="type"?ot.Field:ot.Variable}function h1(e,t={}){let{limit:n=10,scope:r,minDepth:i=3,edgeBasis:o="symbol-references"}=t,s=qe(e,r,o==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-only"}:void 0),{components:a,componentOf:c}=li(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&&y1(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(b1(y,S,o)))}return g.sort((h,b)=>b.depth-h.depth||h.chain.join("\0").localeCompare(b.chain.join("\0"))),S1(g).slice(0,n)}function y1(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 b1(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 S1(e){let t=[];for(let n of e)t.some(r=>v1(n.chain,r.chain))||t.push(n);return t}function v1(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 C1(e,t){let n=le(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:M(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:M(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(i.length>1)return i;let c=nr(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 x1(e,t={}){let r=new q(e).productionCallableDefinitions({scope:t.scope,requireCallableSymbol:!0,includeSuppressed:!0}),i=Ux(e,r),o=t.search?.trim().toLocaleLowerCase();return r.map(s=>qx(e,s,i.get(s.symbolId)??[])).filter(s=>s!==null).map(s=>s.result).filter(s=>!o||I1(s).includes(o)).sort(w1)}function R1(e,t,n={}){let r=pt(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:M(r.match.symbol),relativePath:r.match.relativePath,startLine:r.match.startLine},...r.candidates]};let i=new q(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:M(r.match.symbol),file:r.match.relativePath,reason:"The resolved symbol is not a callable definition."};let s=Ux(e,[o]),a=qx(e,o,s.get(o.symbolId)??[]);if(!a)return{kind:"not-entry",query:t,symbol:o.symbol,shortName:M(o.symbol),file:o.relativePath,reason:"The callable is neither an external root nor an uncalled callable on a detected entry surface."};let c=L1(e,i,o),l=new Set(n.expand??[]),u=T1(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 Ux(e,t){let n=t.filter(r=>Gx(e,r.relativePath)||Ui(e,r.symbol,r.relativePath).length>0);return jr(e,n,{semantic:!1,semanticEvidence:ue})}function qx(e,t,n){let r=E1(e,t),i=r.length>0,o=Gx(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:M(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,documentation:t.documentation,confidence:i?"root":"candidate",evidence:s,indexedCallerCount:n.length}}}function Gx(e,t){return tt(e,t)||/(?:^|\/)entry\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(t)}function E1(e,t){let n=Ui(e,t.symbol,t.relativePath),r=[];return $x(n,["package-surface-file","transitive-package-surface"])&&Tt(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"),$x(n,["configured-file","configured-path-prefix","configured-qualified-var","configured-symbol-pattern"])&&r.push("configured-entry-root"),r}function $x(e,t){return t.some(n=>e.includes(n))}function I1(e){return[e.symbol,e.shortName,e.file,e.documentation??"",...e.evidence].join(`
|
|
319
|
+
`).toLocaleLowerCase()}function w1(e,t){return jx(e.confidence)-jx(t.confidence)||e.file.localeCompare(t.file)||e.startLine-t.startLine||e.symbol.localeCompare(t.symbol)}function jx(e){return e==="root"?0:1}function L1(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,Hx(d,m));for(let p of l.get(d.symbolId)??[]){let f=P1(t,p,o);if(!f){let S=M1(d,p);a.set(F1(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,Hx(f,Math.min(g,h??g)));let b=D1(d,f,p);s.set(A1(b),b),h===void 0&&u.push(f)}}c=u}return{symbols:[...i.values()].sort(N1),edges:[...s.values()].sort(_1),externalCalls:[...a.values()].sort(O1)}}function P1(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 Hx(e,t){return{symbol:e.symbol,shortName:M(e.symbol),file:e.relativePath,depth:t}}function D1(e,t,n){return{fromSymbol:e.symbol,fromShortName:M(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:M(t.symbol),toFile:t.relativePath,source:n.source,evidenceStrength:n.source==="scip-chunk"?"candidate":"exact"}}function M1(e,t){return{fromSymbol:e.symbol,fromShortName:M(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:M(t.symbol),reportedFile:t.file,source:t.source,evidenceStrength:t.source==="scip-chunk"?"candidate":"exact"}}function T1(e,t){let n=Ve(e.symbols,l=>l.file),r=Ve(e.edges.filter(l=>l.fromFile===l.toFile),l=>l.fromFile),i=Ve(e.externalCalls,l=>l.fromFile),o=k1(e.edges.filter(l=>l.fromFile!==l.toFile)),s=Ve(o,l=>l.toRegionId),a=Ve(o,l=>l.fromRegionId);return{regions:[...n.entries()].map(([l,u])=>{let d=wm(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:vs((s.get(d)??[]).map(g=>g.fromRegionId)),outgoingRegionIds:vs((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 k1(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:wm(r.fromFile),fromFile:r.fromFile,toRegionId:wm(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:vs(n.map(i=>i.fromShortName)),toSymbols:vs(n.map(i=>i.toShortName)),evidence:vs(n.map(i=>i.source))}}).sort((n,r)=>n.fromFile.localeCompare(r.fromFile)||n.toFile.localeCompare(r.toFile))}function wm(e){return`file:${e}`}function vs(e){return[...new Set(e)].sort()}function A1(e){return`${e.fromSymbol}\0${e.toSymbol}`}function F1(e){return`${e.fromSymbol}\0${e.toSymbol}`}function N1(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function _1(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function O1(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function Qt(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function st(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function wr(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 zx(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 Lm(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 to(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 no(e,t){let n=0;for(let r of e){let i=t.get(r)??0;n+=i*i}return Math.sqrt(n)}function Kx(e,t,n,r={}){let i=0,o=0,s=0,a=r.medianIdf??to(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 Wx(e,t,n,r){let i=0,o=r.medianIdf??to(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 Cs(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=K1(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!Ae(o.symbol))return[];if(o.callees.size===0)return Vx(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"});let s=$1(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):Vx(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"})}function Tm(e,t,n,r={}){let i=le(e,t),o=le(e,n);if(!i||!o)return null;let s=Cs(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:M(i.symbol),file:i.relativePath,loc:a},symbolB:{symbol:o.symbol,shortName:M(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:B1(s)}}function B1(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 $1(e,t,n,r){let i=ro(e).calleeIndex({minCallees:3,scanLimit:r.scanLimit,semantic:r.semantic}),o=eH(t,i.corpus),s=X1(o,i),a=j1(o,i),c=to(a),l=no(o.callees,a),u=[];for(let d of s){if(d.callees.size<3)continue;let m=no(d.callees,a),p=Qx(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 j1(e,t){let n=new Map(t.docFreq);for(let r of e.callees)n.set(r,(n.get(r)??0)+1);return Lm(n,t.corpus.length+1)}function Qx(e,t,n,r){let i=U1(e,t,n,r);if(!q1(i,r))return null;let{similarity:o,significantShared:s,trivialShared:a}=i,c=s.length>0?s:a,l=rR(c,"callees");return{symbolA:e.symbol,shortNameA:M(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:M(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:c.map(M),uniqueToA:[...st(e.callees,t.callees)].map(M),uniqueToB:[...st(t.callees,e.callees)].map(M),...l}}function H1(e,t,n,r){let i=r.magnitudeA??no(e.callees,n),o=r.magnitudeB??no(t.callees,n),s=0,a=0,c=0,l=r.medianIdf??to(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 U1(e,t,n,r){return r.magnitudeA===void 0||r.magnitudeB===void 0?Kx(e.callees,t.callees,n,{medianIdf:r.medianIdf}):Wx(e.callees,t.callees,n,{medianIdf:r.medianIdf,magnitudeA:r.magnitudeA,magnitudeB:r.magnitudeB})}function q1(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 xs(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=ke(),u=0,d=0,m=0,p=0,f=0,g=0,h=0;return _("similar.all",()=>{let S=ro(e).calleeIndex({minCallees:o,scope:i,scanLimit:a,semantic:c}),y=S.corpus;u=y.length;let x=t.focusFiles,v=[],C=0;return _("similar.all.pair-scan",()=>{for(let E=0;E<y.length;E+=1){let R=y[E],w=x?.has(R.file)??!1,I=S.weightedMagnitudes[E],A=new Set;for(let k of R.callees){let T=S.candidateIndexesByCallee.get(k);if(T)for(let L of T)L<=E||x&&!w&&!x.has(y[L].file)||A.add(L)}l&&(m+=A.size,A.size>0&&(d+=1));for(let k of A){let T=y[k];if(s&&R.file===T.file){l&&(f+=1);continue}if(Zx(R,T)){l&&(g+=1);continue}l&&(p+=1);let L=Qx(R,T,S.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:S.medianIdf,magnitudeA:I,magnitudeB:S.weightedMagnitudes[k]});L&&(G1(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})),_("similar.all.sort-project",()=>(v.sort((E,R)=>R.result.similarity-E.result.similarity||E.order-R.order),v.map(E=>E.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 km(e,t={}){let{minSimilarity:n=.5,scope:r,minCallees:i=4,crossFileOnly:o=!1,scanLimit:s}=t,a=t.semantic!==!1,c=ke(),l=0,u=0,d=0,m=0,p=0,f=0,g=0;return _("similar.all-count",()=>{let b=ro(e).calleeIndex({minCallees:i,scope:r,scanLimit:s,semantic:a}),S=b.corpus;l=S.length;let y=t.focusFiles;return _("similar.all-count.pair-scan",()=>{for(let x=0;x<S.length;x+=1){let v=S[x],C=y?.has(v.file)??!1,E=b.weightedMagnitudes[x],R=new Set;for(let w of v.callees){let I=b.candidateIndexesByCallee.get(w);if(I)for(let A of I)A<=x||y&&!C&&!y.has(S[A].file)||R.add(A)}c&&(d+=R.size,R.size>0&&(u+=1));for(let w of R){let I=S[w];if(o&&v.file===I.file){c&&(p+=1);continue}if(Zx(v,I)){c&&(f+=1);continue}c&&(m+=1),H1(v,I,b.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:b.medianIdf,magnitudeA:E,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 Zx(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 eR=Dt({kind:"source-fingerprints",invalidation:Qe("source-fingerprints"),serialize:vH,deserialize:SH});function G1(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 z1=["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 K1(e,t,n){let r=le(e,t);if(!r||!Ae(r.symbol))return null;let i=new q(e),o=Vt(e,r,{semantic:n.semantic,semanticEvidence:ue});return{symbol:r.symbol,file:r.relativePath,callees:Kc(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}var W1=Le("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),V1=Le("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function tR(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=t.semantic!==!1,a=W1.get(e,()=>new Map),c=`${n}|${r??""}|${o??""}|${s}`,l=!0,u=0,d=0;return _("similar.callee-fingerprints.resolve",()=>{let m=a.get(c);if(l=m!==void 0,m||(m=Q1(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 Y1(e,t){let{minCallees:n,scope:r,scanLimit:i}=t,o=t.semantic!==!1,s=V1.get(e,()=>new Map),a=`${n}|${r??""}|${i??""}|${o}`,c=!0,l=0,u=0,d=0;return _("similar.callee-index.resolve",()=>{let m=s.get(a);return c=m!==void 0,m||(m=J1(tR(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 ro(e){return{calleeCorpus:t=>tR(e,t),calleeIndex:t=>Y1(e,t),sourceCorpus:(t={})=>cR(e,t),sourceIndex:(t={})=>Xx(e,t),sourceCandidates:(t,n)=>(n.candidateMode??"full")==="target-pruned"?dH(e,t,{minSimilarity:n.minSimilarity,scanLimit:n.scanLimit}):uH(t,Xx(e,{scanLimit:n.scanLimit}))}}function J1(e){let t=ke(),n=0,r=_("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=_("similar.callee-index.idf-weights",()=>Lm(r,e.length),()=>({corpusSize:e.length,uniqueCallees:r.size})),s=_("similar.callee-index.weighted-magnitudes",()=>e.map(m=>no(m.callees,o)),()=>({corpusSize:e.length})),a=0,c=0,l=0,u=_("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=_("similar.callee-index.median-idf",()=>to(o),()=>({uniqueCallees:o.size}));return{corpus:e,candidateIndexesByCallee:u,docFreq:r,idfWeights:o,weightedMagnitudes:s,medianIdf:d,ubiquityThreshold:i}}function X1(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 Q1(e,t){let{minCallees:n,scope:r,scanLimit:i,semantic:o}=t,s=ke(),a=new q(e),c=0,l=_("similar.callee-fingerprints.candidates",()=>{let g=Pe(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=_("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 _("similar.callee-fingerprints.shape",()=>{let g=l.map(S=>({symbol:S.symbol,file:S.relativePath,callees:Kc((d.get(S.symbolId)??[]).map(y=>y.symbol)),paramCount:a.callableSignature(S)?.paramCount??-1})),h=Z1(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 nR=5;function Z1(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)>=nR);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 eH(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>=nR);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 Kc(e){return new Set([...e].filter(t=>!tH(t)))}function tH(e){return z1.some(t=>e.includes(t))}function Vx(e,t,n){let r=oH(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 _("similar.source-shape",()=>{let m=ro(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=Qt(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:M(r.symbol),fileA:r.file,symbolB:p.symbol,shortNameB:M(p.symbol),fileB:p.file,similarity:h,similarityBasis:"source-tokens",sharedCallees:[...f].sort(),uniqueToA:[...st(r.tokens,p.tokens)].sort(),uniqueToB:[...st(p.tokens,r.tokens)].sort(),...rR([...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 rR(e,t){let n=e.flatMap(Dm),r=e.flatMap(h=>Yx(h,t)),i=Pm(n,iR),o=Pm(n,oR),s=Pm(r,Mm),a=[...new Set(r.filter(Jx))],c=e.filter(h=>{let b=Yx(h,t);return b.some(S=>Mm.has(S))&&b.some(Jx)}).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=>sR.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:nH(f,g)}}function nH(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 Pm(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function Dm(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function Yx(e,t){if(t==="source-tokens")return Dm(e);let n=W(e);return Dm(n.length>0?n:rH(e))}function rH(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 Jx(e){return e.length>3&&!Mm.has(e)&&!iR.has(e)&&!oR.has(e)&&!sR.has(e)&&!iH.has(e)}var Mm=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),iR=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),oR=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"]),sR=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),iH=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 oH(e,t){let n=le(e,t);if(!n||!Ae(n.symbol))return null;let r=sH(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function sH(e,t){let n=W(t.symbol),r=hH(e,t.relativePath,t.startLine,t.endLine,n),i=dR(r,n);return i.size>0?i:null}var aH=Le("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),cH=Le("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function aR(e){return`${e.scanLimit??""}`}function cR(e,t={}){let n=aH.get(e,()=>new Map),r=aR(t),i=n.get(r);return i||(i=gH(e,t),n.set(r,i)),i}function Xx(e,t={}){let n=cH.get(e,()=>new Map),r=aR(t),i=n.get(r);return i||(i=lH(cR(e,t)),n.set(r,i)),i}function lH(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 uH(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 dH(e,t,n){let r=ke(),i=new q(e),o=mH(t.tokens.size,n.minSimilarity),s=0,a=0,c=0,l=_("similar.source-shape.target-files",()=>{let f=[...t.tokens],g=[];for(let h of ae(e,{includeIgnored:!1})){s+=1;let b=X(e,h);b&&(a+=1,pH(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=_("similar.source-shape.target-definitions",()=>{let f=Pe(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 _("similar.source-shape.target-fingerprints",()=>{let f=lR(e,d);return r&&(m=f.length),f},()=>({symbol:t.symbol,definitionCount:u,fingerprintCount:m})).filter(f=>f.symbol!==t.symbol)}function mH(e,t){return Math.max(2,Math.ceil(e*t))}function pH(e,t,n){if(t.length<n)return!1;let r=e.toLowerCase(),i=0;for(let o of t)if(fH(r,o)&&(i+=1,i>=n))return!0;return!1}function fH(e,t){return t==="num"?/\b\d+\b/.test(e):e.includes(t)}function gH(e,t={}){let n=new q(e),{scanLimit:r}=t,i=Pe(n.productionCallableDefinitions({sortByLocDesc:typeof r=="number"&&r>0}),r);return lR(e,i)}function lR(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=X(e,i);if(!s)continue;let a=Ht(e,i,s),c=bH(e,i,a),l=!1,u=null;for(let d of o){let m=yH(d),p=c.get(m),f=p?new Set(p.tokens):null;f||(u??=Q(e,i),f=dR(uR(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&&CH(e,i,a,c)}return t.map(i=>r.get(i.symbol)).filter(i=>!!i)}function hH(e,t,n,r,i){let o=Q(e,t);return o.length===0?"":uR(o,n,r,i)}function uR(e,t,n,r){if(n>=t&&n-t<=12)return e.slice(t,n+1).join(`
|
|
320
|
+
`);let i=[new RegExp(`\\bdef\\s+${Ne(r)}\\b`),new RegExp(`\\bfun\\s+${Ne(r)}\\b`),new RegExp(`\\bfn\\s+${Ne(r)}\\b`),new RegExp(`\\bfunction\\s+${Ne(r)}\\b`),new RegExp(`\\b${Ne(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&&RH(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 yH(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function bH(e,t,n){return eR.read(e,t,n)??new Map}function SH(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 vH(e){let t={entries:[...e.values()].sort((n,r)=>n.key.localeCompare(r.key))};return JSON.stringify(t)}function CH(e,t,n,r){eR.write(e,t,n,new Map(r))}function dR(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=xH(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 xH(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 RH(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 En(e){let t=mR(e.profile?.name),n=()=>{let r=[];t=mR(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 EH(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 IH(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?_(`pairwise-profile:${e.profile.name}`,n,()=>({...wH(e.profile?.metadata),...t})):n()}function EH(e,t){if(e.candidateIndex)return pR(e,t,-1);let n=[];for(let r=0;r<e.profiles.length;r+=1)r!==t&&n.push(r);return n}function IH(e,t){if(e.candidateIndex)return pR(e,t,t);let n=[];for(let r=t+1;r<e.profiles.length;r+=1)n.push(r);return n}function pR(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 mR(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 wH(e){return typeof e=="function"?e():e??{}}function LH(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=PH(e,{scope:i,minDeps:s}),l=Rn(a,u=>u.deps);return En({profiles:a,limit:r,filePattern:o,overrunFactor:5,candidateIndex:l,profile:{name:"similar-files"},compare:(u,d)=>MH(u,d,n,c)})}function PH(e,t){let{scope:n,minDeps:r}=t,i=qe(e,n),{universalDeps:o,distinctiveDeps:s}=DH(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 DH(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 MH(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=wr(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 Lr(e){let t=[],n=[],r=[];for(let l of e.primitiveGroups)l.values.length!==0&&fR(l.bucket,n,r).push(`${l.reasonPrefix}: ${l.values.join(", ")}`);for(let l of e.nameGroups)TH(l.names,l.label,e.genericWords,e.stripPrefixes??[],t,fR(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 Wc(e,t){if(e.size===0||t.size===0)return 0;let i=Qt(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(wr(e,t),i)}function Pr(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 Vc(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 be(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function gt(e){return[...e].sort()}function TH(e,t,n,r,i,o){let s=[],a=[];for(let c of e)kH(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 kH(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 fR(e,t,n){return e==="generic"?t:n}function Rs(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=zt(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 En({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-component-duplicates"},compare:(d,m)=>AH(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 AH(e,t,n){let r=Qt(e.tokens,t.tokens);if(r.size<6||!FH(r))return null;let i=wr(e.tokens,t.tokens);if(i<n)return null;let o=be(r,"component:"),s=be(r,"native:"),a=be(r,"prop:"),c=be(r,"event:"),l=be(r,"binding:"),u=NH({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:gt(r),sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l,evidenceClass:u.evidenceClass,actionTier:u.actionTier,evidenceClassReasons:u.reasons,recommendation:u.recommendation,uniqueToA:gt(st(e.tokens,t.tokens)).slice(0,25),uniqueToB:gt(st(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.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("native:")||r.startsWith("jsx:"))&&(n+=1);return Pr([{name:"component",count:t},{name:"shape",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{shape:4},reason:"shared JSX structure"}]).pass}function NH(e){return Lr({genericWords:OH,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:_H})}function _H(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 OH=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 Es(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=zt(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 En({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-hook-candidates"},compare:(d,m)=>BH(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 BH(e,t,n,r){let i=Qt(e.tokens,t.tokens);if(i.size<r||!HH(i))return null;let o=Wc(e.tokens,t.tokens);if(o<n)return null;let s=be(i,"hook:"),a=be(i,"react-hook:"),c=be(i,"effect:"),l=be(i,"state:"),u=be(i,"request:"),d=be(i,"handler:"),m=be(i,"handler-verb:"),p=$H({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:gt(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:gt(st(e.tokens,t.tokens)).slice(0,25),uniqueToB:gt(st(t.tokens,e.tokens)).slice(0,25),reason:UH({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function $H(e){return Lr({genericWords:qH,stripPrefixes:GH,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:jH})}function jH(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 HH(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 Pr([{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 UH(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 qH=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"]),GH=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function Am(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 zt(e).reactProfiles({scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>zH(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 zH(e,t){let n=Math.max(80,Math.floor(t.minComponentLines/2)),r=Vc(e,KH({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=WH(e),c=VH(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:YH(c,a),reasons:i,loc:e.loc}}function KH(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 WH(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=>XH.has(m))>=0,s=n.some(m=>JH.has(m));if(gR(r)||gR(e.name))return"component";let c=QH.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 gR(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&hR.has(t.at(-1))?!0:[...hR].some(n=>e.endsWith(ZH(n)))}function VH(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 YH(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 JH=new Set(["component","components","panel","panels","partial","partials"]),hR=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"]),XH=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),QH=new Set(["page","route","screen"]);function ZH(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Is(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=eU(e,{scope:o,minTokens:r,scanLimit:s}),u=Rn(l,d=>d.tokens);return En({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-component-duplicates"},compare:(d,m)=>nU(d,m,n),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function eU(e,t){return zt(e).vueProfiles({scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:tU(n)}))}function tU(e){return e.totalLines}function nU(e,t,n){let r=Qt(e.tokens,t.tokens);if(r.size<6||!rU(r))return null;let i=wr(e.tokens,t.tokens);if(i<n)return null;let o=be(r,"component:"),s=be(r,"prop:"),a=be(r,"event:"),c=be(r,"directive:"),l=be(r,"slot:"),u=be(r,"id:"),d=iU({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:gt(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:gt(st(e.tokens,t.tokens)).slice(0,25),uniqueToB:gt(st(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function rU(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 Pr([{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 iU(e){return Lr({genericWords:sU,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:oU})}function oU(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 sU=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 ws(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=zt(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 En({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-composable-candidates"},compare:(d,m)=>aU(d,m,n,r),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function aU(e,t,n,r){let i=Qt(e.tokens,t.tokens);if(i.size<r||!uU(i))return null;let o=Wc(e.tokens,t.tokens);if(o<n)return null;let s=be(i,"composable:"),a=be(i,"store:"),c=be(i,"reactivity:"),l=be(i,"lifecycle:"),u=be(i,"request:"),d=be(i,"function:"),m=be(i,"function-verb:"),p=be(i,"template-binding:"),f=be(i,"template-event:"),g=cU({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:gt(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:gt(st(e.tokens,t.tokens)).slice(0,25),uniqueToB:gt(st(t.tokens,e.tokens)).slice(0,25),reason:dU({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function cU(e){return Lr({genericWords:mU,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:lU})}function lU(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 uU(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 Pr([{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 dU(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 mU=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 Fm(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 zt(e).vueProfiles({scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>pU(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 pU(e,t){let n=Vc(e,fU(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=gU(e.file),a=hU(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:yU(a,s),reasons:r,loc:c}}function fU(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 gU(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(r=>bU.has(r))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function hU(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 yU(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 bU=new Set(["landing","page","pages","route","routes","view","views"]);function SU(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=qe(e,i),c=LU(a,o,s);if(c.length===0)return[];let l=vU(c);return l.length<2?[]:wU(RU(l,n,r),r)}function vU(e){let t=CU(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 CU(e){let{nodeFreq:t,tailFreq:n}=xU(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 xU(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 RU(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=EU(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 EU(e,t,n){if(!IU(e.filtered,t.filtered))return null;let{distance:r,ops:i}=PU(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:DU(e.original,t.original),commonSuffix:MU(e.original,t.original)}}function IU(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function wU(e,t){let n=[];for(let r of e)if(n.some(o=>yR(r.chainA,o.chainA)&&yR(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function LU(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;bR(e,o,[o],new Set([o]),t,n,r,500)}return r}function bR(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),bR(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 PU(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 DU(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 MU(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 yR(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function Zt(e){let t=TU(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=Pe(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?_(`candidate-pipeline:${e.profile.name}`,n,()=>({...kU(e.profile?.metadata),...t})):n()}function TU(e){return{pipeline:e,loadedCandidates:0,filteredCandidates:0,scannedCandidates:0,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:!1,resultLimitApplied:!1}}function kU(e){return typeof e=="function"?e():e??{}}function Ls(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new q(e);return Zt({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)=>AU(c,l.get(c.symbolId)??[],i),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function AU(e,t,n){let r=new Set(t.map(l=>l.symbol));if(r.size<n)return null;let i=BU(r,t),o=$U(r,i);if(o.length<2)return null;let s=jU(o,i);if(s.length===0)return null;let a=M(e.symbol),c=FU(a,r.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:ce(e),totalCallees:r.size,extractionKind:c.extractionKind,actionTier:"signal",evidenceReasons:c.evidenceReasons,recommendation:c.recommendation,clusters:s}}function FU(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=NU(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 NU(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=_U(e);return OU.has(r)?`caller verb suggests orchestration: ${r}`:null}function _U(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 OU=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function BU(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 $U(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 jU(e,t){return e.filter(n=>n.size>=3).map(n=>HU(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function HU(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(M),isolation:s}}import{posix as io}from"path";import{spawnSync as UU}from"child_process";import{createHash as qU}from"crypto";import{existsSync as GU}from"fs";import{dirname as SR,join as zU}from"path";import{fileURLToPath as KU}from"url";var xR=Xn("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),vR=Dt({kind:"consumer-file-usage",invalidation:Qe("consumer-file-usage"),serialize:nq,deserialize:rq});function Kn(e,t){return{forDefinitions(n,r){return WU(e,t,n,r)}}}function Wn(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 Jc(e,t,n){return ER(e,t,n).partition}function WU(e,t,n,r){let i=RR(n.length),o=ke()?Pn(e):null,s=o?VU(n,r,o):void 0,a=s?{workIdentity:s,workOutcome:"computed"}:{};return _("consumer-evidence.product",()=>{let c=_("consumer-evidence.provenance",()=>YU(e,t,n,r),()=>({...a,definitions:n.length,semantic:r.semantic,sourceFallback:r.sourceFallback!==!1})),l=new Map;i={...i,...c.counters};let u=JU(n,c.sources);return _("consumer-evidence.classify",()=>{let d=XU(e,n,c.sources,u);for(let m of n){let p=d.get(m.symbolId)??ZU();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 VU(e,t,n){let r=qU("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 RR(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function YU(e,t,n,r){let i=RR(n.length),o=new Map;return Nm(o,i,"indexed",t.crossFileCallerMap(n,{semantic:!1})),r.semantic&&Nm(o,i,"semantic",mr(e,n)),r.sourceFallback!==!1&&Nm(o,i,"source-fallback",t.sourceFallbackCallerFiles(n)),i.totalFiles=[...o.values()].reduce((s,a)=>s+a.size,0),{sources:o,counters:i}}function JU(e,t){return{definitions:e.length,consumerFiles:[...t.values()].reduce((n,r)=>n+r.size,0),nativeAttempted:!1,nativeUsed:!1,nativeReason:"not-attempted"}}function Nm(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 XU(e,t,n,r){let i=uq(e,t,n,r);return i||QU(e,t,n)}function QU(e,t,n){let r=new Map;for(let i of t){let o=n.get(i.symbolId)??new Map;r.set(i.symbolId,ER(e,i,[...o.keys()],o))}return r}function ER(e,t,n,r=new Map){let i=[],o=0,s=0,a=W(t.symbol),c=[];for(let l of n){let u;iq(e,l,t.relativePath,a)?(o++,u="reexport-only"):_m(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 ZU(){return{partition:{realConsumers:[],barrelConsumers:0,importOnlyConsumers:0},files:[]}}function _m(e,t,n){if(!n)return!1;let r=de(t);if(!r)return!1;let i=xR.get(e,t,()=>IR(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function IR(e,t,n){let r=tr(e).forFile(t,{text:!0,ast:!0}),i=r.text;if(!i)return tq();let o=Ht(e,t,i),s=vR.read(e,t,o);if(s)return s;let a=eq(r.ast,n);return vR.write(e,t,o,a),a}function eq(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 tq(){return{importedLeaves:new Set,usedLeaves:new Set}}function nq(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function rq(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 iq(e,t,n,r){if(!r)return!1;let i=tr(e).forFile(t,{lines:!0,reexports:!0}),o=i.lines??[];if(o.length===0)return!1;let s=i.reexports??[];return wR(o,s,r)}function wR(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 oq="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY",sq="SCIP_QUERY_NATIVE_KERNELS_BIN",aq="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY_MIN_FILES",CR=1e3,cq=5e3,lq=64*1024*1024,Yc;function uq(e,t,n,r){let i=process.env[oq]?.toLowerCase();if(i!=="1"&&i!=="true")return r.nativeReason=i==="0"||i==="false"?"disabled":"opt-in-required",null;if(r.consumerFiles<yq())return r.nativeReason="below-threshold",null;let o=bq();if(!o)return r.nativeReason="binary-missing",null;r.nativeAttempted=!0;let s=dq(e,t,n),a=UU(o,["consumer-classify"],{input:JSON.stringify(s),encoding:"utf8",timeout:cq,maxBuffer:lq});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=pq(c,t);return l?(r.nativeUsed=!0,r.nativeReason="used",l):(r.nativeReason="invalid-response",null)}catch{return r.nativeReason="invalid-json",null}}function dq(e,t,n){let r=new Map,i=[];for(let a of t){let c=W(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=de(a);if(l){let d=xR.get(e,a,()=>IR(e,a,l));o[a]={imported_leaves:[...d.importedLeaves],used_leaves:[...d.usedLeaves]}}let u=mq(e,a,c);u.length>0&&(s[a]=u)}return{definitions:i,file_usages:o,reexport_only_leaves:s}}function mq(e,t,n){if(n.size===0)return[];let r=tr(e).forFile(t,{lines:!0,reexports:!0}),i=r.lines??[],o=r.reexports??[];return i.length===0||o.length===0?[]:[...n].filter(s=>wR(i,o,s))}function pq(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=fq(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 fq(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(gq)||!hq(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 gq(e){return e==="indexed"||e==="semantic"||e==="source-fallback"}function hq(e){return e==="real"||e==="reexport-only"||e==="import-only"}function yq(){let e=process.env[aq];if(!e)return CR;let t=Number(e);return Number.isFinite(t)&&t>=0?t:CR}function bq(){if(Yc!==void 0)return Yc;let e=process.env[sq],t=process.platform==="win32"?"scip-query-kernels.exe":"scip-query-kernels";return Yc=[...e?[e]:[],...Sq().map(r=>zU(r,"target","release",t))].find(r=>GU(r))??null,Yc}function Sq(){let e=new Set,t=SR(KU(import.meta.url));for(let n=0;n<5;n++)e.add(t),t=SR(t);return[...e]}var vq=20,Cq=1,xq=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"]]),Rq=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),Eq=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 Iq(e,t={}){let n=$m(t.limit,vq),r=$m(t.minConsumers,Cq),i=new q(e),o=i.fileDependencyGraph(t.scope),s=zq(ae(e,{includeIgnored:!1})),a=Vq(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?wq(e,i,t.target):Lq(e,t.scope,t.scanLimit)).map(u=>Pq(e,i,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=r||t.target).sort(Gq).slice(0,n)}function wq(e,t,n){let r=Tq(e,n);if(r)return[TR(r)];let i=le(e,n);if(!i)return[];let o=t.definitionsForFile(i.relativePath).find(s=>s.symbolId===i.symbolId);return o?[kq(o)]:[{unit:{kind:"symbol",file:i.relativePath,shortName:M(i.symbol),symbol:i.symbol,startLine:i.startLine,endLine:i.endLine}}]}function Lq(e,t,n){let r=ae(e,{scope:t,includeIgnored:!1}),i=$m(n,r.length);return r.slice(0,i).map(o=>TR(o))}function Pq(e,t,n,r,i,o,s){let a=r.definition?Dq(e,t,r.definition,i.semantic):Mq(n,r.unit.file),c=r.definition?a.length>0?"exact":"none":a.length>0?"file-level":"none",l=r.unit.file,u=sn(io.dirname(l)),d=Fq(a),m=Aq(u),p=Hm([...LR(u),...d?LR(d):[]]),f=Nq(r.unit,u,d,a),g=_q(f,r.unit,u,d,a,o,s),h=Hq(r.unit,c,d,a,u,g.whyNoSuggestedHome),b=Uq(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:qq(f,g.suggestedHome,c)}}function Dq(e,t,n,r){let i=Wn(Kn(e,t).forDefinitions([n],{semantic:r!==!1,sourceFallback:!0}));return _R(i.get(n.symbolId)??[])}function Mq(e,t){let n=[];for(let[r,i]of e.entries())r!==t&&i.has(t)&&n.push(r);return _R(n)}function Tq(e,t){let n=zs(t),r=ae(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 kq(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:M(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function TR(e){return{unit:{kind:"file",file:e,shortName:io.basename(e)}}}function Aq(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:jm(i)})}return t}function LR(e){return e==="."?[]:kR(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function jm(e){return Hm(kR(e).map(({marker:t})=>t))}function kR(e){let t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){let i=xq.get(t[r]);i&&n.push({marker:i,prefix:t.slice(0,r+1).join("/")})}return n}function Fq(e){if(e.length===0)return null;let t=e.map(r=>sn(io.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 Nq(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":DR(n,"package")?"package-level-shared":DR(n,"app")?"app-level-shared":MR(n,["feature","domain","module"])||MR(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function _q(e,t,n,r,i,o,s){let a=Oq(e,r);if(a)return Dr(a);let c=Kq(t.file),l=Bq(e,n,c,i,s);if(l)return l;let u=r;if(sn(n)===sn(u))return Dr(`${n} is already the nearest common owner for its consumers.`);let d=$q(u,n,c,s);return d||jq(u,n,c,o,s)}function Oq(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 Bq(e,t,n,r,i){if(e==="same-file"){let o=r[0]??null;return o?Om(o):Dr("No same-file consumer path was available.")}if(e==="sibling-folder"&&r.length===1){let o=sn(io.dirname(r[0])),s=NR(t,n,o,i);return s?Dr(s):Om(o)}return null}function $q(e,t,n,r){return Jq(e)?AR(e,t,n,r,`Nearest shared owner ${e} is outside source root ${n}.`):null}function jq(e,t,n,r,i){if(e===".")return Dr("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:Dr(`${o} does not exist in the indexed project.`)}function AR(e,t,n,r,i){if(!FR(e,n))return Dr(i);let o=NR(t,n,e,r);return o?Dr(o):Om(e)}function Om(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function Dr(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function Hq(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 Uq(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 qq(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 Gq(e,t){return PR(t)-PR(e)||e.candidatePath.localeCompare(t.candidatePath)}function PR(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 zq(e){let t=new Set(["."]);for(let n of e){let r=sn(io.dirname(n));for(;!t.has(r)&&(t.add(r),r!==".");)r=sn(io.dirname(r))}return t}function Kq(e){let t=Bm(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function FR(e,t){let n=sn(e),r=sn(t);return r==="."||n===r||n.startsWith(`${r}/`)}function Wq(e,t,n){let r=Bm(e),i=Bm(t);return(FR(e,t)?r.slice(i.length):r).some(s=>n.has(s.toLowerCase()))}function NR(e,t,n,r){return sn(e)===sn(n)||!Wq(e,t,r)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function Vq(...e){let t=new Set(Eq);for(let n of e)for(let r of n??[]){let i=Yq(r);i&&t.add(i)}return t}function Yq(e){let t=e.trim().toLowerCase();return t===""?null:t}function DR(e,t){return jm(e).includes(t)}function MR(e,t){let n=jm(e);return t.some(r=>n.includes(r))}function Jq(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?Rq.has(n):!1}function sn(e){let t=zs(e);return t===""?".":t}function Bm(e){let t=zs(e);return t==="."?[]:t.split("/").filter(Boolean)}function $m(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function _R(e){return Hm([...e]).sort((t,n)=>t.localeCompare(n))}function Hm(e){return[...new Set(e)]}function Um(e,t,n={}){return OR(e,t,n).rows}function Xq(e,t,n={}){return OR(e,t,n)}function OR(e,t,n){let{maxDepth:r=5,scope:i}=n,o=r===Number.MAX_SAFE_INTEGER,s=o?null:500,a=le(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=jr(e,d,{...o?{}:{limit:s+1},semanticEvidence:ue});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 Qq(e,y,i,v)){let E=`${C.file}|${C.shortName}`;if(C.symbolId!==null){if(l.has(C.symbolId))continue;l.add(C.symbolId)}else if(u.has(E))continue;u.add(E),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 Qq(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 Zq(e,t,n)){if(o.has(u))continue;let d=z(e,u),m=d.length>0?We(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=Nr(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:M(u.symbol),file:u.file,symbolMatch:null});continue}if(d.symbolId===t.symbolId||e.isIgnored(d.relativePath)||!eG(d))continue;let m=`${d.symbolId}|${d.relativePath}`;l.has(m)||(l.add(m),c.push({symbolId:d.symbolId,symbol:d.symbol,shortName:M(d.symbol),file:d.relativePath,symbolMatch:d}))}return c}function Zq(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 eG(e){if(e.symbol.startsWith("scip-clojure ")||de(e.relativePath)==="clojure")return!0;let t=Kt(e.symbol);return t==="method"||t==="type"||e.symbol.endsWith("().")}function $R(e,t){let n=Ct(t),r=[],i="complete",o=K(n);o==="entry"&&Vn(r,"operational-root","structural entrypoint path"),o==="worker"&&Vn(r,"operational-root","worker launch convention"),Ed(n)&&Vn(r,"operational-root","framework-discovered entrypoint"),tG(e,n)&&Vn(r,"operational-root","configured entry root");let s=!1;try{s=Bn(e,n),s&&Vn(r,"published-api","package manifest export");for(let a of Bb(e,n))Vn(r,"operational-root",a)}catch(a){i="partial",Vn(r,"metadata-unavailable",`package metadata unavailable: ${BR(a)}`)}try{let a=ut(e.config.projectRoot,n,{maxBytes:8388608,inputKind:"change-surface source"});nG(a)&&Vn(r,"operational-root","module contains a direct-execution process guard")}catch(a){i="partial",Vn(r,"metadata-unavailable",dt(a)?"indexed source file is unavailable on disk":`source metadata unavailable: ${BR(a)}`)}return{operationalRoot:r.some(a=>a.kind==="operational-root"),publishedApi:s,coverage:i,reasons:r}}function tG(e,t){let n=e.config.entryRoots;return n?n.files?.some(r=>Ct(r)===t)?!0:n.pathPrefixes?.some(r=>t.startsWith(Ct(r)))??!1:!1}function nG(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 Vn(e,t,n){e.some(r=>r.kind===t&&r.detail===n)||e.push({kind:t,detail:n})}function BR(e){return e instanceof Error?e.message:String(e)}function qm(e,t,n={}){let r=Mt(e,t);if(!r)return null;let i=rG(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=0,a=iG(e,i.relative_path),c=$R(e,i.relative_path),l=n.semantic===!1?new Map:mr(e,a);for(let u of a){let d=oG(e,i,u,l.get(u.symbolId)??new Set);s+=d;let m=sG(d),p=[...c.reasons,...d>0?[{kind:"external-consumers",detail:`${d} external consumer${d===1?"":"s"}`}]:[]];o.push({symbol:u.symbol,shortName:M(u.symbol),startLine:u.startLine,endLine:u.endLine,externalConsumers:d,externalConsumerRiskLevel:m,riskLevel:aG(m,c),riskReasons:p})}return{file:i.relative_path,symbols:o,totalExternalConsumers:s,fileRisk:c}}function rG(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 iG(e,t){return new q(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function oG(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 sG(e){return e>10?"high":e>0?"medium":"low"}function aG(e,t){return e==="high"?"high":e==="medium"||t.operationalRoot||t.publishedApi||t.coverage==="partial"?"medium":"low"}function cG(e,t={}){let{scope:n,minLoc:r=1,maxDepth:i=5,scanLimit:o}=t,s=new q(e),a=lG(e,n,r,o),c=new Gm;for(let g of a)c.add(g);let l=[],u=[];a.length>0&&l.push(jR(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=HR(e,y);if(!x||e.isIgnored(x.relativePath)||tt(e,x.relativePath)||Ge(e,x.symbol,x.relativePath)||s.fileKind(x.relativePath)==="test"||s.hasSuppressionComment(x))continue;let v=dG(e,x,c);v.removable?S.push(uG(x,"cascade")):v.blockingFiles.length>0&&u.push({shortName:M(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(jR(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 lG(e,t,n,r){let i=ci(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:r,semantic:!1}),o=[];for(let s of i.symbols)s.kind==="dead-code"&&(tt(e,s.relativePath)||Ge(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:HR(e,s.symbol)}));return o}function uG(e,t){return{symbol:e.symbol,shortName:M(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function HR(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?z(e,n.relative_path).find(r=>r.symbol===t)??null:null}function dG(e,t,n){let r=yo(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 jR(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=z(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 Gm=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 oo}from"child_process";import{existsSync as mG}from"fs";import{basename as UR}from"path";function Xc(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 Ym="Unable to compute git diff.",pG={semanticConsumers:mr,sourceFallbackConsumers:Yo},Jm={resolveCommit:Bl,readBatch({projectRoot:e,resolvedBase:t,relativePaths:n}){let r=n.map(i=>`${t}:./${i}
|
|
345
|
+
`).join("");return oo("git",["cat-file","--batch"],{cwd:e,input:r,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"]})}};function Qc(e,t={}){let n=t.plan??so(e,t);return n.note?fG(n.note,n.changedFileLines):n.changedFiles.length===0?gG(n.changedFileLines):Zc(n.changedFiles,[KR(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function so(e,t={}){let{base:n="HEAD"}=t;try{let r=Bl(e.config.projectRoot,n),i=hG(e.config.projectRoot,r),o=i.changedFileLines,s=xG(e,o),a=RG(e,i.changedRanges);return{changedFileLines:o,changedFiles:s,changedRanges:a,renamedFiles:SG(e.config.projectRoot,r,s,i),note:o.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:Ym}}}function KR(e,t,n,r=[],i={}){let o=i.evidenceRuntime??pG,s=new q(e),a=new Set(n),c=Xc(r),l=[],u=new Map,d=t.flatMap(R=>s.definitionsForFile(R)).filter($G),m=d.filter(R=>IG(R,c)),p=LG(e,d,m,c),f=MG([...m,...p.definitions]).sort((R,w)=>R.relativePath.localeCompare(w.relativePath)||R.startLine-w.startLine),g=f.map(R=>R.symbolId),h=_G(e,g),b=OG(e,g,n),S=f.filter(R=>(h.get(R.symbolId)??0)===0),y=zR("semantic-consumers",S.length,()=>o.semanticConsumers(e,S)),x=y.values,v=S.filter(R=>(x.get(R.symbolId)?.size??0)===0),C=zR("source-fallback-consumers",v.length,()=>o.sourceFallbackConsumers(e,v)),E=C.values;for(let R of f)AG(e,R,a,l,u,x.get(R.symbolId)??new Set,E.get(R.symbolId)??new Set,h.get(R.symbolId)??0,b.get(R.symbolId)??new Set);return{changedSymbols:l,consumerEntries:[...u.entries()].map(([R,w])=>({file:R,symbols:[...w].sort()})),attributionNotes:p.notes,evidenceTiers:[y.status,C.status]}}function Zc(e,t){let n=new Map,r=t.flatMap(a=>a.changedSymbols),i=t.flatMap(a=>a.attributionNotes??[]),o=FG(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=BG(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:s,attributionNotes:i,evidenceTiers:o,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:s.length}}}function fG(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:ZR(),summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function gG(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:ZR(),summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function hG(e,t){let n=oo("git",["diff","--name-status","--find-renames",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864}),r=oo("git",["diff","--name-status","--find-renames","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),i=oo("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),o=oo("git",["diff","--unified=0",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),s=oo("git",["diff","--unified=0","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),a=vG([n,r]);return{changedFileLines:[...new Set([...a.changedFiles,...YR(i)])],changedRanges:XR([...GR(o),...GR(s)]),renamedFiles:a.renamedFiles,deletedFiles:a.deletedFiles}}function yG(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=Xm(i);if(s.state==="unavailable")throw new Error(`Base content unavailable for ${o}: ${s.reason}`);return s.state==="present"?s.content:null}function Xm(e,t=Jm){return VR(e.relativePath),Qm({projectRoot:e.projectRoot,base:e.base,relativePaths:[e.relativePath]},t).get(e.relativePath)??{state:"unavailable",reason:`Base-content lookup omitted ${e.relativePath}.`}}function Qm(e,t=Jm){for(let s of e.relativePaths)VR(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 zm(n,Km(s))}let i;try{i=t.readBatch({projectRoot:e.projectRoot,resolvedBase:r,relativePaths:n})}catch(s){return zm(n,Km(s))}let o;try{o=bG(i,n)}catch(s){return zm(n,`Malformed git cat-file batch output: ${Km(s)}`)}return new Map(n.map(s=>{let a=o.get(s)??null;return[s,a===null?{state:"absent"}:{state:"present",content:a}]}))}function Zm(e,t=Jm){let n=Qm({projectRoot:e.projectRoot,base:e.base,relativePaths:e.preloadPaths??[]},t);return r=>(n.has(r)||n.set(r,Xm({projectRoot:e.projectRoot,base:e.base,relativePath:r},t)),n.get(r)??{state:"unavailable",reason:`Base-content reader omitted ${r}.`})}function WR(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 VR(e){Dn(e)}function zm(e,t){return new Map(e.map(n=>[n,{state:"unavailable",reason:t}]))}function Km(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 bG(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 SG(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)||!mG(`${e}/${a}`))continue;let c=s.filter(d=>!o.has(d)).filter(d=>UR(d)===UR(a));if(c.length===0)continue;let l=ut(e,a),u=c.map(d=>({from:d,to:a,similarity:CG(yG({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 vG(e){let t=new Set,n=new Map,r=new Set;for(let i of e.flatMap(o=>YR(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 CG(e,t){let n=new Set(qR(e)),r=new Set(qR(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 qR(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function YR(e){return e.split(`
|
|
346
|
+
`).map(t=>t.trim()).filter(t=>t.length>0)}function xG(e,t){let n=JR(e),r=[];for(let i of t){let o=n(i);o&&!e.isIgnored(o)&&r.push(o)}return r}function RG(e,t){let n=JR(e),r=[];for(let i of t){let o=n(i.file);o&&!e.isIgnored(o)&&r.push({...i,file:o})}return XR(r)}function JR(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 GR(e){let t=[],n=null;for(let r of e.split(`
|
|
348
|
+
`)){if(r.startsWith("+++ ")){n=EG(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 EG(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function XR(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 IG(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(r=>ep(e.startLine,e.endLine,r.startLine,r.endLine))}function wG(e,t,n){let r=new Map,i=[],o=QR(e),s=TG(n);for(let a of t){let c=o.get(a.file)??[];if(c.some(d=>ep(d.startLine,d.endLine,a.startLine,a.endLine)))continue;let l=s.get(a.file)??[],u=kG(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(Wm(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(Wm(a,"nearest-preceding"));continue}}i.push(Wm(a,"unattributed"))}return{definitions:[...r.values()],notes:i}}function LG(e,t,n,r){let i=QR(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=>ep(m.startLine,m.endLine,d.startLine,d.endLine))||o.push(d);o.some(d=>d.file===c)&&s.push(...PG(e,c))}return wG(t,o,s)}function PG(e,t){let n=te(e,t);return n?n.rootNode.namedChildren.filter(DG).map(r=>({file:t,startLine:r.startPosition.row,endLine:r.endPosition.row})).filter(r=>r.endLine>=r.startLine):[]}function DG(e){return e.endPosition.row<e.startPosition.row?!1:!new Set(["import_statement","comment"]).has(e.type)}function MG(e){let t=new Map;for(let n of e)t.set(n.symbolId,n);return[...t.values()]}function QR(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 TG(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 kG(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 Wm(e,t){return{file:e.file,startLine:e.startLine,endLine:e.endLine,method:t}}function ep(e,t,n,r){return e<=r&&n<=t}function AG(e,t,n,r,i,o,s,a,c){let l=Math.max(a,o.size,s.size);if(!jG(t,l))return;let u=M(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)Vm(e,n,i,d,u);for(let d of o)Vm(e,n,i,d,u);for(let d of s)Vm(e,n,i,d,u)}function zR(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:NG(r)}}}}function FG(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 ZR(){return[{tier:"semantic-consumers",state:"complete",attemptedSymbols:0},{tier:"source-fallback-consumers",state:"complete",attemptedSymbols:0}]}function NG(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 _G(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 OG(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 Vm(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 BG(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function $G(e){return!(Ce(e.symbol)||e.parentTypeName!==null&&!mt(e.symbol))}function jG(e,t){return mt(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}var HG=5;function UG(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??so(e,{base:n}),d={available:u.note!==Ym,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 q(e),p=new Set(u.changedFiles),f=new Map(u.renamedFiles.map(E=>[E.to,E.from]));if(t.baseContentAt&&t.baseContentResultAt)throw new Error("Specify only one of baseContentAt or baseContentResultAt.");let g=t.baseContentResultAt?t.baseContentResultAt:t.baseContentAt?YG(t.baseContentAt):Zm({projectRoot:e.config.projectRoot,base:n,preloadPaths:WR(u)}),h=VG(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(E=>({def:E,callees:Kc((S.get(E.symbolId)??[]).map(R=>R.symbol))})),x=ro(e),v,C=()=>(v??=x.calleeIndex({minCallees:Math.min(3,i),scanLimit:c,semantic:l}),v);for(let{def:E,callees:R}of y){let w=M(E.symbol);if(R.size<i){d.skipped.push({helperShortName:w,helperFile:E.relativePath,reason:`fewer than ${i} meaningful callees \u2014 too small to score`});continue}let I=C(),A=WG(R,I);if(A===0){d.skipped.push({helperShortName:w,helperFile:E.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let k=JG(e,E.symbolId);if(k.length===0){d.skipped.push({helperShortName:w,helperFile:E.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}d.helpersChecked+=1;let T=qG({candidateIndex:I,changed:p,helperCallees:R,helperFile:E.relativePath,helperSymbol:E.symbol,minContainment:r,minSiteCoverage:o,migratedFiles:k});T.length!==0&&(T.sort((L,F)=>eE(F.migrationScope)-eE(L.migrationScope)||F.containment-L.containment||F.siteCoverage-L.siteCoverage||L.file.localeCompare(F.file)),d.findings.push({helperSymbol:E.symbol,helperShortName:w,helperFile:E.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:R.size,specificHelperCalleeCount:A,migratedFiles:k.sort(),leftovers:T.slice(0,HG)}))}return d.findings.sort((E,R)=>(R.leftovers[0]?.containment??0)-(E.leftovers[0]?.containment??0)||E.helperFile.localeCompare(R.helperFile)),d.findings=d.findings.slice(0,a),d}function qG(e){let t=[],n=GG(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=zx(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=zG(n,o.symbol,o.file);t.push({symbol:o.symbol,shortName:M(o.symbol),file:o.file,...l,containment:s,siteCoverage:c,uniqueSiteCalleeCount:Math.max(0,o.callees.size-a.length),sharedCallees:a.map(M).sort()})}return t}function eE(e){return e==="same-scope"?2:e==="unknown"?1:0}function GG(e,t,n){let r=new Set([...tp(t),...np(W(e))]);for(let i of n)for(let o of tp(i))r.add(o);return r}function zG(e,t,n){let r=new Set([...tp(n),...np(W(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 KG=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 tp(e){return np(e.replace(/\.[^.]+$/,""))}function np(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!KG.has(t))}function WG(e,t){let n=0;for(let r of e)(t.docFreq.get(r)??0)<=t.ubiquityThreshold&&(n+=1);return n}function VG(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${Ne(o.leaf)}\\b`).test(a.content))&&i.push(o)}return{definitions:i}}function YG(e){return t=>{let n=e(t);return n===null?{state:"absent"}:{state:"present",content:n}}}function JG(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 XG}from"child_process";var oE=2e3,el=50,QG=64,ZG=8,ez=3,tz=2160*60*60,nz=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,rz=3,iz=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,oz=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function sz(e){let t=Le(e,{clearGroups:["whole-project"]});return(n,r,i)=>{let o=i??rp(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 tl(e){let t=Le(e,{clearGroups:["whole-project"]});return(n,r,i,o)=>{let s=o??rp(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 az=tl("git-commit-history");function an(e,t={}){let n=t.historyMode??"bounded",r=t.head;return{capability:i=>cz(e,i,r),commitHistory:()=>Ps(e,n,r),fileChurn:()=>dz(e,n,r),changeAmplification:()=>mz(e,n,r),trackedFiles:()=>fz(e,r),fileAddRecords:()=>hz(e,n,r),coChangePairs:(i={})=>Rz(e,i,n,r),coChangePairsForFiles:(i,o={})=>cE(e,i,o,n,r),directionalCoChangePairsForFiles:(i,o={})=>Ez(e,i,o,n,r)}}function Ps(e,t="bounded",n){return az(e,ao(t),(r,i)=>lz(r,i,t),n)}function cz(e,t,n){let r=n??rp(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 rp(e){try{return In(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function In(e,t){return XG("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"})}function lz(e,t,n){let r;try{r=In(e,["log","--no-merges","--name-only",...nl(n),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}return{head:t,...sp(r,el)}}function uz(e){return nz.test(e.subject)}function dz(e,t,n){let r=Ps(e,t,n);if(!r)return null;let i=new Map;for(let o of r.commits){let s=uz(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 mz(e,t,n){let r=Ps(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:tE(i,.5),p90FilesPerCommit:tE(i,.9),commitsAnalyzed:i.length}}function tE(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var pz=sz("git-tracked-files");function fz(e,t){return pz(e,n=>{try{let r=In(n,["ls-files"]);return new Set(r.split(`
|
|
367
|
+
`).map(i=>i.trim()).filter(i=>i!==""))}catch{return null}},t)}var gz=tl("git-file-adds"),nE="__git__/file-adds",rE=Dt({kind:"git-file-adds",invalidation:Qe("git-file-adds"),serialize:bz,deserialize:Sz});function sE(e){return an(e).fileAddRecords()}function hz(e,t,n){let r=ao(t);return gz(e,r,(i,o)=>yz(e,i,o,t),n)}function yz(e,t,n,r){let i=rE.read(e,iE(r),n);if(i)return i;let o=vz(t,r);return o&&rE.write(e,iE(r),n,o),o}function bz(e){return JSON.stringify([...e.entries()])}function Sz(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 vz(e,t){let n;try{n=In(e,["log","--no-merges","--find-renames","--name-status",...nl(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=Cz(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 Cz(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 aE=tl("git-co-change-pairs"),xz=tl("git-directional-co-change-pairs");function Rz(e,t,n,r){let i=`all\0${ao(n)}\0${ip(t)}`,o=aE(e,i,()=>{let s=Ps(e,n,r);return s?op(s,t):null},r);return o&&[...o]}function cE(e,t,n,r,i){if(t.size===0)return[];let o=`files\0${ao(r)}\0${lE(t)}\0${ip(n)}`,s=aE(e,o,()=>{let a=Ps(e,r,i);return a?op(a,n,t):null},i);return s&&[...s]}function Ez(e,t,n,r,i){if(t.size===0)return[];let o=n.maxFilesPerCommit??el;if(t.size>QG)return cE(e,t,n,r,i);let s=`directional\0${ao(r)}\0${lE(t)}\0${ip({...n,maxFilesPerCommit:o})}`,a=xz(e,s,(c,l)=>{let u=Iz(c,l,t,o,r);return u?op(u,n,t):null},i);return a&&[...a]}function ip(e){let t=e.minTogether??4,n=e.minConfidence??.6,r=e.maxFilesPerCommit??el;return`${t}\0${n}\0${r}`}function lE(e){return[...e].sort().join("\0")}function op(e,t,n){let{minTogether:r=4,minConfidence:i=.6,maxFilesPerCommit:o=el}=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=Pz(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-tz;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:Mz(m.broadTogether,p),recency:x>0?"recent":"stale",subjectContext:Tz(m.subjects)})}return l.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),l}function Iz(e,t,n,r,i){let o;try{o=wz(e,i)}catch{return null}if(o.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:0};let s;try{s=In(e,["log","--no-merges","--format=%H",...nl(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=Lz(e,o,r);if(c.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:l};let u;try{u=In(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...c])}catch{return null}let d=sp(u,r);return{head:t,...d,newestAnalyzedAt:l}}function wz(e,t){return In(e,["log","--no-merges","--format=%H%x00%ct",...nl(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 nl(e){return e==="full"?[]:["-n",String(uE())]}function uE(){return ur(process.env.SCIP_QUERY_GIT_HISTORY_MAX_COMMITS)??oE}function ao(e){return e==="full"?"full":`bounded:${uE()}`}function iE(e){let t=ao(e);return t===`bounded:${oE}`?nE:`${nE}:${t}`}function Lz(e,t,n){for(let i=0;i<t.length;i+=20){let o=t.slice(i,i+20),s;try{s=In(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=sp(s,n);if(a.commits.length>0)return a.commits[0].timestamp}return 0}function sp(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 Pz(e){return e.length>=ZG?!0:Dz(e).size>=ez}function Dz(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 Mz(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function Tz(e){let t=new Set,n=[],r=[];for(let i of e){!r.includes(i)&&r.length<rz&&r.push(i);for(let o of kz(i))t.add(o);for(let o of i.match(iz)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:r,externalIssueLabelStatus:"unavailable"}}function kz(e){let t=new Set,n=oz.exec(e)?.[1]?.toLowerCase();return n&&t.add(Az(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 Az(e){return e==="feat"?"feature":e}var dE=/(?:^|\/)(?: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 Ds(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=an(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=qe(e),p=hE(e),f=_z(e,m,p),g=n.includeLinked===!0||l,h=[];for(let b of d){if(dE.test(b.fileA)||dE.test(b.fileB)||!mE(e,b.fileA)||!mE(e,b.fileB)||l&&!b.fileA.includes(t)&&!b.fileB.includes(t)||!l&&(K(b.fileA)==="test"||K(b.fileB)==="test"||jz(b.fileA,b.fileB)||Bz(b.fileA,b.fileB)))continue;let S=f(b.fileA,b.fileB);if(!g&&S)continue;let y=Fz(b.fileA,b.fileB),x=Nz(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 mE(e,t){return qt(e.config.projectRoot,t)}function Fz(e,t){let n=fE(e),r=fE(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=Xz(n.tokens,r.tokens).filter(c=>!Yz.has(c));return gE(e,t)||a.length>=2?(o(gE(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 Nz(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!Vz.has(t.partnerClass))return;let r=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${Qz(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 _z(e,t=qe(e),n=hE(e)){return(r,i)=>Hz(t,n,r,i)}var Oz=/(?:^|\/)(?:locales|i18n)\//i;function pE(e){return Oz.test(e)}function Bz(e,t){return pE(e)&&pE(t)?!0:$z(e,t)}function $z(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 jz(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 hE(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function Hz(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 Uz=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,qz=/(?:^|\/)(?:\.[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,Gz=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,zz=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,Kz=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,Wz=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,Vz=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),Yz=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 fE(e){let t=e.replace(/\\/g,"/"),n=new Set;return Uz.test(t)&&n.add("doc"),qz.test(t)&&n.add("config"),Gz.test(t)&&n.add("schema"),zz.test(t)&&n.add("script"),Kz.test(t)&&n.add("model"),Wz.test(t)&&n.add("view"),K(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:Jz(t)}}function gE(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 Jz(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 Xz(e,t){let n=new Set(t);return[...new Set(e.filter(r=>n.has(r)))].sort()}function Qz(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}function ol(e,t){let n=Zz(e,t)??eK(e,t)??tK(e,t)??nK(e,t);return rK(e,n,t)}function Zz(e,t){let n=-1,r=null;for(let i=0;i<=t;i+=1){let o=ap(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(ap(e[i]??"")===r)return{start:n,end:i+1};return{start:n,end:e.length}}function ap(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function eK(e,t){if(!rl(e[t]??""))return null;let n=t;for(;n>0&&rl(e[n-1]??"");)n-=1;let r=t+1;for(;r<e.length&&rl(e[r]??"");)r+=1;return{start:n,end:r}}function rl(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function tK(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if(il(o)!==null)break;if(cp(o)!==null)return null;n-=1}if(n<0)return null;let r=il(e[n]??"");if(r===null)return null;let i=n+1;for(;i<e.length;){let o=e[i]??"",s=il(o);if(s!==null){if(s<=r)break;i+=1;continue}if(cp(o)!==null)break;i+=1}return{start:n,end:i}}function il(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function nK(e,t){let n=e[t]??"";if(bE(n)||n.trim().length===0)return{start:t,end:t+1};let r=t;for(;r>0&&yE(e[r-1]??"");)r-=1;let i=t+1;for(;i<e.length&&yE(e[i]??"");)i+=1;return{start:r,end:i}}function yE(e){return cp(e)===null}function cp(e){return e.trim().length===0?"blank":bE(e)?"heading":ap(e)?"fence":rl(e)?"table":il(e)!==null?"list":null}function bE(e){return/^#{1,6}\s+/.test(e.trim())}function rK(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 ui(e,t){return t.filter(n=>e.includes(n))}var iK=/<!--\s*scip-query:\s*snapshot\s*-->/i;function SE(e,t){if((e.config.docs?.snapshotPaths??[]).some(i=>Ir(i,t)))return!0;let r=X(e,t);return r.length>0&&iK.test(r)}var vE={classifyCitation:sK,citationContexts:aK,citationKindLabel:lK,citationRemediation:uK,referenceTargets:dK,hasLineAnchoredCitation:oK};function oK(e){return e.some(t=>(t.lineReferences?.length??0)>0)}function sK(e){let t=e.join(`
|
|
375
|
+
`).toLowerCase(),n=[],r=ui(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=ui(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=ui(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 aK(e,t,n){let r=X(e,t);if(!r&&!qt(e.config.projectRoot,t))return[];let i=r.split(/\r?\n/),o=n.flatMap(cK),s=[];for(let a=0;a<i.length;a+=1){let c=i[a]??"";o.some(l=>c.includes(l))&&s.push(ol(i,a))}return s}function cK(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 lK(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 uK(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 dK(e,t,n){let r=Xc(n),i=new Set;for(let o of t)mK(e,o,r.get(o)??[])&&i.add(o);return i}function mK(e,t,n){if(!pK.test(t)||!qt(e.config.projectRoot,t))return!0;if(n.length===0)return!1;let r=ut(e.config.projectRoot,t,{inputKind:"changed source file"}).split(/\r?\n/),i=fK(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 pK=/\.(?:[cm]?[jt]sx?)$/i;function fK(e){let t=new Set,n=!1;for(let r=0;r<e.length;r+=1){let i=e[r].trim();!n&&gK(i)&&(n=!0),n&&(t.add(r),i.endsWith(";")&&(n=!1))}return t}function gK(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}var CE=Dt({kind:"doc-path-evidence",invalidation:Qe("doc-path-evidence"),serialize:DK,deserialize:MK}),Ms=/\.(?:md|mdx|rst|txt)$/i;function hK(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var yK=3,bK=/([A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6})(?::([1-9][0-9]*))?\b/g;function SK(e,t={}){let{doc:n,limit:r=20,minCoupling:i=yK,includeSnapshotExcluded:o=!1}=t,s=RK(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&&!EK(e,c)||n!==void 0&&!qt(e.config.projectRoot,c))continue;let l=SE(e,c);if(l&&!o)continue;let{value:u,estimated:d}=vK(e,c,s.changeTimes.get(c)),m=CK(e,c),p=new Map,{resolved:f,broken:g,citations:h}=wK(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||Ms.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,...lp("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(E=>E>u).length;if(v===0)continue;let C=p.get(y);C?(C.evidence="both",C.coChanges=x,Object.assign(C,lp("both",m,C.citationContexts))):p.set(y,{file:y,evidence:"co-change",coChanges:x,changesSinceDocUpdate:v,...lp("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 vK(e,t,n){if(n&&n.length>0)return{value:Math.max(...n),estimated:!1};try{return{value:Math.floor(Vs(e.config.projectRoot,t).mtimeMs/1e3),estimated:!0}}catch(r){if(qt(e.config.projectRoot,t))throw r;return{value:0,estimated:!1}}}function CK(e,t){let n=X(e,t).slice(0,6e3);if(!n)return{docIntent:"unknown",reasons:["doc text unavailable"]};let r=`${t}
|
|
376
|
+
${n}`.toLowerCase(),i=ui(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=ui(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 lp(e,t,n=[]){let r=e==="co-change"||n.length===0?null:vE.classifyCitation(n);return{actionTier:xK(e,t.docIntent,r?.actionTier),docIntent:t.docIntent,docIntentReasons:t.reasons,...r?{citationKind:r.citationKind,citationKindReasons:r.reasons}:{}}}function xK(e,t,n){return t==="historical-note"?"support":n||(e==="co-change"?"signal":"direct")}function RK(e,t){let n=an(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=>Ms.test(m)),d=l.filter(m=>!Ms.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=>Ms.test(c)),everSeenInHistory:a,historyCommitCount:r.commits.length,tracked:i,trackedBySuffix:IK(i)}}function EK(e,t){return Ms.test(t)&&!hK(t)&&qt(e.config.projectRoot,t)}function IK(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 wK(e,t,n,r,i){let o=new Set,s=new Set,a=LK(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,xE(S).slice(0,3))}let b=u.get(g);b&&b.length>0&&m.set(f,up([...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 LK(e,t,n){let r=n;if(r===void 0&&(r=X(e,t),!r&&!qt(e.config.projectRoot,t)))return null;let i=Ht(e,t,r),o=CE.read(e,t,i);if(o)return o;let s=PK(r);return CE.write(e,t,i,s),s}function PK(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(bK)){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,up([...i.get(c)??[],l]));let u=ol(t,o);if(u.length===0)continue;let d=r.get(c)??[];d.push(u),r.set(c,xE(d).slice(0,3))}}return{candidates:[...n],contextsByCandidate:r,lineReferencesByCandidate:i}}function DK(e){let t={candidates:e.candidates,contextsByCandidate:[...e.contextsByCandidate.entries()],lineReferencesByCandidate:[...e.lineReferencesByCandidate.entries()]};return JSON.stringify(t)}function MK(e){try{let t=JSON.parse(e);if(!bf(t))return null;let n=Ol(t.candidates),r=kK(t.contextsByCandidate),i=TK(t.lineReferencesByCandidate);return!n||!r?null:{candidates:n,contextsByCandidate:new Map(r),lineReferencesByCandidate:new Map(i??[])}}catch{return null}}function TK(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],up(r)])}return t}function kK(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=Ol(n[1]);if(!r)return null;t.push([n[0],r])}return t}function xE(e){let t=[];for(let n of new Set(e))t.some(r=>AK(r,n))||t.push(n);return t}function up(e){return[...new Set(e)].sort((t,n)=>t-n)}function AK(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 FK}from"crypto";var NK=3;function Ts(e,t={}){let{scope:n,maxLoc:r=15,minLoc:i=NK,limit:o,scanLimit:s}=t,a=sE(e),c=_K(e,{scope:n,maxLoc:r,scanLimit:s}).map(u=>OK(e,u,a,i)).filter(u=>u!==null),l=IE(c);return o?l.slice(0,o):l}function EE(e){let t=wn(e);return Tn(t).replace(/\s+/g,"")}function IE(e){let t=new Map;for(let r of e){if(r.normalizedBody.length<8)continue;let i=$K(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(jK).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=RE(i)-RE(r);return s!==0?s:r.canonical.file.localeCompare(i.canonical.file)}),n}function _K(e,t){let n=He(e,{scope:t.scope}).filter(r=>r.isFunctionLike&&!e.isIgnored(r.relativePath)).filter(r=>!Qs(e,r.relativePath,r.startLine,"similar")).filter(r=>ce(r)<=t.maxLoc);return n.sort((r,i)=>ce(i)-ce(r)||r.relativePath.localeCompare(i.relativePath)),Pe(n,t.scanLimit)}function OK(e,t,n,r){let i=cn(e,t);if(!i||BK(i)<r)return null;let o=dp(e,t);return o?{symbol:t.symbol,shortName:M(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:ce(t),ageCommits:n?.get(t.relativePath)?.commitsAgo??null,normalizedBody:o}:null}function dp(e,t){let n=cn(e,t);return n&&EE(n)||null}function cn(e,t){let n=Q(e,t.relativePath);return n.length===0?null:n.slice(t.startLine,t.endLine+1).join(`
|
|
377
|
+
`)}function wn(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 BK(e){return wn(e).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0).length}function $K(e){return FK("sha256").update(e).digest("hex").slice(0,16)}function jK(e,t){let n=e.ageCommits??-1;return(t.ageCommits??-1)-n||e.file.localeCompare(t.file)||e.startLine-t.startLine}function RE(e){return e.functions.reduce((t,n)=>t+n.loc,0)}var HK=new Set(mn());function UK(e,t={}){let{includeHomonyms:n=!1,limit:r}=t,i=sl(e,t).filter(o=>o.relationship==="divergent"||n&&o.relationship==="homonym");return r?i.slice(0,r):i}function sl(e,t={}){let{scope:n,minSimilarity:r=.3,scanLimit:i}=t,o=zK(e,{scope:n,scanLimit:i});return PE(o,{minSimilarity:r,isDelegatePair:pW(e)}).filter(s=>!s.members.some(a=>Qs(e,a.file,a.startLine,"twin")))}function PE(e,t={}){let n=t.minSimilarity??.3,r=t.isDelegatePair,i=e.filter(l=>!NE(l.leaf)&&!nW(l.leaf)&&K(l.file)!=="test"&&!Ze(l.symbol)&&!ME(l.symbol)&&!TE(l.symbol,l.leaf)),{recordsByLeaf:o,recordOrder:s}=_("twin-drift.group-by-leaf",()=>qK(i),()=>({records:i.length})),a=_("twin-drift.cluster-leaf-names",()=>DE([...o.keys()]),()=>({leaves:o.size}));return _("twin-drift.compare-clusters",()=>{let l=[];for(let u of a){let d=GK(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||!sW(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=QK(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(XK);if(!m){l.push({leaf:LE(u),relationship:f?"identical":"homonym",maxDivergence:0,members:h});continue}let b=m.similarity>=n?"divergent":"homonym";l.push({leaf:LE(u),relationship:b,maxDivergence:Math.round((1-m.similarity)*1e3)/1e3,members:h,...b==="divergent"?{firstDivergentTokens:ZK(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 qK(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 GK(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 zK(e,t){let n=_("twin-drift.load-definitions",()=>He(e,{scope:t.scope}).filter(o=>KK(o)&&!e.isIgnored(o.relativePath)).filter(o=>!Hi(o.relativePath)));_("twin-drift.sort-definitions",()=>n.sort((o,s)=>o.relativePath.localeCompare(s.relativePath)||o.startLine-s.startLine),()=>({definitions:n.length}));let r=Pe(n,t.scanLimit),i=_("twin-drift.select-candidates",()=>WK(r),()=>({scanned:r.length}));return _("twin-drift.build-records",()=>{let o=[];for(let s of i){let a=VK(e,s);a&&o.push(a)}return o},()=>({candidates:i.length,scanned:r.length}))}function KK(e){return e.isFunctionLike?e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&HK.has(e.kind):!0:!1}function WK(e){let t=e.filter(o=>o.leaf&&!NE(o.leaf)&&!Ze(o.symbol)&&!ME(o.symbol)&&!TE(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=DE([...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=>K(a.relativePath)==="test"))for(let a of s)i.add(a)}return e.filter(o=>i.has(o))}function VK(e,t){if(!t.leaf)return null;let n=cn(e,t);if(!n||!mt(t.symbol)&&!YK(n,t.leaf))return null;let r=Tn(wn(n)),i=r.replace(/\s+/g,"");if(!i||i.length<8)return null;let o=r.match(JK)??[];return o.length===0?null:{leaf:t.leaf,symbol:t.symbol,shortName:M(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:ce(t),normalizedBody:i,tokens:o,isThinForwarder:AE(r)}}function YK(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 JK=/[A-Za-z_$][A-Za-z0-9_$]*|\d+(?:\.\d+)?|[^\sA-Za-z0-9_$]/g;function XK(e){return{symbol:e.symbol,shortName:e.shortName,file:e.file,startLine:e.startLine,endLine:e.endLine,loc:e.loc}}function QK(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 ZK(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 DE(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)eW(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 eW(e,t){return e===t||e.toLowerCase()===t.toLowerCase()?!0:e.length<8||t.length<8||Math.abs(e.length-t.length)>2||tW(e.toLowerCase(),t.toLowerCase())/Math.max(e.length,t.length)<.8?!1:aW(e.toLowerCase(),t.toLowerCase(),2)}function tW(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;return r}function nW(e){return/^[A-Z][A-Z0-9_]*$/.test(e)||/^__[^_].*__$/.test(e)||rW.has(e.toLowerCase())}var rW=new Set(["main","row"]),iW=new Set(["app","component","components","feature","features","impl","index","lib","route","routes","shared","src","tsx","typescript","ui"]);function ME(e){return e.startsWith("rust-analyzer ")&&/\/(?:tests?|benches?)\//.test(e)}var oW=new Set(["default","new","reset"]);function TE(e,t){return e.startsWith("rust-analyzer ")&&oW.has(t.toLowerCase())}function sW(e,t){if(e.leaf.toLowerCase()!==t.leaf.toLowerCase()||e.leaf.length>4)return!0;let n=wE(e);return[...wE(t)].some(r=>n.has(r))}function wE(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&&!iW.has(n)))}function aW(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 kE(e){return AE(Tn(wn(e)))}function AE(e){let t=e.trim();if(!t||cW.test(t))return!1;let n=dW(t);return n.length===0||n.length>2?!1:uW(n[n.length-1])}var cW=/\b(?:if|else|for|while|switch|try|catch|do)\b/,lW=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^[\]]*\])*\((?:[^()]|\([^()]*\))*\)$/;function uW(e){let t=e.trim().replace(/^return\s+/,"").replace(/^await\s+/,"").replace(/;\s*$/,"").trim();return lW.test(t)}function dW(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 mW=3;function pW(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=FE(e,n,r,i,mW,new Set);return t.set(o,a),a}}function FE(e,t,n,r,i,o){if(i<=0||o.has(t.symbol)||(o.add(t.symbol),(un(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(pe(e,t.file).filter(c=>c.sourcePath&&(c.kind!=="namespace"||c.usedMembers.includes(n.leaf))).map(c=>c.sourcePath));if([...a].some(c=>Ke(c,n.file)))return!0;for(let c of r)if(!(c.symbol===t.symbol||c.symbol===n.symbol||!c.isThinForwarder)&&[...a].some(l=>Ke(l,c.file))&&FE(e,c,n,r,i-1,o))return!0;return!1}function NE(e){return e.startsWith("<")&&e.endsWith(">")}function LE(e){return[...e].sort()[0]}import{dirname as PW,isAbsolute as DW,relative as MW,resolve as TW}from"path";import{basename as _E,extname as OE}from"path";function al(e,t,n,r,i,o){let s=new Set;gW(e,t,n,r)&&s.add(i);for(let a of o)a.value&&fW(s,a.label,a.value);return[...s].slice(0,6)}function fW(e,t,n){let r=hW(n);t.endsWith("name")&&yW(r)&&e.add(`${t} has type-guard boundary shape`);for(let i of r){let o=bW.get(i);o&&e.add(`${t} has ${o} term: ${i}`)}}function gW(e,t,n,r){if(n<=0)return!1;let i=Q(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(Js(s)===r)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function hW(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 yW(e){return e.some(t=>SW.has(t))&&e.some(t=>vW.has(t))}var bW=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"]]),SW=new Set(["can","has","is","should"]),vW=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function ks(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new q(e);return Zt({candidates:()=>LW(e,s,n,r),orderCandidates:uc,scanLimit:o,profile:{name:"passthrough-candidates"},prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>CW(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:i})}function CW(e,t,n){let r=wW(n);if(r.size!==1||!Nf(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0],o=xW(e,t,i),s=EW(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:M(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:ce(t),forwardsTo:i.symbol,forwardsToShort:M(i.symbol),forwardsToFile:i.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:RW(a,o,s)}}function xW(e,t,n){return al(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:M(t.symbol)},{label:"callee name",value:M(n.symbol)},{label:"passthrough module",value:_E(t.relativePath,OE(t.relativePath))},{label:"callee module",value:_E(n.file,OE(n.file))}])}function RW(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(IW);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 EW(e,t){return Tt(e,t)?Bn(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:Ge(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function IW(e){return e.includes("public surface")}function wW(e){let t=e.some(r=>Ae(r.symbol))?e.filter(r=>Ae(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function LW(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:3,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0}).filter(i=>!Zs(e,i))}var kW=new Set(mn());function AW(e,t){return`tests/generated/twin-ab/${BE(e)}-vs-${BE(t)}.test.ts`}function BE(e){return(e.split(/[/#]/).pop()||e).replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"symbol"}function FW(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(!DW(s))throw new TypeError("twinAb outFile must be an absolute path.");let a=$E(e,i);if(!a.ok)return a;let c=$E(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=_W(a.symbol,c.symbol,e.config.projectRoot,s,l);return{ok:!0,a:a.symbol,b:c.symbol,signatureCompatible:l,testSource:u}}function $E(e,t){let r=pt(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?kW.has(o):Ae(r.symbol)))return{ok:!1,reason:`${t} resolves to ${M(r.symbol)}${o!==null?` with SCIP kind ${vo(o)}`:""} \u2014 twin-ab compares call outputs, so both referents must be functions or methods.`};if(!Tt(e,r))return{ok:!1,reason:`${t} (${M(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=xi(Ri(a?.documentation??null));return{ok:!0,symbol:{ref:t,symbol:r.symbol,shortName:W(r.symbol)||M(r.symbol),file:r.relativePath,startLine:r.startLine,signature:c,paramCount:c?NW(c):null}}}function NW(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 jE(e,t,n){let r=PW(t),i=TW(e,n),s=MW(r,i).replace(/\\/g,"/").replace(/\.tsx?$/,".js");return s.startsWith(".")?s:`./${s}`}function _W(e,t,n,r,i){let o=jE(n,r,e.file),s=jE(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 HE={caller:3,"entry-surface":2,rooted:1},OW=/not\s*yet\s*implement|not\s*implement|unimplement|\bnyi\b|\btodo\b|\bstub\b|not\s*supported|coming\s*soon/i,BW=/^throw\s+new\s+[\w.]*Error\s*\(([\s\S]*)\)\s*;?$/,$W=/^return(\s+(null|undefined|false|0|''|""|``|\[\]|\{\}))?\s*;?$/,jW=/\/\/\s*TODO\b|\/\*\s*TODO\b/i,HW=/(?:=>|\))\s*(?::\s*[^{;=]+)?\s*\{\s*\}\s*;?\s*$/;function UW(e,t={}){let{scope:n,limit:r=30,scanLimit:i,semantic:o=!0}=t,s=new q(e),a=Pe(s.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),c=[];for(let p of a){let f=GW(e,p);f&&c.push(f)}if(c.length===0)return[];let l=VW(e,c,a),u=c.filter(p=>!l.has(p.def.symbol));if(u.length===0)return[];let d=Kn(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=qW(e,p.def,g);h&&m.push({symbol:p.def.symbol,shortName:M(p.def.symbol),file:p.def.relativePath,startLine:p.def.startLine,endLine:p.def.endLine,loc:ce(p.def),stubKind:p.stubKind,reachability:h,callerFanIn:g,stubText:p.stubText})}return m.sort((p,f)=>HE[f.reachability]-HE[p.reachability]||f.callerFanIn-p.callerFanIn||p.file.localeCompare(f.file)||p.startLine-f.startLine),r?m.slice(0,r):m}function qW(e,t,n){return n>0?"caller":Ge(e,t.symbol,t.relativePath)?"rooted":tt(e,t.relativePath)?"entry-surface":null}function GW(e,t){let n=cn(e,t);if(!n)return null;let r=wn(n),i=r.trim();if(i==="")return!WW(n)||!Tt(e,t)?null:{def:t,stubKind:"empty-body",stubText:"(empty body)"};let o=fo(r),s=Tn(r),a=zW(o,s);if(a.length!==1)return null;let c=a[0];return KW(c)?{def:t,stubKind:"throw-stub",stubText:c.trim()}:jW.test(r)&&$W.test(c.trim())?{def:t,stubKind:"todo-return-default",stubText:i}:null}function zW(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 KW(e){let t=BW.exec(e.trim());return t?OW.test(t[1]??""):!1}function WW(e){return HW.test(e.trimEnd())}function VW(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=JW(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 YW=/\bclass\s+([A-Za-z_$][\w$]*)\s+extends\s+([A-Za-z_$][\w$]*)/g;function JW(e,t){let n=new Map;for(let r of ae(e,{includeIgnored:!1})){let i=X(e,r);if(i)for(let o of i.matchAll(YW)){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 XW=/^(?:validate|verify|check|assert)(?:[A-Z].*)?$/,QW=/^(?:is|has)(?:[A-Z].*)?$/,ZW=/[{,]\s*(?:ok|success|valid|isValid)\s*:\s*false\b/,mp=/\breturn\b/g,eV=/\bfunction\b|=>|\)\s*(?::\s*[^{;=]+)?\s*\{/,tV=/\.(?:addIssue|push)\s*\(/;function nV(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new q(e),s=Pe(o.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),a=[];for(let c of s){let l=iV(e,c);l&&a.push({symbol:c.symbol,shortName:M(c.symbol),file:c.relativePath,startLine:c.startLine,endLine:c.endLine,loc:ce(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 rV(e){return XW.test(e)?"imperative":QW.test(e)?"predicate":null}function iV(e,t){let n=rV(t.leaf);if(!n||Zi(e,t))return null;let r=cn(e,t);if(!r||!eV.test(r))return null;let i=Y(e,t.relativePath)?.callables.find(s=>s.startLine===t.startLine&&s.endLine===t.endLine);if(n==="predicate"&&i?.paramCount===0)return null;if(kE(r)){let s=aV(e,t);return!s||GE(s.body,qE(s.snippet))||UE(s.body)?null:{nameKind:n,resolvedVia:"one-hop-delegate",delegateTarget:s.shortName}}let o=wn(r);return GE(o,qE(r))||UE(o)?null:{nameKind:n,resolvedVia:"direct"}}var oV=new Set(["if","for","while","switch","catch","function"]);function UE(e){let t=fo(e);for(let n of t.matchAll(/\b([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/g))if(!oV.has(n[1]))return!0;return!1}function qE(e){let t=e.indexOf("=>");return t===-1?!1:!/^\s*\{/.test(e.slice(t+2))}function GE(e,t){let n=fo(e);if(/\bthrow\b/.test(n)||/\.reject\s*\(/.test(n)||ZW.test(n)||tV.test(n))return!0;let r=sV(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 sV(e){let t=[];mp.lastIndex=0;let n;for(;n=mp.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()),mp.lastIndex=o}return t}function aV(e,t){let n=Vt(e,t,{callableOnly:!0,limit:3,semanticEvidence:ue}),r=[...new Set(n.map(c=>c.symbol))].filter(c=>c!==t.symbol);if(r.length!==1)return null;let o=pt(e,r[0]).match;if(!o)return null;let s=z(e,o.relativePath).find(c=>c.symbolId===o.symbolId);if(!s)return null;let a=cn(e,s);return a?{body:wn(a),snippet:a,shortName:M(s.symbol)}:null}var cV=60;function lV(e,t={}){let{scope:n,limit:r=30,scanLimit:i,rotDays:o=cV}=t,s=Pe(bi(e,{extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs"]}).filter(u=>K(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=X(e,u);if(!d)continue;let m=kf(d),p=mV(d);for(let g of hV(m,p))p.add(g);let f=uV(m);for(let g of f){if(g.skip){c.push(RV(e,u,g,o));continue}if(g.kind==="describe")continue;let h=KE(d,g.argsStart),b=m.slice(g.argsStart,g.callEnd),S=d.slice(g.argsStart,g.callEnd);WE(b,p)||a.push({file:u,startLine:As(d,g.callStart),endLine:As(d,g.callEnd),title:h,severity:/\bawait\b/.test(b)?"low":"high"});let y=vV(b,S);y&&l.push({file:u,startLine:As(d,g.callStart),endLine:As(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 pp=/(?<!\.)\b(?:x(it|test|describe)|(it|test|describe)(?:\.\s*(skip|only|todo|each\s*\([^)]*\)))?)\s*\(/g;function uV(e){let t=[];pp.lastIndex=0;let n;for(;n=pp.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=Fs(e,a);pp.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 Fs(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 As(e,t){let n=0;for(let r=0;r<t&&r<e.length;r+=1)e[r]===`
|
|
416
|
+
`&&(n+=1);return n}function KE(e,t){let n=e.slice(t,t+400),r=/^\s*(['"`])((?:\\.|(?!\1)[\s\S])*)\1/.exec(n);return r?r[2]:"(anonymous)"}var dV=new Set(["vitest","chai","jest","@jest/globals","assert","node:assert","node:assert/strict","assert/strict","uvu/assert","expect","chai-as-promised"]),zE=/import\s+(?:\*\s+as\s+(\w+)|\{([^}]*)\}|(\w+))\s+from\s+['"]([^'"]+)['"]/g;function mV(e){let t=new Set(["expect","assert"]);zE.lastIndex=0;let n;for(;n=zE.exec(e);){let[,r,i,o,s]=n;if(!(!s||!dV.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 WE(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 pV=/\bfunction\s+(\w+)\s*\(/g,fV=/\b(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/g,gV=60;function hV(e,t){let n=new Set;for(let r of[pV,fV]){r.lastIndex=0;let i;for(;i=r.exec(e);){let o=i[1],s=i.index+i[0].length-1,a=Fs(e,s),c=e.indexOf("{",a+1);if(c===-1||c-a>gV)continue;let l=yV(e,c),u=e.slice(c+1,l);WE(u,t)&&n.add(o)}}return n}function yV(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 bV=/\bmock(?:ReturnValue|ResolvedValue)(?:Once)?\s*\(/g,fp=/\bexpect\s*\(/g,SV=/^\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(/,VE=/^(?:-?\d+(?:\.\d+)?|(['"`]).+\1)$/;function vV(e,t){let n=CV(e,t,bV);if(n.length===0)return null;let r=xV(e,t);for(let i of r)if(n.includes(i))return i;return null}function CV(e,t,n){let r=[];n.lastIndex=0;let i;for(;i=n.exec(e);){let o=i.index+i[0].length-1,s=Fs(e,o),a=t.slice(o+1,s).trim();VE.test(a)&&r.push(a),n.lastIndex=s+1}return r}function xV(e,t){let n=[];fp.lastIndex=0;let r;for(;r=fp.exec(e);){let i=r.index+r[0].length-1,o=Fs(e,i),s=e.slice(o+1),a=SV.exec(s);if(fp.lastIndex=o+1,!a)continue;let c=o+1+a[0].length-1,l=Fs(e,c),u=t.slice(c+1,l).trim();VE.test(u)&&n.push(u)}return n}function RV(e,t,n,r){let i=X(e,t),o=KE(i,n.argsStart),s=As(i,n.callStart),a=EV(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 EV(e,t,n){let r=n+1;try{let i=In(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 IV=.7,YE=.62,JE=.45;function wV(e,t={}){let{windowCommits:n=100,limit:r=30,scope:i,scanLimit:o}=t,s=an(e,{historyMode:t.historyMode}).fileAddRecords();if(!s)return{available:!1,windowCommits:n,findings:[]};if(r<=0)return{available:!0,windowCommits:n,findings:[]};let a=NV(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let l=LV(e,{limit:r,minSimilarity:t.minSimilarity,scanLimit:o,scope:i,semantic:t.semantic,focusFiles:Number.isFinite(r)?void 0:a}).map(d=>_V(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(OV);return{available:!0,windowCommits:n,findings:u,rootCauseGroups:BV(u)}}function LV(e,t){let n=jV(t.limit),r=[...PV(e,{scope:t.scope,minSimilarity:t.minSimilarity??IV,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],i=ea(e,{scope:t.scope});return i.react&&r.push(...DV(e,{scope:t.scope,minSimilarity:t.minSimilarity??YE,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...MV(e,{scope:t.scope,minSimilarity:t.minSimilarity??JE,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i.vue&&r.push(...AV(e,{scope:t.scope,minSimilarity:t.minSimilarity??YE,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...FV(e,{scope:t.scope,minSimilarity:t.minSimilarity??JE,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r}function PV(e,t){return xs(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles}).filter(n=>!Ze(n.symbolA)&&!Ze(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 DV(e,t){return ll(e,t,{query:Rs,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 ll(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:HV(...n.evidenceBuckets(r)),sharedCallees:[]}))}function MV(e,t){return ll(e,t,{query:Es,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,acceptPair:kV,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 TV=new Set(["useCallback","useEffect","useLayoutEffect","useMemo","useMutation","useQueries","useQuery","useQueryClient","useReducer","useRef","useState"]);function kV(e){return e.sharedHooks.some(t=>!TV.has(t))||e.sharedState.length>0||e.sharedHandlers.length>0||e.sharedHandlerVerbs.length>=2}function AV(e,t){return ll(e,t,{query:Is,domain:"vue-component",basis:"vue-template",symbolA:n=>cl(n.fileA),symbolB:n=>cl(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function FV(e,t){return ll(e,t,{query:ws,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>cl(n.fileA),symbolB:n=>cl(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 NV(e,t){let n=new Set;for(let[r,i]of e)i.commitsAgo<=t&&n.add(r);return n}function _V(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 OV(e){let t=XE(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function XE(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 BV(e){let t=new Map;for(let[n,r]of e.entries()){let i=r.rootCauseKey??XE(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:$V(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 $V(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 jV(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function HV(...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 cl(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var UV=Le("suppression-inventory",{clearGroups:["whole-project"]});function ul(e){return UV.get(e,()=>qV(e))}function qV(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 bi(e)){let o=X(e,i);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=Js(s);if(a===null)continue;r+=1,n.set(i,(n.get(i)??0)+1);let c=QE(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[QE(i.check)]+=1);return{total:r,byCategory:t,byFile:n}}function QE(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 gp(e,t,n={}){let r=le(e,t);if(!r)return null;let i=new q(e),o=GV(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:M(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:KV(e,r.symbolId),fanOut:WV(c,r.relativePath)}}function GV(e,t){let n=te(e,t.relativePath);if(n){let r=Fr(n.rootNode,t.startLine,t.endLine);if(r)return{branches:VV(r),estimateBasis:"ast"}}return{branches:rI(tI(e,t.relativePath,t.startLine,t.endLine),eI(e,t.relativePath)),estimateBasis:"regex-fallback"}}function ZE(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=te(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"});YV(s.rootNode,a,n)}for(let l of o)c.has(l.symbolId)||n.set(l.symbolId,zV(e,l))}return n}function zV(e,t){return{branches:rI(tI(e,t.relativePath,t.startLine,t.endLine),eI(e,t.relativePath)),estimateBasis:"regex-fallback"}}function eI(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function tI(e,t,n,r){try{return ut(e.config.projectRoot,t,{inputKind:"indexed source file"}).split(`
|
|
417
|
+
`).slice(n,r+1).join(`
|
|
418
|
+
`)}catch(i){if(!dt(i))throw i;return""}}function KV(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 WV(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function VV(e){let t=0;return Ul(e,n=>{t+=nI(n)}),t}function YV(e,t,n){let r=[...t].sort((i,o)=>i.startLine-o.startLine||o.endLine-i.endLine);Ul(e,i=>{let o=nI(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 JV=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 nI(e){return JV.has(e.type)?1:e.type==="binary_expression"&&e.parent?.type!=="binary_expression"&&(e.text.includes("&&")||e.text.includes("||"))?XV(e.text):0}function XV(e){return(e.match(/&&|\|\|/g)??[]).length}function rI(e,t){let n=Tn(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 iI(e,t,n={}){let r=le(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],o=ir(e,r,{semantic:n.semantic,semanticEvidence:ue}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?M(c.enclosingSymbol):"(top-level)"})),{outgoingCalls:s,incomingCalls:a}=QV(e,r,o,{semantic:n.semantic!==!1});return{symbol:r.symbol,shortName:M(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:M(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)":M(c.symbol),file:c.file}))}}function hp(e,t,n={}){let r=iI(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 QV(e,t,n,r){let i=qi(Vt(e,t,{limit:30,semantic:r.semantic,semanticEvidence:ue}).map(a=>({symbol:a.symbol,file:a.file}))),o=qi(An(e,t,{limit:30,semantic:r.semantic,semanticEvidence:ue})),s=o.length>0?o:qi(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{outgoingCalls:i,incomingCalls:s}}function oI(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=le(e,t);return o?r==="backward"?ZV(e,o,i,{semantic:n.semantic!==!1}):e2(e,o,{semantic:n.semantic!==!1}):null}function dl(e,t,n={}){return oI(e,t,n)}function ZV(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=Vt(e,l,{semantic:r.semantic,semanticEvidence:ue});for(let d of u){if(o.has(d.symbol))continue;o.add(d.symbol),i.push({symbol:d.symbol,shortName:M(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=Nr(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&c.push(m)}}s=c}return{symbol:t.symbol,shortName:M(t.symbol),direction:"backward",connectedSymbols:i}}function e2(e,t,n){let r=new Set,i=[],o=new q(e);for(let s of ir(e,t,{semantic:n.semantic,semanticEvidence:ue})){if(i.length>=30)break;let a=s.enclosingSymbol??We(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=Nr(e,a);!c||e.isIgnored(c.relativePath)||r.has(c.symbol)||(r.add(c.symbol),i.push({symbol:c.symbol,shortName:M(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:M(t.symbol),direction:"forward",connectedSymbols:i}}function sI(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 mI=6,pl=10,bp=3,Sp=8,t2=.7,aI=24,yp=200,pI=12,cI=80,lI=600;function n2(e,t,n={}){let r=n.impactDepth??3,i=n.sliceDepth??3,o=n.semantic,s=m2(t)?i2(e,t):null,a=s?s.primary?.symbol??null:t,c=a!==null,l=c?Ye("trace",a,()=>Ud(e,a,{semantic:o,referenceContext:pI}),T=>({definitions:T.definitions.length,references:T.referencedBy.length})):{definitions:[],referencedBy:[],claimSupport:null},u=c?Ye("call-graph",a,()=>ts(e,a,{semantic:o}),T=>({callers:T?.callers.length??0,callees:T?.callees.length??0})):null,d=c?Ye("complexity",a,()=>gp(e,a,{semantic:o}),T=>({callees:T?.calleeCount??0})):null,m=c?Ye("dataflow",a,()=>hp(e,a,{semantic:o}),T=>({references:T?.usageSites.length??0,producers:T?.producers.length??0,consumers:T?.consumers.length??0})):null,p=c?Ye("backward-slice",a,()=>dl(e,a,{direction:"backward",maxDepth:i,semantic:o}),T=>({maxDepth:i,connectedSymbols:T?.connectedSymbols.length??0})):null,f=c?Ye("forward-slice",a,()=>dl(e,a,{direction:"forward",maxDepth:i,semantic:o}),T=>({maxDepth:i,connectedSymbols:T?.connectedSymbols.length??0})):null,g=c?Ye("affected",a,()=>Um(e,a,{maxDepth:r,scope:n.scope}),T=>({maxDepth:r,affectedSymbols:T.length})):[],h=c?Ye("reuse-candidates",a,()=>Cs(e,a,{minSimilarity:.4,limit:5,semantic:o,sourceCandidateMode:"target-pruned"}),T=>({candidates:T.length,direct:T.filter(L=>L.actionTier==="direct").length})):[],b=c?le(e,a)?.symbol??null:null,S=c?Ye("affected-consumer-reuse",a,()=>s2(l,b,T=>Cs(e,T,{minSimilarity:.4,limit:pl,semantic:o,sourceCandidateMode:"target-pruned"}),{consumerLimit:mI,perConsumerSearchLimit:pl,perConsumerCandidateLimit:bp,candidateLimit:Sp}),T=>({totalConsumers:T.coverage.totalConsumers,analyzedConsumers:T.coverage.analyzedConsumers,candidates:T.candidates.length})):u2(),y=Ye("change-surface",t,()=>qm(e,t,{semantic:o}),T=>({symbols:T?.symbols.length??0,externalConsumers:T?.totalExternalConsumers??0})),x=Ye("system",t,()=>bm(e,t),T=>({files:T.files.length,symbols:T.symbols.length})),v=x.files.length===1,C=Ye("deps",t,()=>v?x.dependsOn.map(T=>({relativePath:T,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):ns(e,t),T=>({files:T.length,reusedSystem:v})),E=Ye("rdeps",t,()=>v?x.dependedOnBy.map(T=>({relativePath:T,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):rs(e,t),T=>({files:T.length,reusedSystem:v})),R=Ye("surface",t,()=>Sm(e,t),T=>({consumers:T.length})),w={symbol:l.definitions.length>0||l.referencedBy.length>0||u!==null||d!==null||m!==null||p!==null||f!==null||g.length>0,file:y!==null||C.length>0||E.length>0,module:x.files.length>0||x.symbols.length>0||R.length>0},I=[];s&&!s.primary&&s.callableCount>1&&I.push(`File target has ${s.callableCount} callable symbols; use one callable name for compiler-resolved flow.`);let A=[...new Set(l.referencedBy.map(T=>T.relativePath))];A.length>0&&A.every(T=>K(T)==="test")&&I.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."),!w.symbol&&!w.file&&!w.module&&I.push("No symbol, file, or module matched target.");let k=y?.file??l.definitions[0]?.relativePath??null;return{target:t,...s?.primary?{primaryCallable:{symbol:s.primary.symbol,shortName:W(s.primary.symbol),file:s.primary.relativePath}}:{},matched:w,history:Ye("history",k??t,()=>d2(e,k,n.gitHead)),trace:r2(l),callGraph:u,complexity:d,dataflow:m,backwardSlice:p,forwardSlice:f,affected:g,changeSurface:y,deps:C,rdeps:E,system:x,surface:R,reuseCandidates:h,affectedConsumerReuse:S,sourcePacket:o2(e,b,l,S,h),warnings:I}}function r2(e){return{definitions:e.definitions,referencedBy:e.referencedBy.map(t=>({relativePath:t.relativePath,line:t.line,enclosingSymbol:t.enclosingSymbol,enclosingShort:t.enclosingShort}))}}function i2(e,t){let n=$r(e,t);if(n.length!==1)return{primary:null,callableCount:0};let r=z(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 o2(e,t,n,r,i){let o=[...t?[{definition:uI(e,t),role:"target"}]:[],...[...r.candidates.map(d=>d.candidate),...i].map(d=>({definition:uI(e,d.symbolB),role:"reuse-candidate"}))],s=new Map;for(let d of sI(o)){if(s.has(d.definition.symbol))continue;let m=d.role==="target"?yp:cI,p=d.definition.endLine<=d.definition.startLine?cr(e,d.definition.relativePath,d.definition.startLine,m):null,f=p?.unitType?p.source:cn(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:W(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=lI;for(let d of c){if(l.length>=aI||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:aI,maxLinesPerSlice:yp,maxTotalLines:lI,targetLineLimit:yp,consumerContextLines:pI,reuseLineLimit:cI}}function uI(e,t){let n=Nr(e,t);return n?z(e,n.relativePath).find(r=>r.symbol===t)??null:null}function s2(e,t,n,r={}){let i=ml(r.consumerLimit,mI),o=ml(r.perConsumerSearchLimit,pl),s=ml(r.perConsumerCandidateLimit,bp),a=ml(r.candidateLimit,Sp),c=a2(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=c2(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>=t2||p.consumers.length>1).sort(l2).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 a2(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:W(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 c2(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 l2(e,t){let n=dI(t.candidate.actionTier)-dI(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 dI(e){return e==="direct"?1:0}function ml(e,t){return typeof e=="number"&&Number.isFinite(e)?Math.max(1,Math.floor(e)):t}function u2(){return{candidates:[],coverage:{totalConsumers:0,analyzedConsumers:0,omittedConsumers:0,perConsumerSearchLimit:pl,perConsumerCandidateLimit:bp,candidateLimit:Sp,returnedCandidates:0}}}function Ye(e,t,n,r=()=>({})){let i;return _(`context.${e}`,()=>(i=n(),i),()=>({target:t,...r(i)}))}function d2(e,t,n){let r={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return r;let i=an(e,n?{head:n}:{}),o=Ye("history.churn",t,()=>i.fileChurn(),c=>({files:c?.size??0}));if(!o)return r;let s=Ye("history.co-change",t,()=>Ds(e,t,{limit:5,...n?{head:n}:{}}),c=>({commits:c.commitsAnalyzed,partners:c.findings.length})),a=Ye("history.suppressions",t,()=>ul(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 m2(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}var Be={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 p2}from"fs";import{isAbsolute as f2,join as g2}from"path";var h2=".scipquery-baseline.json";function vp(e){if(e.startsWith("similar:")){let t=e.slice(8).split("|");return t.length!==2?e:`similar:${t.map(M).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(M).sort().join("|")}`}return e}function Cp(e,t){return t&&f2(t)?t:g2(e.config.projectRoot,t??h2)}function fI(e,t,n={}){let r=Cp(e,n.path);if(!p2(r))throw new Error(`No baseline found at ${r}. Create one with: scip-query health --write-baseline`);let o=(JSON.parse(lt(r,"health baseline")).findings??[]).map(vp),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 Ns from"path";function Os(e,t){let{scope:n,minDeviation:r=5,limit:i=50}=t??{},o=t?.semantic!==!1,s=t?.includePatternDeviations===!0,c=new q(e).fileDependencyGraph(n),l=bs(e,{scope:n}),u=C2([...y2(e,c,{scope:n,semantic:o}),...S2(l.forbiddenEdges),...s?v2(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 y2(e,t,n){let r=E2(e,n.scope),i=[],o=new Set;for(let[a,c]of t){if(_s(a))continue;let l=r.get(a)??new Set;for(let u of c)_s(u)||l.has(u)||b2(e,a,u,n)||(i.push({file:a,dep:u}),o.add(a))}o.size>0&&L2(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 b2(e,t,n,r){return M2(e,t,n)||T2(e,t,n)||P2(n)||A2(e,t,n)||k2(n)?!0:r.semantic&&D2(e,t,n)}function S2(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 v2(e,t){let n=[];for(let[r,i]of x2(e)){let o=i.filter(a=>!_s(a));if(o.length<t)continue;let s=R2(e,o);for(let a of o)for(let c of e.get(a)??[])_s(c)||(s.get(c)??0)===1&&Ns.dirname(c)!==r&&Ns.dirname(c)!==Ns.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 C2(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 x2(e){let t=new Map;for(let n of e.keys()){let r=Ns.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function R2(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])_s(i)||n.set(i,(n.get(i)??0)+1);return n}function E2(e,t){let n=new Map;return I2(e,n,t),n}function I2(e,t,n){for(let r of w2(e,n))gI(e,t,r.from_file,r.to_file)}function w2(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 L2(e,t,n={}){new q(e).scanSourceReferences({paths:n.paths??ae(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},i=>{i.target.relativePath!==i.sourceFile&&(e.isIgnored(i.target.relativePath)||gI(e,t,i.sourceFile,i.target.relativePath))})}function gI(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 P2(e){return e.includes("types")||e.endsWith(".d.ts")}function D2(e,t,n){return Go(e,t).filter(i=>i.sourcePath===n).some(i=>i.isUsed)}function M2(e,t,n){return pe(e,t).filter(i=>i.sourcePath===n).some(i=>i.used)}function T2(e,t,n){let r=pe(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function k2(e){return e.endsWith(".vue")}function A2(e,t,n){let r=pe(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 _s(e){let t=K(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||F2(Ns.basename(e)))}function F2(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 Bs(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 q(e),u=l.scopedDefinitions(n),d=K2(l,n),m={high:0,medium:1,low:2};return Zt({candidates:()=>N2(e,l,u,{minLoc:r,maxLoc:i}),orderCandidates:(p,f)=>ce(f)-ce(p)||p.relativePath.localeCompare(f.relativePath),scanLimit:a,profile:{name:"stale-abstractions"},prepare:p=>{let f=O2(p),g=_2(e,l,p,f,{semantic:c}),h=p.filter(b=>{if(l.hasSuppressionComment(b))return!1;let S=fl(e,b,g,f);return S.realConsumers.length<=1&&!S.transitivelyReachable&&hI(b,S.realConsumers.length,d)});return{consumerFileMap:g,singletonBackedClassIds:j2(e,l,u,h,{semantic:c}),candidateIndex:f}},evaluate:(p,f)=>{if(l.hasSuppressionComment(p)||f.singletonBackedClassIds.has(p.symbolId))return null;let g=fl(e,p,f.consumerFileMap,f.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!hI(g.definition,g.realConsumers.length,d))return null;let h=B2(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 N2(e,t,n,r){return n.filter(i=>i.isTypeLike&&ce(i)>=r.minLoc).filter(i=>ce(i)<=r.maxLoc).filter(i=>!e.isIgnored(i.relativePath)).filter(i=>!i.relativePath.endsWith(".d.ts")).filter(i=>K(i.relativePath)!=="test").filter(i=>!Ge(e,i.symbol,i.relativePath)).filter(i=>!W2(i.symbol))}function xp(e,t,n,r){return Wn(Kn(e,t).forDefinitions(n,{semantic:r.semantic,sourceFallback:r.sourceFallback}))}function _2(e,t,n,r,i){let o=xp(e,t,n,{semantic:!1,sourceFallback:!1}),s=n.filter(l=>{let u=fl(e,l,o,r);return u.realConsumers.length<=1&&!(u.realConsumers.length>0&&Rp(l.relativePath))}),a=i.semantic&&s.length>0?$n(o,xp(e,t,s,{semantic:!0,sourceFallback:!1})):o,c=s.filter(l=>fl(e,l,a,r).realConsumers.length<=1);return $n(a,xp(e,t,c,{semantic:!1,sourceFallback:!0}))}function O2(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=W(n.symbol);i&&r.set(i,n)}return t}function fl(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}=Jc(e,t,o),l=V2(e,t,n,r);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function B2(e,t){let n=bI(e,t.definition.relativePath,t.definition.startLine),r=Rp(t.definition.relativePath)?!0:Y2(e,t.definition),{confidence:i,reason:o}=J2(t.realConsumers.length,n,r),s=$2(t.realConsumers.length,n,r);return{symbol:t.definition.symbol,shortName:M(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:ce(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 $2(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 j2(e,t,n,r,i){let o=U2(e,H2(n),r),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=Wn(Kn(e,t).forDefinitions(s,{semantic:i.semantic,sourceFallback:!0})),c=new Set;for(let{singleton:l,classId:u}of o)G2(e,l,a)&&c.add(u);return c}function H2(e){let t=new Map;for(let n of e){let r=W(n.symbol);r&&t.set(yI(n.relativePath,r),n)}return t}function U2(e,t,n){let r=[];for(let i of n){let o=q2(e,t,i);o&&r.push({singleton:o,classId:i.symbolId})}return r}function q2(e,t,n){if(bI(e,n.relativePath,n.startLine)!=="class")return null;let r=W(n.symbol);if(!r)return null;let i=z2(e,n.relativePath,r);return i?t.get(yI(n.relativePath,i))??null:null}function G2(e,t,n){let r=W(t.symbol),i=n.get(t.symbolId);return!r||!i?!1:[...i].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!_m(e,o,r))}function yI(e,t){return`${e}\0${t}`}function z2(e,t,n){let r=X(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 K2(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function W2(e){let t=nr(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 Rp(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 hI(e,t,n){return!(Rp(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function V2(e,t,n,r){let i=_f(e,t.relativePath),o=W(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 bI(e,t,n){let r=X(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 Y2(e,t){let n=X(e,t.relativePath);if(!n)return!1;let r=W(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 J2(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 co,extname as gl}from"path";function $s(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new q(e),a=nY(s.fileDependencyGraph(n));return Zt({candidates:()=>Z2(e,s,n,r),orderCandidates:uc,scanLimit:o,profile:{name:"wrapper-candidates"},prepare:c=>({callerFileMap:X2(e,s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>Q2(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:i})}function X2(e,t,n,r){let i=Kn(e,t),o=Wn(i.forDefinitions(n,{semantic:!1,sourceFallback:!1})),s=[];r.semantic&&_("wrapper.semantic-candidates",()=>{s=n.filter(m=>Ep(e,t,m,o).length<=1)},()=>({symbols:n.length,semanticCandidates:s.length}));let a=s.length===0?new Map:Wn(i.forDefinitions(s,{semantic:!0,sourceFallback:!1})),c=a.size===0?o:$n(o,a),l=new Map(n.map(m=>[m.symbolId,m])),u=new Map;for(let m of n){let p=Ep(e,t,m,c);if(p.length>1||(u.set(m.symbolId,m),p.length!==1))continue;let f=p[0],g=SI(e,m.symbolId,f);if(!g)continue;let h=vI(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:$n(c,Wn(i.forDefinitions(d,{semantic:!1,sourceFallback:!0})))}function Q2(e,t,n,r){let i=Ep(e,t,n,r.callerFileMap);if(i.length!==1)return null;let o=i[0],s=SI(e,n.symbolId,o);if(!s)return null;let a=vI(t,e,o,n.symbol,s);if(a&&Ci(a.symbol))return null;let{fanIn:c,source:l}=eY(r.callerFileMap,r.reverseFanIn,o,a);if(l==="function"?c<=3:c<=5)return null;let u=iY(e,n,o,a);return{symbol:n.symbol,shortName:M(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:ce(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?M(a.symbol):co(o),callerFanIn:c,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function Z2(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:2,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0}).filter(i=>!Zs(e,i))}function Ep(e,t,n,r){let i=co(n.relativePath,gl(n.relativePath)),o=[...r.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>co(s,gl(s))!==i).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return Jc(e,n,o).realConsumers}function SI(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 vI(e,t,n,r,i){let o=e.definitionsForFile(n),s=tY(t,n,r,i.start_line,i.end_line);return We(o,s)}function eY(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:rY(t,n),source:"file"}}function tY(e,t,n,r,i){let o=W(n);if(!o)return r;let s=Ei(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 nY(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 rY(e,t){let n=e.get(t)??0;if(n>0)return n;let r=co(t,gl(t)),i=0;for(let[o,s]of e)o!==t&&co(o,gl(o))===r&&s>i&&(i=s);return i}function iY(e,t,n,r){return al(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:M(t.symbol)},{label:"caller name",value:r?.symbol?M(r.symbol):co(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var oY=25e3,sY=2500,aY=2500;function cY(e){let t=Jr(e);return t.symbols>=oY||t.documents>=sY?aY:void 0}function Ip(e,t={}){let{scope:n}=t,r=cY(e),i=[],o=ci(e,{scope:n,...Be.dead,scanLimit:r});for(let s of o.symbols)tt(e,s.relativePath)||Ge(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&i.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of Ss(e,{scope:n,...Be.isolated,scanLimit:r}))tt(e,s.relativePath)||Ge(e,s.symbol,s.relativePath)||i.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of ys(e,{scope:n}))s.kind==="real"&&i.push(`cycle:${lY(s.path)}`);for(let s of xs(e,{scope:n,...Be.similar,scanLimit:r}))i.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of Ts(e,{scope:n,...Be.duplicateBodies,scanLimit:r}))i.push(`duplicate-bodies:${s.hash}:${s.functions.map(a=>a.symbol).sort().join("|")}`);for(let s of Ls(e,{scope:n,...Be.extract,scanLimit:r}))i.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of $s(e,{scope:n,...Be.wrappers,scanLimit:r}))i.push(`wrapper:${s.file}:${s.shortName}`);for(let s of ks(e,{scope:n,...Be.passthroughs,scanLimit:r}))i.push(`passthrough:${s.file}:${s.shortName}`);for(let s of Bs(e,{scope:n,...Be.stale,scanLimit:r}))i.push(`stale:${s.file}:${s.shortName}`);for(let s of Os(e,{scope:n,...Be.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY}).results)s.kind!=="architecture-violation"&&i.push(`drift:${s.kind}:${s.file}:${s.dep}`);return i.push(...Im(bs(e,{scope:n}))),[...new Set(i.map(vp))].sort()}function lY(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 uY(e,t={}){let n=Ip(e,{scope:t.scope}),r=Cp(e,t.path);return sg(r,{version:1,findings:n},{spacing:2,trailingNewline:!0}),{path:r,findingCount:n.length}}function dY(e,t={}){return fI(e,Ip(e,{scope:t.scope}),{path:t.path})}function mY(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new q(e);return Zt({candidates:()=>o.productionCallableDefinitions({scope:n,files:t.files,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}),filterCandidate:s=>pY(s.relativePath),scanLimit:i,profile:{name:"unused-params"},evaluate:s=>{let a=Y(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=Ei(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("_")||fY(c.get(d.name),a.paramsEndLine,a.endLine))break;l.unshift(d.name)}return l.length===0?null:{symbol:s.symbol,shortName:M(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 pY(e){let t=de(e);return t==="typescript"||t==="tsx"||t==="javascript"}function fY(e,t,n){return e?e.some(r=>r>t&&r<=n):!1}var gY=new Set(mn());function wp(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:o}=t??{},s=new q(e);return Zt({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:r,requireFunctionLikeSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,filterCandidate:hY,profile:{name:"complexity-hotspots"},prepare:a=>{let c=bY(e,a),l=t?.semantic!==!1,u=l?Rt(e):null;u?.materializeReferences(a,{prefetchCallees:!0});let d=s.crossFileCallerMap(a,{semantic:!1});return{callerMap:u?$n(d,u.callerMap(a)):d,calleeMap:s.calleeMap(a,{semantic:l}),languageByFile:c,clojureCallableIds:SY(e,a,c),branchEstimates:ZE(e,a)}},evaluate:(a,c)=>yY(a,c,r),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:i})}function hY(e){return e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&gY.has(e.kind):!0}function yY(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:M(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 bY(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 SY(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((Y(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 vY}from"fs";import{basename as CY,join as CI}from"path";function xY(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 RY(e,t){let n=EY(e,t.file,t.keys);if(!n.ok)return{name:t.name,file:t.file,status:"unavailable",missing:[],extra:[],unavailableReason:n.reason};let r=MY(e.config.projectRoot,t.mustEqual),i=xY(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 RI(e,t){return t.map(n=>RY(e,n))}function EY(e,t,n){return n.type==="markdown-list"?DY(e,t,n.marker):IY(e,t,n)}function IY(e,t,n){if(!X(e,t))return{ok:!1,reason:`file not found: ${t}`};let i=de(t);if(!i)return{ok:!1,reason:`unsupported file type for ${n.type} extraction: ${t}`};let o=te(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"?wY(o,n.identifier):PY(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 EI(e){let t=e.childForFieldName("value");return t?t.type==="as_expression"||t.type==="satisfies_expression"?t.namedChild(0):t:null}function wY(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=EI(n);if(i?.type==="object")return LY(i)}return null}function LY(e){let t=new Set;for(let n of e.namedChildren)if(n.type==="pair"){let r=n.childForFieldName("key");r&&t.add(II(r.text))}else n.type==="shorthand_property_identifier"&&t.add(n.text);return[...t].sort()}function PY(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=EI(n);if(i?.type!=="array")continue;let o=new Set;for(let s of i.namedChildren)s.type==="string"&&o.add(II(s.text));return[...o].sort()}return null}function II(e){return e.length>=2&&(e[0]==="'"&&e.endsWith("'")||e[0]==='"'&&e.endsWith('"'))?e.slice(1,-1):e}function DY(e,t,n){let r=X(e,t);if(!r)return{ok:!1,reason:`file not found: ${t}`};let i=wI(r,n);return i===null?{ok:!1,reason:`no <!-- BEGIN GENERATED ${n} --> ... <!-- END GENERATED ${n} --> block in ${t}`}:{ok:!0,keys:LI(i)}}function wI(e,t){let n=Ne(t),i=new RegExp(`<!--\\s*BEGIN GENERATED ${n}\\s*-->([\\s\\S]*?)<!--\\s*END GENERATED ${n}\\s*-->`).exec(e);return i?i[1]:null}function LI(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 MY(e,t){switch(t.type){case"top-level-dirs":return xI(CI(e,t.path));case"file-glob":return[...new Set(zc(e,t.pattern).map(n=>CY(n)))].sort();case"registered-commands":return TY(e);case"builtin-skills":return xI(CI(e,"skills"))}}function xI(e){let t;try{t=vY(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort()}function TY(e){let t;try{t=ut(e,"docs/COMMAND_REFERENCE.md",{maxBytes:8*1024*1024,inputKind:"generated command reference"})}catch(r){if(!dt(r))throw r;return[]}let n=wI(t,"COMMAND REFERENCE");return n?LI(n):[]}function Yn(e){return e.scoreCount??e.count}function MI(e){let t=NY(e),{breakdown:n,pressure:r}=_Y(e),i=DI(n,"risk"),o=DI(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:Yn(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:Yn(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:Yn(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:kY(e),validation:FY(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 kY(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:AY(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 AY(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:Ln(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function FY(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?Ln(i/r.size):0,c=s>0?Ln(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=Ln(p/m.size);l[u]={flaggedFiles:m.size,fixDensity:f,lift:c>0?Ln(f/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?Ln(a/c):null,byCategory:l,validationBasis:{method:"subject-regex",commitsScanned:e.gitEvidence?.commitsScanned??0}}}function Ln(e){return Math.round(e*100)/100}function TI(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function hl(e,t="existing shared infrastructure discount"){let n=Yn(e);return Math.abs(n-e.count)<.01?"":` (${TI(n)} score-weighted after ${t})`}function js(e,t){let n=Yn(e),r=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?r:`${r} (${TI(n)} score-weighted)`}function NY(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${hl(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${hl(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${hl(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`+hl({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 PI={"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 DI(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 _Y(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=[],i=[],o=(E,R,w)=>{R>0&&r.push({axis:E,points:R,detail:w,kind:PI[E]??"hygiene"})},s=(E,R,w,I,A,k,T)=>{let L=Math.max(I,1);if(w<=L)return;let F=w/L,N=Math.min(A,Math.ceil(Math.log2(F)*k));if(N<=0)return;let re=PI[E]??"hygiene";i.push({axis:E,category:R,kind:re,count:w,threshold:Ln(L),ratio:Ln(F),extraPenalty:N}),o(E,N,`${w} ${T} exceed pressure threshold ${Ln(L)} (${Ln(F)}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=Yn(e.reactHookCandidates),f=p/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(f)),js(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=Yn(e.vueComposableCandidates),S=b/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(S)),js(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=Yn(e.wrappers);o("wrappers",Math.min(3,x),js(e.wrappers,"wrapper candidate(s)"));let v=Yn(e.passthroughs);o("passthroughs",Math.min(3,v),js(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 E=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(E/10)),js({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:E},"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 E=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",E,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 OY}from"v8";var BY=64*1024*1024;function Lp(){let e=globalThis.gc;if(!e)return;let t=OY();t.heap_size_limit-t.used_heap_size<BY||e()}var $Y=[{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 kI(e=new Set(["indexed-graph","source-facts"])){return $Y.map(t=>{let n=t.relationRequirements.map(i=>{let o=Ic(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 jY=50,HY=25e3,UY=2500,AI=2500,FI=50,qY=10,yl=["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"],GY={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:VY(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:YY(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:JY(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:XY(e,t,n)}),"duplicate-bodies":(e,t,n)=>({phase:"duplicate-bodies",duplicateBodies:ZY(e,t,n)}),"twin-drift":(e,t,n)=>({phase:"twin-drift",twinDrift:eJ(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:tJ(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:nJ(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:rJ(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:iJ(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:oJ(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:sJ(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:QY(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:aJ(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:cJ(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:lJ(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:pJ(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:fJ(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:uJ(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:dJ(e,n)}),"coverage-contracts":(e,t,n)=>({phase:"coverage-contracts",coverageContracts:mJ(e,n)})};function Pp(e,t,n={}){return zY(e,[t],n)[0]}function zY(e,t,n={}){return KY(e,n.full!==!1,(r,i)=>{let o={...i,releaseCachesBetweenPhases:!1};return t.map(s=>GY[s](e,n.scope,o,r))})}function KY(e,t,n){let r=Jr(e),i=gJ(r,t);try{return n(r,i)}finally{xm(e,{semanticProvider:!0}),Lp()}}function Dp(e){return MI(WY(e))}function WY(e){let t=Ue(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,detectorEvidence:kI(),dead:Ue(e,"dead").dead,isolated:Ue(e,"isolated").isolated,realCycleCount:Ue(e,"cycles").realCycleCount,similarCount:Ue(e,"similar").similarCount,duplicateBodies:Ue(e,"duplicate-bodies").duplicateBodies,twinDrift:Ue(e,"twin-drift").twinDrift,reactComponentDuplicates:Ue(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:Ue(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:Ue(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:Ue(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:Ue(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:Ue(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:Ue(e,"extract-candidates").extractCount,wrappers:Ue(e,"wrapper-candidates").wrappers,passthroughs:Ue(e,"passthrough-candidates").passthroughs,stale:Ue(e,"stale-abstractions").stale,drift:Ue(e,"drift").drift,complexity:Ue(e,"complexity-hotspots").complexity,gitEvidence:NI(e,"git-evidence")?.gitEvidence??null,suppressions:NI(e,"suppressions")?.suppressions??null,coverageContracts:Ue(e,"coverage-contracts").coverageContracts}}function NI(e,t){return e.find(n=>n.phase===t)}function Ue(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function VY(e,t,n){return $e(e,n,"dead",()=>{let r=ci(e,{scope:t,...Be.dead,scanLimit:n.candidateScanLimit,semantic:n.semantic});return bl(bJ(e,r.symbols))})}function YY(e,t,n){return $e(e,n,"isolated",()=>{let r=Ss(e,{scope:t,...Be.isolated,scanLimit:n.candidateScanLimit,semantic:n.semantic});return bl(SJ(e,r))})}function JY(e,t,n){return $e(e,n,"cycles",()=>ys(e,{scope:t}).filter(i=>i.kind==="real").length)}function XY(e,t,n){let r=$e(e,n,"similar",()=>km(e,{scope:t,...Be.similar,scanLimit:n.candidateScanLimit,semantic:n.semantic}));return Math.min(r,n.candidateResultLimit)}function QY(e,t,n){return $e(e,n,"extract-candidates",()=>Ls(e,{scope:t,...Be.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}).length)}function ZY(e,t,n){return $e(e,n,"duplicate-bodies",()=>{let r=Ts(e,{scope:t,...Be.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 eJ(e,t,n){return $e(e,n,"twin-drift",()=>{let r=sl(e,{scope:t,...Be.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 tJ(e,t,n){return $e(e,n,"react-component-duplicates",()=>{let r=Rs(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Mp(r)})}function nJ(e,t,n){return $e(e,n,"react-hook-candidates",()=>{let r=Es(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return BI(r,CJ)})}function rJ(e,t,n){return $e(e,n,"react-large-component-pressure",()=>{let r=Am(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return vJ(r)})}function iJ(e,t,n){return $e(e,n,"vue-component-duplicates",()=>{let r=Is(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Mp(r)})}function oJ(e,t,n){return $e(e,n,"vue-composable-candidates",()=>{let r=ws(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return BI(r,xJ)})}function sJ(e,t,n){return $e(e,n,"vue-large-view-pressure",()=>{let r=Fm(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return bl(r)})}function aJ(e,t,n){return $e(e,n,"wrapper-candidates",()=>{let r=$s(e,{scope:t,...Be.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return OI(r,RJ)})}function cJ(e,t,n){return $e(e,n,"passthrough-candidates",()=>{let r=ks(e,{scope:t,...Be.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return OI(r,EJ)})}function lJ(e,t,n){return $e(e,n,"stale-abstractions",()=>{let r=Bs(e,{scope:t,...Be.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 uJ(e,t){return $e(e,t,"git-evidence",()=>{let n=an(e,{historyMode:t.gitHistoryMode}),r=n.fileChurn();if(!r)return null;let i=n.commitHistory(),o=Ds(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:Tp(o.findings.reduce((a,c)=>a+_I(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:_I(a),subjectContext:a.subjectContext}))},fileStats:s,commitsScanned:i?.commits.length??0}})}function dJ(e,t){return $e(e,t,"suppressions",()=>{let n=ul(e);return{total:n.total,byCategory:{...n.byCategory}}})}function mJ(e,t){return $e(e,t,"coverage-contracts",()=>{let n=e.config.coverageContracts??[],i=RI(e,n).filter(o=>o.status!=="ok");return{count:i.length,loc:0,files:[...new Set(i.map(o=>o.file))].sort()}})}function pJ(e,t,n){return $e(e,n,"drift",()=>{let r=Os(e,{scope:t,...Be.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 fJ(e,t,n){return $e(e,n,"complexity-hotspots",()=>{let r=wp(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>jY).length}})}function gJ(e,t){let n=e.symbols>=HY||e.documents>=UY,r=t?Number.POSITIVE_INFINITY:FI,i=t?Number.POSITIVE_INFINITY:qY;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 ${FI} findings. Enable full mode for unbounded candidate counts.`]}}function hJ(e,t){t.releaseCachesBetweenPhases&&(xm(e),Lp())}function $e(e,t,n,r){yJ(n);try{return r()}finally{hJ(e,t)}}function yJ(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function bJ(e,t){return t.filter(n=>!tt(e,n.relativePath)&&!Ge(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function SJ(e,t){return t.filter(n=>!tt(e,n.relativePath)&&!Ge(e,n.symbol,n.relativePath))}function bl(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 OI(e,t){return{...bl(e),scoreCount:Tp(e.reduce((r,i)=>r+t(i),0))}}function vJ(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 Mp(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 BI(e,t){return{...Mp(e),scoreCount:Tp(e.reduce((r,i)=>r+t(i),0))}}function CJ(e){let t=e.sharedHooks.length>0,n=$I({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:jI(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function xJ(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=$I({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:jI(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function $I(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!UI.has(HI(t))).length+Math.min(e.functions.length,3)}function jI(e,t,n){let r=[...e,...t,...n].map(HI);return r.length>0&&r.every(i=>UI.has(i))}function HI(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function RJ(e){return e.actionTier==="signal"?.25:1}function EJ(e){return e.actionTier==="signal"?.25:1}function _I(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 Tp(e){return Math.round(e*100)/100}var UI=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 IJ(e,t,n,r={}){let i=Tm(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 wJ(e,t,n={}){let r=gs(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 LJ=/:\d+(?:-\d+)?$/u;function PJ(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=LJ.test(t),s=gs(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;qI(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);qI(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"&&!DJ(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 qI(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 DJ(e){return e.semanticFamily==="control"&&e.sourceKind==="control-dependence"}function MJ(e,t={}){let{scope:n,limit:r}=t,i=new q(e),o=$J([...TJ(e,n),...FJ(e,i,n)]);return jJ(o),r?o.slice(0,r):o}function TJ(e,t){let n=[];for(let r of kJ(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||Rd(e,r.barrel_path)||X(e,r.barrel_path)&&ta(e,r.barrel_path).length===0)continue;let i=AJ(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:M(r.symbol),originalFile:r.original_path,barrelConsumers:o,directConsumers:s,...zI(e,r.barrel_path)})}return n}function kJ(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 AJ(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 FJ(e,t,n){let r=[],i=BJ(e);for(let o of NJ(e,n))KI(i,o,o)>0||r.push(..._J(e,t,o,i));return r}function NJ(e,t){return ae(e,{scope:t,includeIgnored:!1}).filter(n=>ta(e,n).length>0||go(e,n).length>0)}function _J(e,t,n,r){let i=ta(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>GI(e,t,n,s.sourcePath,r,[OJ(s.specifier)])),o=go(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>GI(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 GI(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?M(c.symbol):a,originalFile:r,barrelConsumers:0,directConsumers:KI(i,r,n),...zI(e,n)}})}function OJ(e){return e.split("::").at(-1)?.split("/").at(-1)?.replace(/\.[^.]+$/,"")??e}function zI(e,t){return Bn(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 BJ(e){let t=new Map;for(let n of ae(e,{includeIgnored:!1}))for(let r of pe(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 KI(e,t,n){let r=e.get(t);return r?r.size-(r.has(n)?1:0):0}function $J(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 jJ(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function HJ(e,t={}){let{samples:n=50,scope:r,maxDisagreements:i=5}=t,o=new q(e),s=UJ(o.productionCallableDefinitions({scope:r,minLoc:2,requireFunctionLikeSymbol:!0}),n),a=qJ(e,s);if(s.length===0||!a)return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let c={references:WI(),callees:WI()},l=[],u=0,d=a==="semantic"?Ga(e,s):new Map,m=a==="source"?KJ(e,o,s):null;for(let p of s){let f=Sl(p,a==="semantic"?qa(e,p).map(x=>x.file):[...m?.referencesBySymbolId.get(p.symbolId)??[]]),g=Sl(p,a==="semantic"?(d.get(p.symbolId)??[]).map(x=>x.file):[...m?.calleesBySymbolId.get(p.symbolId)??[]]);u+=1;let h=Sl(p,ir(e,p,{semanticEvidence:ue}).map(x=>x.file)),b=Sl(p,(o.calleeMap([p],{semantic:!1}).get(p.symbolId)??[]).map(x=>x.file)),S=kp(a,"references"),y=kp(a,"callees");VI(c.references,p,"references",h,f,S,l),VI(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?Fp(u/s.length):0,oracleKind:a,scores:["references","callees"].map(p=>zJ(p,c[p],a)),topDisagreements:l.slice(0,i)}}function WI(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0,skippedOraclePartial:0}}function UJ(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 qJ(e,t){let n=t[0];if(!n)return null;if(Ap(e,n))return"source";try{if(Rt(e).capability("semantic-references",n.relativePath).available)return"semantic"}catch{}return t.some(r=>Ap(e,r))?"source":null}function Sl(e,t){let n=new Set;for(let r of t)r!==e.relativePath&&n.add(r);return n}function VI(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:M(t.symbol),question:n,cheapOnly:a,oracleOnly:c})}var GJ={references:!0,callees:!1};function zJ(e,t,n){let r=t.oracleTotal>0?t.agreed/t.oracleTotal:1,i=t.cheapTotal-t.agreed,o=kp(n,e);return{question:e,comparedSymbols:t.comparedSymbols,precision:o&&t.cheapTotal>0?Fp(t.agreed/t.cheapTotal):null,recall:Fp(r),unverified:i,skippedOraclePartial:t.skippedOraclePartial}}function kp(e,t){return e==="semantic"?GJ[t]:!1}function Ap(e,t){return de(t.relativePath)==="clojure"&&Y(e,t.relativePath)!==null}function KJ(e,t,n){let r=new Map,i=new Map,o=n.filter(c=>Ap(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(de(c)!=="clojure")continue;let l=Y(e,c);if(l)for(let u of l.fileIdentifiers)for(let d of s.get(u)??[])YI(r,d.symbolId,c)}let a=new Map;for(let c of t.scopedDefinitions()){if(de(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=Y(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)??[])YI(i,c.symbolId,d.relativePath)}}return{referencesBySymbolId:r,calleesBySymbolId:i}}function YI(e,t,n){let r=e.get(t);if(r){r.add(n);return}e.set(t,new Set([n]))}function Fp(e){return Math.round(e*1e3)/1e3}var WJ=new Set(mn());function VJ(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o,maxShapeFrequency:s=12}=t,a=t.semantic!==!1,c=XJ(e,YJ(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:a,maxShapeFrequency:s}),l=ZJ(c);return i?l.slice(0,i):l}function YJ(e,t){let n=He(e,{scope:t.scope}).filter(r=>JJ(r)&&!e.isIgnored(r.relativePath)).filter(r=>ce(r)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((r,i)=>ce(i)-ce(r)||r.relativePath.localeCompare(i.relativePath)),Pe(n,t.scanLimit)}function JJ(e){return!e.isFunctionLike||Ze(e.symbol)?!1:e.kind===null||WJ.has(e.kind)}function XJ(e,t,n){let r=[];for(let s of t){let a=t5(e,s,n);a&&r.push({signature:a,definition:s,fn:QJ(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=e5(s.fn.loc),c=(i.get(s.signature)??0)>n.maxShapeFrequency,l=c?dp(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 QJ(e){return{symbol:e.symbol,shortName:M(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:ce(e)}}function ZJ(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 e5(e){return e<=5?"<=5":e<=20?"6-20":">20"}function t5(e,t,n){if(n.semantic){let o=Yy(e,t);if(o)return o}let r=n5(t.documentation),i=r?o5(r):null;return i||s5(r5(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function n5(e){return xi(Ri(e))}function r5(e,t,n,r,i){let o=X(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=c5(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,i5(u)))return u}if(u&&u.includes("("))return u}return null}function i5(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||Af(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function o5(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 s5(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${Ne(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=a5(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 a5(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 c5(e,t,n,r){let i=Ne(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 khe}from"child_process";import{execFileSync as rhe}from"child_process";import{createHash as ohe}from"crypto";import{lstatSync as ahe,readlinkSync as che,readdirSync as lhe,realpathSync as uhe,statSync as dhe}from"fs";import{dirname as phe,isAbsolute as fhe,join as ghe,posix as hhe,relative as yhe,resolve as bhe,sep as She}from"path";var Che=512*1024*1024;function JI(e){return _r({version:e.version,...e.base?{base:e.base}:{},files:[...e.files].sort((t,n)=>t.path.localeCompare(n.path))})}function Np(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 u5="scip-query:collaboration-domain",d5="scip-query:workspace-instance",m5="scip-query:index-generation",p5="scip-query:repository-content",XI="scip-query:index-inputs",f5="scip-query:index-inputs";function di(e){let t=e.snapshot,n=e.observedSourceKinds?new Set(e.observedSourceKinds):void 0,r=e.gitContext??t?.gitContext??(n?.has("live-workspace")?$l(e.projectRoot):void 0),i=e.collaborationDomainId??e.db?.config.collaborationDomainId,o=i?Vr(u5,1,i):void 0,s=r?Vr(d5,1,r.worktreeId):void 0,a=t?Vr(p5,1,JI(t.repositoryContent)):void 0,c=t?Vr(XI,t.indexInputs.version,Np(t.indexInputs)):void 0,l=e.db&&t?h5(e.db.generation.metadataRaw):void 0,u=e.db?{generation:Vr(m5,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:hr,observedAt:(e.observedAt??(t?new Date(t.capturedAt):new Date)).toISOString(),facts:{...o?{collaborationDomain:o}:{},...s?{workspaceInstance:s}:{},...a?{wholeContent:a}:{},...c?{relevantInputs:[{subject:f5,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 g5(e){return di({projectRoot:e.projectRoot,db:e.db,...e.gitContext?{gitContext:e.gitContext}:{},...e.observedAt?{observedAt:e.observedAt}:{},observedSourceKinds:["index-generation"]})}function Dhe(){let e=ic();if(!e)return di({projectRoot:rc(),observedSourceKinds:["process"]});let t=e.config.projectRoot,n=$l(t);return g5({projectRoot:t,db:e,...n?{gitContext:n}:{}})}function h5(e){if(!e)return;let t=kr(e);if(t.kind!=="legacy"&&t.kind!=="supported")return;let n=qs(t.metadata.fingerprint);return n&&Number.isSafeInteger(n.version)&&n.version>0?Vr(XI,n.version,Np(n)):void 0}var Op="scip-query-isolated-analysis",Bp=1;function y5(e){let t=[...e??[]];return t.includes("--json")?t:["--json",...t]}var lo=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 jhe(e,t){let n=ic(),r={protocol:Op,schemaVersion:Bp,producer:{name:"scip-query",version:Ar},command:e,result:t,...n?{observationReceipt:di({projectRoot:n.config.projectRoot,db:n,observedSourceKinds:["index-generation"]})}:{}};yd(JSON.stringify(r))}function QI(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function vl(e){let t=e.timeoutMs??xg.analysis,n=e.maxBuffer??10*1024*1024;return Eg({command:process.execPath,args:[...process.execArgv,e.cliPath,e.command,...y5(e.args)],cwd:process.cwd(),env:e.env??process.env,label:e.label,timeoutMs:t,maxStdoutBytes:n,maxStderrBytes:n}).catch(r=>{throw r instanceof Rg&&r.kind==="timeout"?new lo(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 b5(r.stdout,e)})}function b5(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(!se(n))throw new Error(`${t.label} returned a non-object isolated-analysis message.`);if(n.protocol!==Op)throw new Error(`${t.label} returned protocol ${_p(n.protocol)}; expected ${Op}.`);if(n.schemaVersion!==Bp)throw new Error(`${t.label} returned unsupported isolated-analysis schemaVersion ${_p(n.schemaVersion)}; expected ${Bp}.`);if(!S5(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 ${_p(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&&(!Ka(r)||r.schemaVersion!==2))throw new Error(`${t.label} returned an invalid observation receipt.`);return{result:n.result,...r?{observationReceipt:r}:{}}}function S5(e){return se(e)&&e.name==="scip-query"&&typeof e.version=="string"&&e.version.length>0}function _p(e){return typeof e=="string"?JSON.stringify(e):String(e)}async function $p(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 ZI(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 v5}from"child_process";import{existsSync as C5,mkdirSync as x5,renameSync as R5,writeFileSync as E5}from"fs";import{dirname as ew,join as I5}from"path";var Cl=5,w5="health-report-cache.json";function jp(e,t,n,r=M5()){let i=Pn(e);return i?{version:Cl,projectFingerprint:i,cliVersion:n,scope:t.scope??null,full:t.full===!0,phaseTimeoutMs:t.phaseTimeoutMs??null,gitHead:r.gitHead(e.config.projectRoot)}:null}function tw(e,t,n=ow()){let r=rw(e),i=iw(t),o=!1;return _("health.report-cache.read",()=>{if(!n.existsSync(r))return null;try{let s=JSON.parse(n.readFile(r));return!L5(s)||s.keyHash!==i?null:(o=!0,s.report)}catch{return null}},()=>({available:!0,hit:o,keyHash:i}))}function nw(e,t,n,r=ow()){let i=rw(e),o={version:Cl,keyHash:iw(t),key:t,writtenAt:r.nowIso(),report:n};r.mkdirSync(ew(i),{recursive:!0});let s=`${i}.${process.pid}.${Date.now()}.tmp`;r.writeFileSync(s,JSON.stringify(o)),r.renameSync(s,i)}function rw(e){return I5(ew(e.config.dbPath),w5)}function iw(e){return ln(JSON.stringify(e))}function L5(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===Cl&&typeof t.keyHash=="string"&&P5(t.key)&&typeof t.writtenAt=="string"&&D5(t.report)}function P5(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===Cl&&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 D5(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 M5(){return{gitHead(e){let t=v5("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:3e4,killSignal:"SIGKILL"});return t.status===0?t.stdout.trim():null}}}function ow(){return{existsSync:C5,mkdirSync:x5,readFile:e=>lt(e,"health report cache"),renameSync:R5,writeFileSync:E5,nowIso:()=>new Date().toISOString()}}var cw="__health-phase",k5="__diff-impact-batch",A5=10,F5=4,N5=8,_5=25e3,O5=2500,Hp=2500,B5=4,$5=12,sw=3e4,lw=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),uw=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]),j5=new Set([...uw,"suppressions"]),H5=new Set(["similar","extract-candidates"]),Rl=2,aw=po({kind:"health-semantic-prewarm",invalidation:Qe("health-semantic-prewarm"),serialize:e=>JSON.stringify(e),deserialize:U5});function U5(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return n.version!==Rl||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:Rl,definitions:n.definitions,referenceCacheWrites:n.referenceCacheWrites,referenceIncomplete:n.referenceIncomplete,calleeRows:n.calleeRows,warmedAt:n.warmedAt}}catch{return null}}function mye(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
|
|
533
|
+
`)}function q5(e){let t=Jr(e);return t.symbols>=_5||t.documents>=O5}function pye(e,t,n,r={}){if(!q5(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 ${Hp}. `+i)}return{scanLimit:Hp,semantic:!1,analysisBudget:{scanLimit:Hp,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 G5={env:process.env,projectFingerprint:Pn,semanticEngineFingerprint:V5,readMarker:(e,t,n)=>aw.read(e,t,n),writeMarker:(e,t,n,r)=>aw.write(e,t,n,r),candidateDefinitions:(e,t)=>new q(e).scopedDefinitions(t.scope).filter(n=>et(n.relativePath)!==null),materializeReferences:(e,t,n)=>Rt(e).materializeReferences(t,n),materializeCallees:ed};function z5(e,t,n=G5){if(t.full!==!0)return Mr("default-mode");if((n.env??process.env).SCIP_QUERY_HEALTH_SEMANTIC_PREWARM==="0")return Mr("disabled");let r=Mr("error");return _("health.semantic-prewarm",()=>{try{r=K5(e,t,n)}catch(i){r=Mr("error",{error:i instanceof Error?i.message:String(i)})}return r},()=>Y5(r))}function K5(e,t,n){let r=n.projectFingerprint(e);if(!r)return Mr("missing-project-fingerprint");let i=W5(t,n.semanticEngineFingerprint(e)),o=n.readMarker(e,i,r);if(o&&o.referenceIncomplete===0)return Mr("cache-hit");let s=[];if(s=_("health.semantic-prewarm.candidate-definitions",()=>(s=n.candidateDefinitions(e,t),s),()=>({definitions:s.length})),s.length===0)return Mr("no-semantic-definitions");let a=0,c=_("health.semantic-prewarm.references",()=>{let m=n.materializeReferences(e,s,{prefetchCallees:!0});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 Mr("provider-unavailable",{definitions:s.length,referenceMisses:c.misses});let u=0,d=_("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}:(_("health.semantic-prewarm.marker-write",()=>n.writeMarker(e,i,r,{version:Rl,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 W5(e,t){return JSON.stringify({version:Rl,cliVersion:Ar,semanticEngineFingerprint:t,scope:e.scope??null})}function V5(e){return ln(JSON.stringify({kind:"health-semantic-prewarm-engine",rust:qr(e.config.projectRoot)}))}function Mr(e,t={}){return{status:"skipped",reason:e,definitions:0,referenceCacheHits:0,referenceCacheWrites:0,referenceMisses:0,referenceIncomplete:0,calleeRows:0,...t}}function Y5(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 xl(e){return fd(t=>{let n=di({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 El(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 di({projectRoot:r.database.config.projectRoot,...o&&s?{db:r.database}:{},observedSourceKinds:n})}async function fye(e){return(await J5(e)).result}async function J5(e){let t=nX(e),n={...e,phaseTimeoutMs:t??null},r=xl(g=>{let h=jp(g,n,Ar);if(!h)return null;let b=tw(g,h);return b||null});if(r.value)return{result:r.value,observationReceipt:El([r.anchor],[],["index-generation","live-workspace"])};let i=xl(g=>({applicability:X5(g,e),overview:Pp(g,"overview",e)})),{applicability:o,overview:s}=i.value,a=[r.anchor,i.anchor],c=new Map;c.set("overview",s);let l=yl.filter(g=>g==="overview"?!1:Q5(g,o)?!0:(c.set(g,mi(g)),!1)),u=Z5(l);if(e.full){let g=xl(h=>z5(h,e));a.push(g.anchor)}let d=await $p(u,rX(u.length),g=>eX(g,e,t)),m=d.flatMap(g=>g.result),p=[];if(m.forEach(g=>{g.healthPhaseMeta&&p.push(`Health phase "${g.phase}" deferred: ${g.healthPhaseMeta.reason}. Run health --full for exhaustive analysis.`),c.set(g.phase,g)}),p.length>0){let g=c.get("overview");c.set("overview",{...g,warnings:[...g.warnings,...p]})}let f=Dp(yl.map(g=>c.get(g)));return fd(g=>{let h=jp(g,n,Ar);h&&nw(g,h,f)}),{result:f,observationReceipt:El(a,d.map(g=>g.observationReceipt),["index-generation","live-workspace"])}}function X5(e,t){return ea(e,{scope:t.scope})}function Q5(e,t){return lw.has(e)?t.react:uw.has(e)?t.vue:!0}function Z5(e){return ZI(e,[lw,j5,H5])}function mi(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 eX(e,t,n){if(e.length===1)return tX(e[0],t,n).then(s=>({result:[s.result],...s.observationReceipt?{observationReceipt:s.observationReceipt}:{}}));let r=e.join(","),i=process.argv[1]??qp(import.meta.url),o=[r];return t.scope&&o.push("--scope",t.scope),t.full&&o.push("--full"),vl({cliPath:i,command:cw,args:o,label:`Health phases "${r}"`,timeoutMs:n}).catch(s=>{if(t.full||!(s instanceof lo))throw s;return{result:e.map(a=>dw(a,s.timeoutMs,`timed out after ${s.timeoutMs}ms`))}})}function tX(e,t,n){let r=process.argv[1]??qp(import.meta.url),i=[e];return t.scope&&i.push("--scope",t.scope),t.full&&i.push("--full"),vl({cliPath:r,command:cw,args:i,label:`Health phase "${e}"`,timeoutMs:n}).catch(o=>{if(t.full||!(o instanceof lo))throw o;return{result:dw(e,o.timeoutMs,`timed out after ${o.timeoutMs}ms`)}})}function nX(e,t=process.env){if(e.full)return;let n=t.SCIP_QUERY_HEALTH_PHASE_TIMEOUT_MS;if(!n)return sw;let r=parseInt(n,10);return!Number.isFinite(r)||r<0?sw:r===0?void 0:r}function dw(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{...mi(e),...r};case"react-hook-candidates":return{...mi(e),...r};case"react-large-component-pressure":return{...mi(e),...r};case"vue-component-duplicates":return{...mi(e),...r};case"vue-composable-candidates":return{...mi(e),...r};case"vue-large-view-pressure":return{...mi(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 rX=mw({envKey:"SCIP_QUERY_HEALTH_CONCURRENCY",defaultMinimum:B5,defaultMaximum:$5});function gye(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 | ${gd(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: ${Up(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: ${Up(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: ${Up(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(sX(e),oX(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 Up(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${iX(t)} score-weighted)`}function iX(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function oX(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 sX(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 hye(e){let t=xl(o=>{let s=so(o,{base:e.base});return s.note?{kind:"complete",result:Qc(o,{base:e.base})}:s.changedFiles.length===0?{kind:"complete",result:Qc(o,{base:e.base})}:{kind:"batched",plan:s}}),n=t.value;if(n.kind==="complete")return{result:n.result,observationReceipt:El([t.anchor],[],["index-generation","live-workspace"])};let r=QI(n.plan.changedFiles,A5),i=await $p(r,aX(r.length),o=>uX(o,e));return{result:Zc(n.plan.changedFiles,i.map(o=>o.result)),observationReceipt:El([t.anchor],i.map(o=>o.observationReceipt),["index-generation","live-workspace"])}}var aX=mw({envKey:"SCIP_QUERY_DIFF_IMPACT_CONCURRENCY",defaultMinimum:F5,defaultMaximum:N5});function mw(e){return(t,n=process.env,r=T5)=>cX(t,n,r,e)}function cX(e,t,n,r){let i=t[r.envKey],o=lX(n,r),s=i?parseInt(i,10):o;return!Number.isFinite(s)||s<1?Math.min(o,e):Math.min(s,e)}function lX(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 uX(e,t){let n=process.argv[1]??qp(import.meta.url),r=[];return t.base&&r.push("--base",t.base),vl({cliPath:n,command:k5,args:r,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch"})}function yye(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:"),Sd.list(e.changedSymbols,n=>` ${n.file} ${n.shortName} (fan-in: ${n.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
|
|
545
|
+
Affected consumer files:`),Sd.list(e.affectedConsumers,n=>` ${n.file} (${n.consumedSymbols} symbol(s))`))}import{AsyncLocalStorage as dX}from"async_hooks";import{createHash as zp}from"crypto";import{existsSync as mX,mkdirSync as pX}from"fs";import{tmpdir as fX}from"os";import{isAbsolute as gX,join as gw,resolve as hw}from"path";var Gp=2,hX="SCIP_QUERY_SESSION",pw="SCIP_QUERY_SESSION_DIR",yX=128,uo=new dX;function Mye(e,t){let n=e.sessionEnabled===!1||e.json?void 0:TX(),r={enabled:n!==void 0,reemit:e.reemit===!0,command:e.command,projectRoot:hw(e.cwd),sessionIdentity:n,staged:[],stagedEvidence:[],finalized:!1};return uo.run(r,t)}function Tye(e){let t=uo.getStore();!t||t.finalized||(t.generationIdentity=e)}function kye(e){let t=uo.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=wX(t.staged).map(s=>({...s,ordinal:r,command:t.command})),o=PX(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(),Or(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 Aye(e){let t=e.source.split(`
|
|
546
|
+
`);if(t.length===0)return"";let n=bX(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=bd(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(oc(m)).padStart(f)} ${u}`});return[`${r}${a}${c}`,...e.blankAfterHeader?[""]:[],...e.afterHeader??[],...l].join(`
|
|
548
|
+
`)}).join(`
|
|
549
|
+
`)}function Fye(e){let t=uo.getStore();if(!t||!t.enabled)return e.content;let n=Kp(t);if(!n)return e.content;let r=yw(e.content),i=Il(n.ledger.evidence,o=>o.kind===e.kind&&o.identity===e.identity&&o.contentHash===r);if(i&&!t.reemit){let o=e.label?`; ${fw(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:kX(e.kind,e.identity,r),...e.label?{label:fw(e.label)}:{}}),e.content}function Nye(e=!1){let t=uo.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=Kp(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{Or(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=>bd(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:DX(n.ledger.ranges),evidenceItems:n.ledger.evidence.length,emissions:new Set([...r.keys(),...i.keys()]).size,rows:s}}function bX(e,t,n,r,i){let o=uo.getStore(),s=t+n.length-1;if(!o)return[{kind:"source",startLine:t,endLine:s,lines:[...n]}];let c=(o.enabled?Kp(o):null)?.ledger.ranges??[],l=n.map(yw),u=i==="exact-unit"&&!o.reemit?Il(c,h=>h.policy==="exact-unit"&&h.relativePath===e&&h.startLine===t&&h.endLine===s&&h.ownerSymbol===r&&AX(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?vX(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)=>SX(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&&CX(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 SX(e,t,n,r){let i=Il(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 vX(e,t,n,r,i){let o=Il(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 CX(e,t){return!e||!t?e===t:e.ordinal===t.ordinal&&e.command===t.command}function Kp(e){if(e.state!==void 0)return e.state;if(!e.sessionIdentity||!e.generationIdentity)return e.state=null,null;try{let t=MX();pX(t,{recursive:!0,mode:448});let n=zp("sha256").update(e.projectRoot).update("\0").update(e.generationIdentity).update("\0").update(e.sessionIdentity).digest("hex"),r=gw(t,`${n}.json`),i=Di(`${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=mX(r)?RX(JSON.parse(lt(r,"source emission session ledger")),{projectRoot:e.projectRoot,generationIdentity:e.generationIdentity,sessionIdentity:e.sessionIdentity}):xX(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 xX(e){return{version:Gp,projectRoot:e.projectRoot,generationIdentity:e.generationIdentity,sessionIdentity:e.sessionIdentity,nextOrdinal:1,updatedAt:new Date().toISOString(),ranges:[],evidence:[]}}function RX(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:Gp,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!==Gp||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(EX)||!Array.isArray(n.evidence)||!n.evidence.every(IX))throw new Error("Invalid source emission ledger.");return n}function EX(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(fi)&&(t.ownerSymbol===void 0||typeof t.ownerSymbol=="string")}function IX(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"&&fi(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 wX(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&&LX(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 LX(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 PX(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 DX(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 MX(){let e=process.env[pw];if(!e)return gw(fX(),`scip-query-source-sessions-${process.getuid?.()??"user"}`);if(!gX(e))throw new Error(`${pw} must be an absolute path.`);return hw(e)}function TX(){let e=process.env[hX]?.trim();if(e&&!(e.length>yX||!/^[A-Za-z0-9._:-]+$/.test(e)))return`explicit:${e}`}function kX(e,t,n){return`ev-${zp("sha256").update(e).update("\0").update(t).update("\0").update(n).digest("hex").slice(0,12)}`}function fw(e){let t=e.replace(/[\r\n\t]+/gu," ").replace(/\s+/gu," ").trim();return t.length<=160?t:`${t.slice(0,157)}...`}function yw(e){return zp("sha256").update(e).digest("hex")}function AX(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Il(e,t){for(let n=e.length-1;n>=0;n-=1){let r=e[n];if(t(r))return r}}import{createHash as FX}from"crypto";import{existsSync as Vp,mkdirSync as NX,rmSync as _X}from"fs";import{tmpdir as OX}from"os";import{isAbsolute as BX,join as Sw,resolve as wl}from"path";var vw=1,$X="SCIP_QUERY_SESSION",bw="SCIP_QUERY_SESSION_DIR",jX=128,Cw=8,xw=32768,Ll=new Map;function Gye(e,t,n=!0){if(!n)return;let r=Pl();if(!r)return;let i=Xp(e),o=t.map(a=>a.trim()).filter(a=>a.startsWith("scip-query system-map ")&&a.length<=xw).slice(0,Cw),s=Rw(i,r);o.length===0?Ll.delete(s):Ll.set(s,o)}function zye(e,t,n,r=!0,i){if(!r||e!=="anchors"&&e!=="system-map")return;let o=Pl();if(!o)return;let s=Xp(t),a=Jp(s,o);if(e==="system-map"){n?_X(a,{force:!0}):Vp(a)&&i&&Wp(a,()=>{let c=Yp(a,s,o);c&&Or(a,{...c,pendingMapContinuation:i,mapExecution:void 0,updatedAt:new Date().toISOString()},{spacing:2,trailingNewline:!0})});return}Wp(a,()=>{let c=HX(s,o),l={version:vw,projectRoot:s,sessionIdentity:o,mapRequired:!0,...c.length>0?{recommendedMapCommands:c}:{},updatedAt:new Date().toISOString()};Or(a,l,{spacing:2,trailingNewline:!0})})}function Kye(e,t=!0){if(!t)return;let n=Pl();if(!n)return;let r=Xp(e),i=Jp(r,n);Vp(i)&&Wp(i,()=>{let o=Yp(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&&UX(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
|
+
`));Or(i,{...o,mapExecution:{processId:process.pid,startedAt:new Date().toISOString()},updatedAt:new Date().toISOString()},{spacing:2,trailingNewline:!0})}})}function Wye(e,t,n=!0){if(!n)return;let r=Pl();if(!r)return;let i=Jp(wl(e),r);if(!Vp(i))return;let o=Yp(i,wl(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 Yp(e,t,n){try{let r=JSON.parse(lt(e,"navigation session state"));return r.version===vw&&r.projectRoot===t&&r.sessionIdentity===n&&r.mapRequired===!0&&(r.recommendedMapCommands===void 0||Array.isArray(r.recommendedMapCommands)&&r.recommendedMapCommands.length<=Cw&&r.recommendedMapCommands.every(i=>typeof i=="string"&&i.startsWith("scip-query system-map ")&&i.length<=xw))&&(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 HX(e,t){let n=Rw(e,t),r=Ll.get(n)??[];return Ll.delete(n),r}function Rw(e,t){return`${e}\0${t}`}function UX(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Jp(e,t){let n=qX();NX(n,{recursive:!0,mode:448});let r=FX("sha256").update(e).update("\0").update(t).digest("hex");return Sw(n,`navigation-${r}.json`)}function qX(){let e=process.env[bw];if(!e)return Sw(OX(),`scip-query-source-sessions-${process.getuid?.()??"user"}`);if(!BX(e))throw new Error(`${bw} must be an absolute path.`);return wl(e)}function Xp(e){let t=process.env.SCIP_QUERY_PROJECT_ROOT?.trim();return wl(t||e)}function Pl(){let e=process.env[$X]?.trim();if(e&&!(e.length>jX||!/^[A-Za-z0-9._:-]+$/u.test(e)))return`explicit:${e}`}function Wp(e,t){let n=Di(`${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{Yr as a,vo as b,mn as c,$g as d,m4 as e,Ta as f,B6 as g,zD as h,Jr as i,HA as j,XA as k,t0 as l,ts as m,Dg as n,i3 as o,ns as p,rs as q,Cc as r,uv as s,yN as t,jN as u,l8 as v,Ene as w,KN as x,QN as y,on as z,Ve as A,Ov as B,zO as C,XB as D,gs as E,bm as F,v$ as G,ci as H,lj as I,mj as J,pj as K,fj as L,Lj as M,Mj as N,Tj as O,kj as P,Fj as Q,Nj as R,_j as S,Lx as T,bs as U,Im as V,o1 as W,Ss as X,c1 as Y,l1 as Z,h1 as _,C1 as $,x1 as aa,R1 as ba,Cs as ca,Tm as da,xs as ea,LH as fa,Rs as ga,Es as ha,Am as ia,Is as ja,ws as ka,Fm as la,SU as ma,Ls as na,Iq as oa,Xq as pa,qm as qa,cG as ra,so as sa,KR as ta,UG as ua,Ds as va,SK as wa,Ts as xa,UK as ya,ks as za,AW as Aa,FW as Ba,UW as Ca,nV as Da,lV as Ea,wV as Fa,gp as Ga,iI as Ha,hp as Ia,oI as Ja,dl as Ka,n2 as La,Os as Ma,Bs as Na,$s as Oa,uY as Pa,dY as Qa,mY as Ra,wp as Sa,yl as Ta,Pp as Ua,zY as Va,IJ as Wa,wJ as Xa,PJ as Ya,MJ as Za,HJ as _a,VJ as $a,VM as ab,g8 as bb,Wa as cb,Ko as db,vb as eb,U8 as fb,q8 as gb,G8 as hb,z8 as ib,K8 as jb,W8 as kb,c9 as lb,Rb as mb,l9 as nb,Eb as ob,Ib as pb,tc as qb,pk as rb,fk as sb,gk as tb,hk as ub,Lb as vb,rc as wb,M9 as xb,ic as yb,Pb as zb,T9 as Ab,k9 as Bb,A9 as Cb,F9 as Db,xk as Eb,fd as Fb,N9 as Gb,gd as Hb,_9 as Ib,B9 as Jb,$9 as Kb,j9 as Lb,H9 as Mb,Db as Nb,Jt as Ob,yd as Pb,U9 as Qb,di as Rb,Dhe as Sb,jhe as Tb,oc as Ub,Tk as Vb,bd as Wb,z9 as Xb,Sd as Yb,cw as Zb,k5 as _b,mye as $b,pye as ac,fye as bc,J5 as cc,gye as dc,hye as ec,yye as fc,Mye as gc,Tye as hc,kye as ic,Aye as jc,Fye as kc,Nye as lc,Gye as mc,zye as nc,Kye as oc,Wye as pc};
|
|
554
|
+
//# sourceMappingURL=chunk-4UUCUASK.js.map
|