codebaseiq 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +47 -0
- package/dist/augment-vue-worker.js +1 -1
- package/dist/{chunk-DQMDCD24.js → chunk-27PHVDKL.js} +2 -2
- package/dist/{chunk-ZMI2JSX2.js → chunk-2DMVFAY7.js} +2 -2
- package/dist/{chunk-5PUWMSDU.js → chunk-2E6BTWER.js} +2 -2
- package/dist/{chunk-YESXMKX3.js → chunk-2F5ERMNI.js} +2 -2
- package/dist/chunk-2VKB5CMA.js +60 -0
- package/dist/{chunk-NNJ2KZZG.js → chunk-327YK6TB.js} +4 -4
- package/dist/chunk-347TXATM.js +2 -0
- package/dist/{chunk-VEXUL62T.js → chunk-35YYZD3D.js} +2 -2
- package/dist/chunk-36WRYYTE.js +3 -0
- package/dist/chunk-37TKC6MB.js +2 -0
- package/dist/{chunk-FAJQ7LWY.js → chunk-3AC56WAR.js} +2 -2
- package/dist/{chunk-JE3WZ6II.js → chunk-3NUZVLR7.js} +2 -2
- package/dist/{chunk-UZGZB3VB.js → chunk-3XFJUWJE.js} +2 -2
- package/dist/{chunk-OVTS4DKB.js → chunk-4AOOSCZ7.js} +2 -2
- package/dist/{chunk-LU3BMVH2.js → chunk-4IFISPQW.js} +2 -2
- package/dist/chunk-4NHWNAWQ.js +11 -0
- package/dist/chunk-4O52YNKL.js +5 -0
- package/dist/{chunk-HPJRBHVT.js → chunk-54K6556S.js} +2 -2
- package/dist/{chunk-HRWGYWRJ.js → chunk-57GCCPLS.js} +2 -2
- package/dist/{chunk-J77SU6VA.js → chunk-57KEZDPT.js} +2 -2
- package/dist/{chunk-OFBE4NGP.js → chunk-57KFVPVZ.js} +2 -2
- package/dist/{chunk-WOQBZPIF.js → chunk-5BDK6QC3.js} +2 -2
- package/dist/{chunk-7MGU3HPH.js → chunk-5IO2APSS.js} +2 -2
- package/dist/chunk-5NJPH3QZ.js +61 -0
- package/dist/{chunk-GW6Z3WGY.js → chunk-5WXOEJ4G.js} +2 -2
- package/dist/chunk-5XEVXVTK.js +3 -0
- package/dist/{chunk-RR7SX44N.js → chunk-6OVNYYY4.js} +2 -2
- package/dist/{chunk-ZV3JV5G5.js → chunk-6SDEQTVY.js} +2 -2
- package/dist/{chunk-EF2R3WNQ.js → chunk-6URCE5QY.js} +2 -2
- package/dist/{chunk-UCD3H3UZ.js → chunk-6ZV5EDUT.js} +2 -2
- package/dist/{chunk-C6SBF2WH.js → chunk-77GHPR2R.js} +2 -2
- package/dist/{chunk-YVCIMIOC.js → chunk-7R64XY4Y.js} +2 -2
- package/dist/{chunk-VXYS3FZD.js → chunk-7Z7HCZ7J.js} +2 -2
- package/dist/{chunk-CO5R3UNA.js → chunk-A67HT5FR.js} +2 -2
- package/dist/{chunk-UDS562V4.js → chunk-A7XQT7MH.js} +2 -2
- package/dist/{chunk-RDBI2RXU.js → chunk-ACZDU5GK.js} +2 -2
- package/dist/{chunk-FETNQCFO.js → chunk-AM5SUGHF.js} +2 -2
- package/dist/{chunk-NNOKTMZT.js → chunk-B2E3HZ2A.js} +2 -2
- package/dist/{chunk-CVYSU6BX.js → chunk-BH5CE4LN.js} +2 -2
- package/dist/chunk-BLKYYQ7C.js +543 -0
- package/dist/{chunk-4WKDMDEW.js → chunk-BX2U3QQV.js} +2 -2
- package/dist/{chunk-ZKX2FRS6.js → chunk-CANBLFVQ.js} +2 -2
- package/dist/{chunk-SMRBZ6EC.js → chunk-CCRZLRWJ.js} +2 -2
- package/dist/chunk-CDWSLAPN.js +21 -0
- package/dist/chunk-CIVYHK7U.js +22 -0
- package/dist/{chunk-L57ZKWVG.js → chunk-CMXW7MFV.js} +2 -2
- package/dist/{chunk-T3DGWPXM.js → chunk-CSZOQ7YO.js} +2 -2
- package/dist/{chunk-ZZXSWSN6.js → chunk-CWMHWD56.js} +2 -2
- package/dist/{chunk-6NW7MU72.js → chunk-CZEIHYMP.js} +2 -2
- package/dist/{chunk-DO6WQD2T.js → chunk-D62CTZX6.js} +2 -2
- package/dist/{chunk-XWUOUWYI.js → chunk-DFPAZXLU.js} +2 -2
- package/dist/{chunk-MOVBWNIP.js → chunk-DKJXK3HA.js} +2 -2
- package/dist/{chunk-XMQ23E27.js → chunk-DLC6JDN7.js} +2 -2
- package/dist/chunk-DUKHVPU5.js +4 -0
- package/dist/{chunk-ID63777H.js → chunk-DVYG3JTA.js} +2 -2
- package/dist/{chunk-NE6IU5ZD.js → chunk-EFFMFK7C.js} +2 -2
- package/dist/{chunk-I2T2LLK2.js → chunk-EM5UHLAM.js} +2 -2
- package/dist/chunk-EN4AHLL3.js +3 -0
- package/dist/chunk-EXMVF3JR.js +3 -0
- package/dist/{chunk-SWHMHUKF.js → chunk-FEBLLMTL.js} +2 -2
- package/dist/chunk-FIXYHQ3W.js +3 -0
- package/dist/{chunk-RKEJ6VTF.js → chunk-FLLXYUOL.js} +2 -2
- package/dist/{chunk-KWVHSKHK.js → chunk-FPDL2TUB.js} +2 -2
- package/dist/chunk-FQA3KIFX.js +17 -0
- package/dist/chunk-FWY2PRIF.js +3 -0
- package/dist/chunk-FY5V4V4F.js +2 -0
- package/dist/chunk-G2XUZCF2.js +88 -0
- package/dist/{chunk-QHRNXP3C.js → chunk-GXVDTHFC.js} +2 -2
- package/dist/{chunk-6MUIJMVL.js → chunk-H3CKAL6P.js} +2 -2
- package/dist/chunk-H5QXP63L.js +2 -0
- package/dist/{chunk-VUIYB2V3.js → chunk-HBQGKMM3.js} +2 -2
- package/dist/{chunk-PYAB5SM6.js → chunk-HBXZAGY6.js} +2 -2
- package/dist/{chunk-NNO6A2PO.js → chunk-HCMQZPEO.js} +2 -2
- package/dist/{chunk-Q65CQ4XL.js → chunk-HHBBGWES.js} +2 -2
- package/dist/{chunk-GTXSJDCO.js → chunk-HIEXRDJF.js} +2 -2
- package/dist/{chunk-4FC325IF.js → chunk-HYKSLTAR.js} +2 -2
- package/dist/{chunk-XLQ3GLWZ.js → chunk-I2KP4AGR.js} +2 -2
- package/dist/chunk-I5FCDTK2.js +2 -0
- package/dist/{chunk-QKPLA6IC.js → chunk-I645ZF75.js} +2 -2
- package/dist/{chunk-FDGD5AB5.js → chunk-IBM3F2BJ.js} +2 -2
- package/dist/{chunk-Q72QSKXC.js → chunk-IEL6Q5W3.js} +38 -38
- package/dist/{chunk-NCZUNH3E.js → chunk-IGQQUENU.js} +12 -12
- package/dist/chunk-IGYAZPRX.js +4 -0
- package/dist/chunk-IOVPAZWP.js +3 -0
- package/dist/{chunk-OL6KJP3N.js → chunk-IVJJNVSX.js} +2 -2
- package/dist/{chunk-AKB7V7TV.js → chunk-IWAMYGPN.js} +2 -2
- package/dist/chunk-IYBIBMPF.js +90 -0
- package/dist/{chunk-IOP6FWIM.js → chunk-J24VICI5.js} +2 -2
- package/dist/{chunk-C7QOQX32.js → chunk-JN5LIBT3.js} +2 -2
- package/dist/{chunk-O6QTXQPJ.js → chunk-JOALNFY3.js} +2 -2
- package/dist/{chunk-GCHRX4YW.js → chunk-JUO3Z644.js} +2 -2
- package/dist/{chunk-BJ6SQAEN.js → chunk-JXHLB7TP.js} +2 -2
- package/dist/{chunk-IJ4HMYBE.js → chunk-JYX5UZSZ.js} +2 -2
- package/dist/chunk-K2O7SBAU.js +2 -0
- package/dist/{chunk-OLF4MA5W.js → chunk-K5G7SPAG.js} +2 -2
- package/dist/{chunk-YSNONTJ2.js → chunk-KDYQQJ6X.js} +2 -2
- package/dist/{chunk-7NVGT435.js → chunk-KM4QRWI5.js} +2 -2
- package/dist/{chunk-HKQUXIFO.js → chunk-KNV5VFDV.js} +2 -2
- package/dist/chunk-L3YSDLNB.js +2 -0
- package/dist/{chunk-EZNMUY67.js → chunk-LAGDJXFY.js} +2 -2
- package/dist/{chunk-ENCCHKM6.js → chunk-LY2NB5XR.js} +4 -4
- package/dist/chunk-M4EVGA5S.js +14 -0
- package/dist/chunk-M7LAIM77.js +127 -0
- package/dist/{chunk-BVAJLC5A.js → chunk-MRGTCMDK.js} +2 -2
- package/dist/{chunk-OZYRSMSH.js → chunk-MT5W4DUG.js} +2 -2
- package/dist/{chunk-VE5AVNMP.js → chunk-MTMF4N7F.js} +2 -2
- package/dist/chunk-N3Q3AWGW.js +545 -0
- package/dist/{chunk-TXXOEMZJ.js → chunk-NDGTJHQN.js} +2 -2
- package/dist/chunk-NIO346UL.js +2 -0
- package/dist/chunk-NJA4MMBD.js +2 -0
- package/dist/{chunk-7FND7D7N.js → chunk-NK76RSB6.js} +2 -2
- package/dist/{chunk-H3LGFZVK.js → chunk-NTRW52UR.js} +2 -2
- package/dist/{chunk-JOIRNPPY.js → chunk-OJFLPVBP.js} +2 -2
- package/dist/{chunk-KMITESMT.js → chunk-OMBRP7BB.js} +2 -2
- package/dist/{chunk-UP3BUZR5.js → chunk-OVKZM2XI.js} +2 -2
- package/dist/{chunk-MVB3DAEY.js → chunk-PARCKE3Q.js} +2 -2
- package/dist/{chunk-CAUCPUOF.js → chunk-PFPHS4NO.js} +2 -2
- package/dist/chunk-PHPQ24UG.js +22 -0
- package/dist/chunk-PLZXWZHY.js +77 -0
- package/dist/{chunk-34WBMAYK.js → chunk-PNVZIJ57.js} +2 -2
- package/dist/{chunk-SYDJMPES.js → chunk-QKVTWODE.js} +2 -2
- package/dist/{chunk-FW53T7EB.js → chunk-QLTFXVUI.js} +2 -2
- package/dist/{chunk-PBI2LFKH.js → chunk-QMGWSEPL.js} +2 -2
- package/dist/{chunk-CQP3THUZ.js → chunk-QVHZB75Z.js} +2 -2
- package/dist/{chunk-6BQ3DSPK.js → chunk-QVWDQTMG.js} +2 -2
- package/dist/{chunk-ST7V3SKN.js → chunk-RCPZOPV6.js} +2 -2
- package/dist/chunk-RJWAB4VR.js +345 -0
- package/dist/chunk-RRPK327J.js +20 -0
- package/dist/chunk-RVYLJDXC.js +21 -0
- package/dist/chunk-RWKEXCHU.js +3 -0
- package/dist/{chunk-L4NRUAGJ.js → chunk-S5SKXCND.js} +2 -2
- package/dist/{chunk-RBAS5ZHI.js → chunk-S64NCE2Z.js} +2 -2
- package/dist/{chunk-WMPRTGH2.js → chunk-SF34QLK2.js} +2 -2
- package/dist/{chunk-ANFVSJWQ.js → chunk-SJZQ2PTZ.js} +2 -2
- package/dist/{chunk-4XTAUQFD.js → chunk-SRY26ITJ.js} +2 -2
- package/dist/chunk-SV2LEFVM.js +2 -0
- package/dist/{chunk-7XAN6GKB.js → chunk-T3YFIJ5P.js} +2 -2
- package/dist/chunk-T55YPJGB.js +3 -0
- package/dist/chunk-TAJ6UGCO.js +21 -0
- package/dist/{chunk-PIOMTC27.js → chunk-TUTSO7UZ.js} +2 -2
- package/dist/{chunk-FQKZWM4L.js → chunk-U24M5RQM.js} +5 -5
- package/dist/{chunk-XME3HPXZ.js → chunk-U2XX3BT4.js} +2 -2
- package/dist/{chunk-SZD2KF7Q.js → chunk-UWB5WMC2.js} +2 -2
- package/dist/{chunk-6CS3UQTN.js → chunk-VCL7FK3E.js} +2 -2
- package/dist/{chunk-N3IQCBCF.js → chunk-VCWAJPXQ.js} +2 -2
- package/dist/{chunk-LZYFLFEH.js → chunk-VG55NFXF.js} +2 -2
- package/dist/{chunk-PTAWHLVJ.js → chunk-VLTUX4IF.js} +2 -2
- package/dist/{chunk-JEJLSICM.js → chunk-VVCBMH5O.js} +2 -2
- package/dist/{chunk-JSOYNVWH.js → chunk-VYZQZ4ZN.js} +2 -2
- package/dist/chunk-W3FK73MD.js +8 -0
- package/dist/{chunk-UNBY47BC.js → chunk-W6C6QTXJ.js} +2 -2
- package/dist/chunk-WH5SYOMD.js +2 -0
- package/dist/chunk-WJOQC4P7.js +7 -0
- package/dist/chunk-WO47BIPY.js +3 -0
- package/dist/chunk-WOOTEWQT.js +239 -0
- package/dist/{chunk-UBGWN7I4.js → chunk-X5I2BQGX.js} +2 -2
- package/dist/{chunk-PX4RYAAK.js → chunk-XNUWRTYM.js} +2 -2
- package/dist/{chunk-ICFDQHAM.js → chunk-XUJM6474.js} +2 -2
- package/dist/chunk-XYLV727H.js +21 -0
- package/dist/{chunk-TRRC4ZJ7.js → chunk-YFQPWKHR.js} +2 -2
- package/dist/{chunk-NEDP5RFQ.js → chunk-YIOQJ45A.js} +2 -2
- package/dist/{chunk-Y6KHROC3.js → chunk-YXJ4IAHH.js} +2 -2
- package/dist/chunk-YYFV32WR.js +3 -0
- package/dist/{chunk-BH5F2Q4O.js → chunk-ZB3V5QM7.js} +2 -2
- package/dist/chunk-ZJZQ7Q2Q.js +3 -0
- package/dist/{chunk-EMNIHCRB.js → chunk-ZNQCR656.js} +2 -2
- package/dist/{chunk-TIIC3ZE7.js → chunk-ZOEDRCR4.js} +2 -2
- package/dist/cli-context-TSADTXLB.js +2 -0
- package/dist/cli-context-XEPPF4RX.js +3 -0
- package/dist/cli-program-KJGQEM72.js +7 -0
- package/dist/cli.js +1 -1
- package/dist/{code-DlqpBDd0.d.ts → code-CDe-mIjx.d.ts} +1 -1
- package/dist/code-viewer-YGDON6SY.js +12 -0
- package/dist/code-viewer-ZCTHXQ5C.js +11 -0
- package/dist/command-descriptors-5VAB2MZX.js +335 -0
- package/dist/command-descriptors-EAHKIRAG.js +337 -0
- package/dist/{config-types-BNoC96J3.d.ts → config-types-D6X5S68_.d.ts} +50 -0
- package/dist/{db-D7sauVFH.d.ts → db-DmRNdCtm.d.ts} +1 -1
- package/dist/direct-navigation-B3SGOOBW.js +2 -0
- package/dist/direct-navigation-ZL362KXF.js +3 -0
- package/dist/{graph-evidence-BIFqyisO.d.ts → graph-evidence-Bs54NWws.d.ts} +1 -1
- package/dist/{health-DJaZXg8I.d.ts → health-BnzbSLCE.d.ts} +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/invocation-command-descriptors-CSUGUHTT.js +2 -0
- package/dist/invocation-command-descriptors-PPVZOIE5.js +3 -0
- package/dist/output-continuation-command-FTVVBVSN.js +2 -0
- package/dist/output-continuation-command-ITPRC3YV.js +3 -0
- package/dist/project-reindex-7HZSLLLY.js +3 -0
- package/dist/project-reindex-NGM3DYBN.js +2 -0
- package/dist/queries/affected.d.ts +2 -2
- package/dist/queries/affected.js +1 -1
- package/dist/queries/anchors.d.ts +2 -2
- package/dist/queries/anchors.js +1 -1
- package/dist/queries/architecture.d.ts +2 -2
- package/dist/queries/architecture.js +1 -1
- package/dist/queries/bottlenecks.d.ts +2 -2
- 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 +2 -2
- 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 +3 -3
- 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 +2 -2
- package/dist/queries/context.js +1 -1
- package/dist/queries/convergence.d.ts +2 -2
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.d.ts +2 -2
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.d.ts +2 -2
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dataflow.d.ts +2 -2
- 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 +2 -2
- package/dist/queries/decorative-checkers.js +1 -1
- package/dist/queries/deep-chains.d.ts +2 -2
- package/dist/queries/deep-chains.js +1 -1
- package/dist/queries/dependence-slice.d.ts +3 -3
- package/dist/queries/dependence-slice.js +1 -1
- package/dist/queries/dependency-depth.d.ts +2 -2
- package/dist/queries/dependency-depth.js +1 -1
- package/dist/queries/deps.d.ts +2 -2
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-impact.d.ts +2 -2
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.d.ts +2 -2
- 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 +2 -2
- package/dist/queries/entry-map.js +1 -1
- package/dist/queries/evidence.d.ts +3 -3
- package/dist/queries/evidence.js +1 -1
- package/dist/queries/extract-candidates.d.ts +2 -2
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.d.ts +2 -2
- 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 +3 -3
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.d.ts +2 -2
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.d.ts +2 -2
- 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 +2 -2
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +5 -5
- 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 +2 -2
- 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 +2 -2
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/plan-context.d.ts +2 -2
- 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 +2 -2
- package/dist/queries/reference-neighborhood.js +1 -1
- package/dist/queries/reference-reachability.d.ts +2 -2
- package/dist/queries/reference-reachability.js +1 -1
- 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 +2 -2
- package/dist/queries/slice.js +1 -1
- package/dist/queries/source-inspection.d.ts +4 -4
- package/dist/queries/source-inspection.js +1 -1
- package/dist/queries/source-search.d.ts +2 -2
- package/dist/queries/source-search.js +1 -1
- 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 +2 -2
- 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 +2 -2
- package/dist/queries/system-map.js +1 -1
- package/dist/queries/system.d.ts +2 -2
- 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 +2 -2
- package/dist/queries/trace.js +1 -1
- package/dist/queries/twin-ab.d.ts +2 -2
- package/dist/queries/twin-ab.js +1 -1
- package/dist/queries/twin-drift.d.ts +2 -2
- 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 +3 -3
- package/dist/queries/value-flow.js +1 -1
- 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/reindex-worker.js +1 -1
- package/dist/reindex.d.ts +3 -3
- package/dist/reindex.js +31 -31
- package/dist/runtime.d.ts +24 -4
- package/dist/runtime.js +3 -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-B7N3haxa.d.ts → scip-cli-BRFKkHQn.d.ts} +1 -1
- package/dist/sentinel-ensure-command-KYYULCFU.js +2 -0
- package/dist/sentinel-ensure-command-RIZA3RY7.js +3 -0
- package/dist/sentinel-hook.js +39 -0
- package/dist/sentinel-worker.js +16 -0
- package/dist/typescript-mailbox-worker.js +1 -1
- package/dist/watch-server.js +6 -6
- package/docs/COMMAND_REFERENCE.md +5 -3
- package/docs/schemas/project-config.schema.json +159 -0
- package/package.json +9 -5
- package/skills/codebaseiq/SKILL.md +1 -1
- package/skills/concrete-plan/SKILL.md +1 -1
- package/ui/view/api.js +450 -0
- package/ui/view/app.js +394 -0
- package/ui/view/builder.js +323 -0
- package/ui/view/file-panel.js +170 -0
- package/ui/view/focus.js +379 -0
- package/ui/view/index.html +54 -0
- package/ui/view/map.js +424 -0
- package/ui/view/styles.css +1125 -0
- package/dist/chunk-2X7V4HS4.js +0 -88
- package/dist/chunk-3IER7Q6H.js +0 -12
- package/dist/chunk-3JSXXYTZ.js +0 -345
- package/dist/chunk-476NR5B7.js +0 -2
- package/dist/chunk-5VKBFZZU.js +0 -3
- package/dist/chunk-ADTBPVUZ.js +0 -21
- package/dist/chunk-BFFZDZQV.js +0 -2
- package/dist/chunk-BMYOV5GP.js +0 -77
- package/dist/chunk-C74PPYLA.js +0 -3
- package/dist/chunk-CWONGW6P.js +0 -3
- package/dist/chunk-DDZ7VHWV.js +0 -20
- package/dist/chunk-DR2LURYU.js +0 -3
- package/dist/chunk-ECQBG7PW.js +0 -564
- package/dist/chunk-FM5BPL4V.js +0 -60
- package/dist/chunk-G6XFR4ZL.js +0 -4
- package/dist/chunk-GTIYTDRE.js +0 -562
- package/dist/chunk-HOA5YGOH.js +0 -3
- package/dist/chunk-KUW32IRO.js +0 -2
- package/dist/chunk-LTA3BRZX.js +0 -2
- package/dist/chunk-NAUD7LCA.js +0 -2
- package/dist/chunk-OGTFJ3XD.js +0 -2
- package/dist/chunk-Q5ELPRKQ.js +0 -2
- package/dist/chunk-QCN62RTF.js +0 -3
- package/dist/chunk-QW7EP6WI.js +0 -21
- package/dist/chunk-RU65DDUP.js +0 -215
- package/dist/chunk-SELM5MER.js +0 -2
- package/dist/chunk-SNNWPCN7.js +0 -4
- package/dist/chunk-TFZB6XTM.js +0 -239
- package/dist/chunk-UXM43C7T.js +0 -3
- package/dist/chunk-VFY6Y2H6.js +0 -61
- package/dist/chunk-WE5RZHZ7.js +0 -5
- package/dist/chunk-Z54RD7VL.js +0 -3
- package/dist/cli-context-3SNLDYBM.js +0 -3
- package/dist/cli-context-T3B7W6GG.js +0 -2
- package/dist/cli-program-YNOXO72B.js +0 -7
- package/dist/command-descriptors-6AOUKWW7.js +0 -346
- package/dist/command-descriptors-ZFKJSRUP.js +0 -344
- package/dist/direct-navigation-DP4LVMRX.js +0 -3
- package/dist/direct-navigation-FLUS3BT6.js +0 -2
- package/dist/invocation-command-descriptors-QT2JMY5J.js +0 -3
- package/dist/invocation-command-descriptors-YN4QJEAX.js +0 -2
- package/dist/output-continuation-command-2V2SL4TD.js +0 -2
- package/dist/output-continuation-command-65J5IP3O.js +0 -3
- package/dist/project-reindex-5JOKXAXT.js +0 -2
- package/dist/project-reindex-UQBIKO4M.js +0 -3
|
@@ -0,0 +1,543 @@
|
|
|
1
|
+
import{b as Nt,c as Sl}from"./chunk-ZZ3MWF33.js";import{A as Xt,B as Lm,C as Dm,D as Pm,E as yl,F as Tm,I as Fm,J as Cr,K as Mm,L as On,M as Am,N as Nm,O as km,S as xr,T as ns,X as Hm,Y as bl,a as Kd,b as qd,c as Wd,d as Be,f as Sr,h as pl,i as gl,j as V,k as hl,l as _n,m as xm,n as yn,o as Oi,p as Rm,q as fe,r as rt,s as ri,t as es,u as Em,v as wm,w as Im,x as ts,y as Yt,z as Bn}from"./chunk-IGQQUENU.js";import{a as zm,b as Gm,c as Km,d as oi,i as rs,j as os,k as qm,l as ss,o as Wm}from"./chunk-HCMQZPEO.js";import{a as is}from"./chunk-P5XHIJHI.js";import{h as Um}from"./chunk-EXMVF3JR.js";import{c as Qm}from"./chunk-3AC56WAR.js";import{A as Nn,D as _i,E as Bi,G as bm,H as J,I as ze,J as Sm,K as vm,L as vr,M as Zo,N as Cm,O as Ge,Q as Qo,e as ee,f as dm,g as Vo,h as Mt,i as Jt,j as mm,k as At,l as Ai,m as fm,o as br,p as Ce,q as Yo,s as Xo,t as pm}from"./chunk-M7LAIM77.js";import{c as Mi,d as Jo}from"./chunk-FWY2PRIF.js";import{a as Ni,b as gm,c as k,d as re,e as kn,f as it,g as ke,h as Le,i as at,j as ki,k as hm,l as ym}from"./chunk-DRENNWRG.js";import{a as ef}from"./chunk-SV2LEFVM.js";import{T as ls,U as Ym,da as Xm,fa as cs,pa as vl,ra as Zm,t as Vm,u as si,v as Jm,y as as}from"./chunk-WJOQC4P7.js";import{G as ae,a as jt,b as Ft,c as gn,e as rm,f as om,g as ml,h as sm,i as vt,j as hr,k as Je,l as se,m as ie,n as Ko,o as qo,p as Wo,q as He,r as hn,s as yr,t as lm,x as cm,y as ye,z as um}from"./chunk-IYBIBMPF.js";import{d as Ho,p as am,q as fl}from"./chunk-XYLV727H.js";import{a as Fi,b as Fe,e as he,f as Go}from"./chunk-4NHWNAWQ.js";import{c as nm,d as im,f as dl}from"./chunk-2VKB5CMA.js";import{a as sl,j as Xd,s as tm,t as _m,u as Bm,x as Om,y as $m,z as jm}from"./chunk-ACZDU5GK.js";import{a as ft,g as Jd,i as $}from"./chunk-R2NOK63J.js";import{b as zd,c as Gd,d as Uo}from"./chunk-6URCE5QY.js";import{A as pt,B as Pt,F as pn,G as ii,S as al,T as ll,Y as Zd,_ as cl,aa as Qd,ba as ul,c as $o,ca as nt,da as St,ea as Tt,f as jo,fa as em,g as Ud,h as gr,o as Vd,y as Yd,z as zo}from"./chunk-4O52YNKL.js";import{SymbolInformation_Kind as Re}from"@c4312/scip";var us=new Map(Object.entries(Re).filter(([e,t])=>Number.isInteger(Number(e))&&typeof t=="string").map(([e,t])=>[Number(e),t])),tf=new Map([...us.entries()].map(([e,t])=>[t.toLowerCase(),e]));function Rr(e){return us.get(e)??"Unknown"}function Zt(){return[Re.Function,Re.Method,Re.Macro,Re.Constructor,Re.Getter,Re.Setter,Re.StaticMethod,Re.SingletonMethod,Re.AbstractMethod,Re.ProtocolMethod,Re.TraitMethod]}function nf(){return[Re.Class,Re.Interface,Re.Struct,Re.Trait,Re.Type,Re.TypeAlias,Re.Enum,Re.Union,Re.Protocol]}function PK(){return[Re.Constant,Re.Variable,Re.Value,Re.Field,Re.Property,Re.StaticDataMember,Re.StaticField,Re.StaticProperty,Re.StaticVariable,Re.EnumMember]}import{existsSync as yx}from"fs";import{isAbsolute as bx,join as Sx}from"path";function lt(e,t){let n=of(e,t,{allowMultiple:!1})[0]?.relativePath;return n||rf(e,t)}function bn(e,t){return of(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function rf(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),i=bx(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,r=Sx(e.config.projectRoot,i);return yx(r)?i:null}function of(e,t,n){let i=Go(e,t,n);if(i.length===0){if(rf(e,t))return[];let r=fe(e,t);return!r||e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,score:700}]}return i}function Cl(e,t){let n=bn(e,t),i=Zo(e,n,{sort:!0});if(i.length===0)return[];let r=i.map(a=>({symbol:a.symbol,shortName:a.shortName,startLine:a.startLine,endLine:a.endLine,signature:a.signature,children:[]})),o=new Map;for(let a of r)o.set(a.symbol,a);let s=[];for(let a=0;a<i.length;a++){let l=i[a],c=r[a];if(l.enclosingSymbol&&o.has(l.enclosingSymbol)){o.get(l.enclosingSymbol).children.push(c);continue}let u=null,d=1/0;for(let m of r)if(m!==c&&m.startLine<=c.startLine&&m.endLine>=c.endLine){if(m.startLine===c.startLine&&m.endLine===c.endLine&&!ym(m.symbol,c.symbol))continue;let p=m.endLine-m.startLine;p<d&&(d=p,u=m)}u?u.children.push(c):s.push(c)}return s}import{basename as LR,extname as Nf}from"path";function Ct(e,t){let n=ie(e,t.relativePath);if(n.length===0)return!1;let i=re(t.symbol);if(!i)return!1;let r=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
|
|
2
|
+
`),o=He(i);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(r)?!0:vx(n,i)}function vx(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${He(t)}\\b`);return e.some(i=>n.test(i))}import{createHash as Cx}from"crypto";import{TextDecoder as xx}from"util";var Rx=new xx("utf-8",{fatal:!0});function xl(e){return em(e.config.projectRoot)}function ds(e,t){let n=pn(t),i;try{i=ul(e.config.projectRoot,n,{inputKind:"repository text file"})}catch(o){if(St(o)||o instanceof cl)return null;throw o}let r=uf(i);return r===null?null:af(n,i,r,cf(e),lf(e))}function ms(e,t={}){let n=xl(e).filter(u=>!t.scope||u.includes(t.scope)),i=cf(e),r=lf(e),o=[],s=[],a=[],l=[],c=0;for(let u of n){let d;try{d=ul(e.config.projectRoot,u,{inputKind:"repository text file"})}catch(f){if(f instanceof cl){l.push(u);continue}if(St(f))continue;a.push(u);continue}let m=uf(d);if(m===null){s.push(u);continue}c+=d.byteLength,o.push(af(u,d,m,i,r))}return{files:o,candidateFiles:n.length,scannedBytes:c,skippedBinaryPaths:s,skippedUnreadablePaths:a,skippedOversizedPaths:l}}function af(e,t,n,i,r){let o=Cx("sha256").update(t).digest("hex");return{relativePath:e,text:n,bytes:t.byteLength,freshness:{exactText:{state:"current",basis:"working-tree-read",sha256:o},semantic:Ex(e,o,i,r)}}}function Ex(e,t,n,i){if(!i.has(e))return{state:"unavailable",basis:"no-compiler-document"};let r=n.get(e);return r?{state:r===t?"aligned":"stale",basis:"indexed-input-fingerprint"}:{state:"unavailable",basis:"fingerprint-unavailable"}}function lf(e){return new Set(e.all(`SELECT documents.relative_path FROM documents WHERE 1 = 1 ${e.pathExclusionsFor("documents")}`).map(t=>t.relative_path))}function cf(e){let t=new Map;if(!e.generation.metadataRaw)return t;let n=Ho(e.generation.metadataRaw);if(n.kind!=="legacy"&&n.kind!=="supported")return t;let i=n.metadata.fingerprint;if(!sf(i)||!Array.isArray(i.files))return t;for(let r of i.files)!sf(r)||typeof r.path!="string"||typeof r.hash!="string"||t.set(r.path,r.hash);return t}function uf(e){if(e.includes(0))return null;try{return Rx.decode(e)}catch{return null}}function sf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function fs(e,t,n={}){return ai(e,t,n).rows}function ai(e,t,n={}){let i=Er(e,[t],{additive:n.additive,semantic:n.semantic,semanticEvidence:n.semanticEvidence}),r=n.callableOnly?(i.rows.get(t.symbolId)??[]).filter(o=>it(o.symbol)||o.source==="ast-callsite"):i.rows.get(t.symbolId)??[];return{rows:typeof n.limit=="number"?r.slice(0,n.limit):r,semanticIncomplete:i.incompleteSymbolIds.has(t.symbolId),semanticUnavailable:i.unavailableSymbolIds.has(t.symbolId)}}function ps(e,t,n){return El(e,t,n).rows}function El(e,t,n){let i=Qt(e,[t],n);return{rows:i.rows.get(t.symbolId)??[],semanticIncomplete:i.incompleteSymbolIds.has(t.symbolId),semanticUnavailable:i.unavailableSymbolIds.has(t.symbolId)}}function mf(e,t,n){return Qt(e,t,n).rows}function Qt(e,t,n){let i=Px(e)?Fx(e,t,{semantic:n.semantic!==!1,semanticEvidence:n.semanticEvidence}):Tx(e,n.semanticEvidence,{semantic:n.semantic!==!1});return{rows:new Map(t.map(o=>[o.symbolId,typeof n.limit=="number"?(i.rows.get(o.symbolId)??[]).slice(0,n.limit):i.rows.get(o.symbolId)??[]])),incompleteSymbolIds:new Set(t.filter(o=>i.incompleteSymbolIds.has(o.symbolId)).map(o=>o.symbolId)),unavailableSymbolIds:new Set(t.filter(o=>i.unavailableSymbolIds.has(o.symbolId)).map(o=>o.symbolId))}}var wx=Fe("caller-rows",{clearGroups:["whole-project"]}),Ix=Fe("caller-rows-non-semantic",{clearGroups:["whole-project"]}),Lx=Fe("targeted-caller-strategy",{clearGroups:["whole-project"]}),Dx=2e4;function Px(e){return Lx.get(e,()=>(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>Dx)}function Tx(e,t,n={}){return(n.semantic===!1?Ix:wx).get(e,()=>{let r=ze(e),o=Er(e,r,{semantic:n.semantic!==!1,semanticEvidence:t}),s=new Map;for(let c of r)s.set(c.symbol,c.symbolId);let a=new Map,l=new Map;for(let c of r){let u=o.rows.get(c.symbolId);if(!(!u||u.length===0))for(let d of u){let m=s.get(d.symbol);if(m===void 0||m===c.symbolId)continue;let f=a.get(m);f||(f=[],a.set(m,f),l.set(m,new Set));let p=`${c.symbol}|${c.relativePath}`;l.get(m).has(p)||(l.get(m).add(p),f.push({symbol:c.symbol,file:c.relativePath,source:"caller-map-inversion",callEvidence:d.source}))}}return{rows:a,incompleteSymbolIds:o.incompleteSymbolIds.size===0?new Set:new Set(r.map(c=>c.symbolId)),unavailableSymbolIds:o.unavailableSymbolIds.size===0?new Set:new Set(r.map(c=>c.symbolId))}})}function Fx(e,t,n){let i=n.semantic&&n.semanticEvidence?t.flatMap(u=>{let d=Mx(e,u);return d?[d]:[]}):[],r=new Map(i.map(u=>[u.symbolId,u])),o=n.semantic&&n.semanticEvidence?n.semanticEvidence.referenceEvidenceMap(e,i):{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set},s=Mm(e,t),a=new Map;for(let u of t){let d=[],m=new Set,f=g=>{if(g.symbol===u.symbol)return;let h=`${g.symbol}|${g.file}`;m.has(h)||(m.add(h),d.push(g))};for(let g of s.get(u.symbolId)??[])g.file!==u.relativePath&&f({symbol:g.enclosingSymbol??g.file,file:g.file,source:"resolved-reference"});let p=r.get(u.symbolId);if(p)for(let g of o.rows.get(p.symbolId)??[]){if(g.file===u.relativePath||e.isIgnored(g.file))continue;let h=Ge(J(e,g.file),g.line);f({symbol:h?.symbol??g.file,file:g.file,source:"semantic-reference"})}a.set(u.symbolId,d)}let l=new Set(o.incompleteSymbolIds),c=new Set(o.unavailableSymbolIds);if(n.semantic)for(let u of t)r.has(u.symbolId)||l.add(u.symbolId);return{rows:a,incompleteSymbolIds:l,unavailableSymbolIds:c}}function Mx(e,t){let n=Zt().join(", "),i=nf().join(", ");return e.get(`SELECT
|
|
3
|
+
d.id AS documentId,
|
|
4
|
+
gs.id AS symbolId,
|
|
5
|
+
gs.symbol,
|
|
6
|
+
d.relative_path AS relativePath,
|
|
7
|
+
COALESCE(der.start_line, c.start_line) AS startLine,
|
|
8
|
+
COALESCE(der.end_line, c.end_line) AS endLine,
|
|
9
|
+
COALESCE(gs.display_name, '') AS leaf,
|
|
10
|
+
NULL AS parentTypeName,
|
|
11
|
+
CASE WHEN gs.kind IN (${n}) OR gs.symbol LIKE '%().' THEN 1 ELSE 0 END AS isFunctionLike,
|
|
12
|
+
CASE WHEN gs.kind IN (${i}) THEN 1 ELSE 0 END AS isTypeLike,
|
|
13
|
+
gs.kind AS kind,
|
|
14
|
+
gs.documentation AS documentation,
|
|
15
|
+
gs.enclosing_symbol AS enclosingSymbol
|
|
16
|
+
FROM global_symbols gs
|
|
17
|
+
LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
18
|
+
LEFT JOIN chunks c ON c.document_id = der.document_id
|
|
19
|
+
JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
|
|
20
|
+
WHERE gs.id = ?
|
|
21
|
+
LIMIT 1`,t.symbolId)??null}function wl(e,t,n={}){return Er(e,t,n).rows}function Er(e,t,n={}){if(t.length===0)return{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set};let i=n.additive??!1,r=[],o=[];for(let m of t)ye(m.relativePath)&&Jt(e,m.relativePath)!==null?r.push(m):o.push(m);let s=new Map,a=new Map,l=m=>{for(let[f,p]of m){let g=s.get(f);g||(g=[],s.set(f,g));let h=a.get(f);h||(h=new Set,a.set(f,h));for(let S of p){let v=`${S.symbol}|${S.chunkId}`;h.has(v)||(h.add(v),g.push(S))}}};r.length>0&&l(Ax(e,r));let c=new Set,u=new Set;if(n.semantic!==!1&&n.semanticEvidence){let m=n.semanticEvidence.calleeEvidenceMap(e,t);l($x(m.rows));for(let f of m.incompleteSymbolIds)c.add(f);for(let f of m.unavailableSymbolIds)u.add(f)}else if(n.semantic!==!1)for(let m of t)u.add(m.symbolId);let d=i?t:o;return d.length>0&&l(Bx(e,d)),{rows:s,incompleteSymbolIds:c,unavailableSymbolIds:u}}function Ax(e,t){let n=new Map,i=Nx(t,n),r=Xt(e);for(let[o,s]of i){let a=Jt(e,o);if(!a)continue;let l=Cm(s);for(let c of a){let u=l.get(c.line);if(!u)continue;let d=kx(e,o,r,c);d&&d.symbol!==u.symbol&&n.get(u.symbolId).push({symbol:d.symbol,file:d.file,chunkId:c.line,source:"ast-callsite",callsiteLine:c.line})}}return n}function Nx(e,t){let n=new Map;for(let i of e){let r=n.get(i.relativePath);r?r.push(i):n.set(i.relativePath,[i]),t.set(i.symbolId,[])}for(let i of n.values())i.sort((r,o)=>r.endLine-r.startLine-(o.endLine-o.startLine));return n}function kx(e,t,n,i){let r=Yt(t,n.get(i.calleeLeaf)??[]);if(r.length===0)return null;let o=_x(e,t,r,i.calleeQualifier);return o||Bn(e,t,r,i.memberAccess,i.calleeQualifier)}function _x(e,t,n,i){if(!i||ye(t)!=="clojure")return null;let o=Ce(e,t).filter(s=>s.kind==="namespace"&&s.localName===i&&s.sourcePath).map(s=>s.sourcePath);for(let s of o){let a=n.find(l=>Pt(s,l.file));if(a)return a}return n.find(s=>/`([^`]+)`\//.exec(s.symbol)?.[1]===i)??null}function Bx(e,t){if(t.length===0)return new Map;let i=Rl(t.map(f=>f.documentId)).flatMap(f=>e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
|
|
22
|
+
FROM mentions m
|
|
23
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
24
|
+
WHERE m.role != 1
|
|
25
|
+
AND c.document_id IN (${f.map(()=>"?").join(",")})`,...f)),r=new Map;for(let f of i)r.has(f.document_id)||r.set(f.document_id,[]),r.get(f.document_id).push(f);let s=Rl(i.map(f=>f.symbol_id)).flatMap(f=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
|
|
26
|
+
COALESCE(der.document_id, def_chunk.document_id) AS document_id
|
|
27
|
+
FROM global_symbols gs
|
|
28
|
+
LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
29
|
+
LEFT JOIN (
|
|
30
|
+
SELECT m.symbol_id, MIN(c.document_id) AS document_id
|
|
31
|
+
FROM mentions m
|
|
32
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
33
|
+
WHERE m.role = 1
|
|
34
|
+
AND m.symbol_id IN (${f.map(()=>"?").join(",")})
|
|
35
|
+
GROUP BY m.symbol_id
|
|
36
|
+
) def_chunk ON def_chunk.symbol_id = gs.id
|
|
37
|
+
WHERE gs.id IN (${f.map(()=>"?").join(",")})`,...f,...f)),a=Rl([...t.map(f=>f.documentId),...s.flatMap(f=>f.document_id===null?[]:[f.document_id])]),l=new Map(a.flatMap(f=>e.all(`SELECT id, relative_path FROM documents
|
|
38
|
+
WHERE id IN (${f.map(()=>"?").join(",")})`,...f).map(p=>[p.id,p.relative_path]))),c=new Map;for(let f of s)c.has(f.symbol_id)||c.set(f.symbol_id,{symbol:f.symbol,file:f.document_id!==null?l.get(f.document_id)??"":""});let u=new Map,d=l,m=Ox(t);for(let[f,p]of m){let h=[...r.get(f)??[]].sort((E,w)=>E.start_line-w.start_line||E.end_line-w.end_line),S=[...p].sort((E,w)=>E.startLine-w.startLine||E.endLine-w.endLine),v=new Set,y=0;for(let E of S){for(;y<h.length&&h[y].start_line<=E.endLine;)v.add(h[y]),y+=1;for(let L of v)L.end_line<E.startLine&&v.delete(L);let w=new Set,b=[],R=null,C=()=>{if(R)return R;let L=d.get(E.documentId)??"",I=new Set;if(L){let x=Rm(e,L),P=Math.max(0,E.startLine),_=Math.min(x.length-1,E.endLine);for(let D=P;D<=_;D+=1)for(let T of x[D])I.add(T)}return R=I,I};for(let L of v){if(L.symbol_id===E.symbolId)continue;let I=c.get(L.symbol_id);if(!I)continue;if(!(L.start_line>=E.startLine&&L.end_line<=E.endLine)){if(!(L.start_line<=E.endLine&&L.end_line>=E.startLine))continue;let D=re(I.symbol);if(!D||!C().has(D))continue}let P=`${I.symbol}|${L.chunk_id}`;w.has(P)||(w.add(P),b.push({...I,chunkId:L.chunk_id,source:"scip-chunk"}))}u.set(E.symbolId,b)}}return u}var df=500;function Rl(e){let t=[...new Set(e)],n=[];for(let i=0;i<t.length;i+=df)n.push(t.slice(i,i+df));return n}function Ox(e){let t=new Map;for(let n of e){let i=t.get(n.documentId);i?i.push(n):t.set(n.documentId,[n])}return t}function $x(e){let t=new Map;for(let[n,i]of e){let r=[];for(let o of i)r.push({symbol:o.symbol,file:o.file,chunkId:-1,source:"semantic-callee",...o.callsiteLine===void 0?{}:{callsiteLine:o.callsiteLine}});t.set(n,r)}return t}var jx=12,Hx=280;function $i(e,t,n,i){let r=Ux(e,t,n,i);if(r.size===0)return qx();let o=[],s=new Set,a=(c,u,d,m)=>{if(u===t&&d<=i&&m>=n)return;let f=`${u}:${d}:${m}:${c}`;s.has(f)||(s.add(f),o.push({name:c,relativePath:u,startLine:d,endLine:m}))};for(let c of J(e,t))r.has(c.leaf)&&a(c.leaf,c.relativePath,c.startLine,c.endLine);for(let c of Ce(e,t)){let u=c.localName;if(!u||!r.has(u)||!c.sourcePath||c.kind==="namespace")continue;let d=c.importedName==="default"?u:c.importedName;for(let m of _n(e,c.sourcePath,d,{maxReexportDepth:3}))a(u,m.relativePath,m.startLine,m.endLine)}o.sort(pf);let l=o.map(c=>{let u=zx(e,c);return u?{...c,source:u}:null}).filter(c=>c!==null).slice(0,jx);return Il(l)}function gs(e,t=[]){return Il(Gx(e.flatMap(n=>n?.inline??[]),t))}function ff(e){return e?e.inline.reduce((t,n)=>t+n.name.length+n.source.length+32,0):0}function Ux(e,t,n,i){let r=ee(e,t),o=new Set;if(!r)return o;for(let s=n;s<=i;s+=1)for(let a of r.identifiersByLine[s]??[])o.add(a);return o}function zx(e,t){if(t.startLine!==t.endLine)return null;let n=(ie(e,t.relativePath)[t.startLine]??"").trim();if(!n||n.length>Hx)return null;let i=n.indexOf("=");if(i<0||n[i+1]===">")return null;let r=n.slice(i+1).replace(/(?:\/\/|#).*$/u,"").trim();if(!r||r.includes("${")||/\b(?:function|class|struct|interface|trait|enum|lambda)\b/u.test(r))return null;let s=r.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(c=>!a.has(c))?null:n}function Gx(e,t){let n=new Map;for(let i of e){if(Kx(i,t))continue;let r=`${i.relativePath}:${i.startLine}:${i.endLine}:${i.name}`;n.has(r)||n.set(r,{...i})}return[...n.values()].sort(pf)}function Kx(e,t){return t.some(n=>n.relativePath===e.relativePath&&n.startLine<=e.startLine&&n.endLine>=e.endLine)}function pf(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||e.name.localeCompare(t.name)}function Il(e){return{coverage:"indexed-project-literal-values",inline:e}}function qx(){return Il([])}var Wx=12,Vx=20,Dl=200,Pl=800,Jx=.9,hf={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"},Cs=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],yf=[...Cs,"lifecycle"],bf=["loop","await","throw","mutation","spread","catch","finally","lifecycle"],Yx=new Set(["onBeforeMount","onBeforeUnmount","onMounted","onUnmounted","useEffect","useInsertionEffect","useLayoutEffect"]);var Sf=new Set(["object","object_pattern","dictionary","field_declaration_list","struct_expression","struct_pattern"]);function ji(e,t,n,i,r=[],o={}){let s=ae(e,t);if(!s)return null;let a=ie(e,t),l=gt(e,t,n,i,r),c=Es(e,t,l.startLine,l.endLine),u=c?.startLine??n,d=c?.endLine??i,m=(c?Hi(s.rootNode,l.startLine,l.endLine):null)??Mr(s.rootNode,u,d);if(!m)return null;let f=Ef(m,a,u,d,r);if(!f||f.lines.length===0||f.lines.some(S=>S.text.length>Pl))return null;let p=pR(a,u,d),g=gR(f);if((o.requireSavings??!0)&&g>=p*Jx)return null;let h=Cs.filter(S=>f.lines.some(v=>v.signals.includes(S)));return{...c?{callable:{name:c.name,startLine:c.startLine,endLine:c.endLine}}:{},representation:"outline",constructKind:f.constructKind,signature:f.signature,lines:f.lines,signals:h,testCases:V(t)==="test"?vR(a,u,d):[],coverage:{sourceStatements:f.sourceStatements,representedStatements:f.sourceStatements,copiedStatements:f.copiedStatements,omittedStatements:0},rawCharacters:p,outlineCharacters:g,candidateLines:f.sourceStatements,omittedLines:0}}function xs(e,t,n,i,r){if(r.length===0)return[];let o=ae(e,t);if(!o)return[];let s=ie(e,t),a=gt(e,t,n,i,r),l=Es(e,t,a.startLine,a.endLine),c=l?.startLine??n,u=l?.endLine??i,d=(l?Hi(o.rootNode,a.startLine,a.endLine):null)??Mr(o.rootNode,c,u);if(!d)return[];let m=Ef(d,s,c,u,r);return m?m.lines.filter(f=>f.text.length<=Pl&&f.signals.some(p=>["branch","loop","catch","finally"].includes(p))&&r.some(p=>p>=f.line&&p<=f.endLine)):[]}function vf(e,t,n,i){let r=ae(e,t);if(!r)return null;let o=Hi(r.rootNode,n,i)??Mr(r.rootNode,n,i);if(!o)return null;let s=[],a=Ml(o),l=[];return Al(o,o,c=>{if(Ir.has(c.type)||Xx.has(c.type)){Qx(s,l,c);return}if(Rs.has(c.type)){eR(s,l,c);return}if(Tr.has(c.type)){tR(s,l,c);return}Fr.has(c.type)&&nR(s,c)}),{facts:aR(s),terminals:Rf(a),unsupported:l}}function gt(e,t,n,i,r=[]){let o=r.filter(d=>d>=n&&d<=i),s=ae(e,t);if(o.length>0&&s){let d=[];li(s.rootNode,f=>{lR(f)&&f.startPosition.row>=n&&f.endPosition.row<=i&&o.every(p=>f.startPosition.row<=p&&f.endPosition.row>=p)&&d.push(f)});let m=d.sort((f,p)=>f.endPosition.row-f.startPosition.row-(p.endPosition.row-p.startPosition.row)||f.startPosition.row-p.startPosition.row)[0];if(m)return{startLine:m.startPosition.row,endLine:m.endPosition.row}}let a=Es(e,t,n,i);if(a)return{startLine:a.startLine,endLine:a.endLine};if(o.length===0)return{startLine:n,endLine:i};let l=(ee(e,t)?.callables??[]).filter(d=>d.startLine>=n&&d.endLine<=i&&o.every(m=>d.startLine<=m&&d.endLine>=m)).sort((d,m)=>d.endLine-d.startLine-(m.endLine-m.startLine)||d.startLine-m.startLine)[0];if(!s)return l?{startLine:l.startLine,endLine:l.endLine}:{startLine:n,endLine:i};let c=[];li(s.rootNode,d=>{$n.has(d.type)&&d.startPosition.row>=n&&d.endPosition.row<=i&&o.every(m=>d.startPosition.row<=m&&d.endPosition.row>=m)&&c.push(d)});let u=c.sort((d,m)=>d.endPosition.row-d.startPosition.row-(m.endPosition.row-m.startPosition.row)||d.startPosition.row-m.startPosition.row)[0];return u?{startLine:u.startPosition.row,endLine:u.endPosition.row}:l?{startLine:l.startLine,endLine:l.endLine}:{startLine:n,endLine:i}}function Tl(e,t,n,i,r={}){if(i-n+1<(r.minimumBodyLines??Vx))return null;let s=If(e,t,n,i,[],!1);if(!s)return null;let a=s.candidates.map(S=>({...S,signals:S.signals.filter(v=>v!=="anchor"&&v!=="signature")})).filter(S=>S.signals.length>0);if(a.length===0)return null;let l=bR(a),c=a.filter(S=>S.text.length<=Dl);if(c.length===0)return null;let u=bf.filter(S=>(l[S]??0)>0),d=u.filter(S=>S!=="await"),m=s.shapes.reduce((S,v)=>S+v.fields.length,0);if(d.length===0&&!((l.await??0)>0&&m>0)&&m<3)return null;let f=SR(c,l),p=new Map;for(let S of u){let v=f.find(y=>y.signals.includes(S));v&&p.set(v.line,v)}if(p.size===0){let S=f.find(v=>v.signals.includes("branch"));S&&p.set(S.line,S)}let g=Math.min(10,Math.max(1,r.maxLines??p.size)),h=new Map;for(let S of p.values()){if(h.size>=g)break;h.set(S.line,S)}return h.size>=a.length&&s.shapes.length===0?null:{owner:s.callable?.name??null,startLine:n,endLine:i,lines:[...h.values()].sort((S,v)=>S.line-v.line),shapes:s.shapes,signalCounts:l,candidateLines:a.length,omittedLines:a.length-h.size}}function Sn(e,t,n,i){let r=If(e,t,n,i,[],!1);return r?new Map(r.candidates.map(o=>[o.line,o.signals.filter(s=>s!=="lifecycle")])):new Map}var $n=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"]),xt=new Set(["block","body","compound_statement","declaration_list","statement_block"]),Ir=new Set(["if_expression","if_statement","unless","unless_statement"]),Xx=new Set(["conditional_expression","ternary_expression"]),Rs=new Set(["do_statement","enhanced_for_statement","for_expression","for_in_statement","for_of_statement","for_statement","loop_expression","while_statement"]),Tr=new Set(["match_expression","match_statement","switch_expression","switch_statement"]),Cf=new Set(["case_statement","match_arm","switch_case","switch_default"]),Fr=new Set(["try_expression","try_statement"]),bs=new Set(["catch_clause","except_clause","rescue"]),Dr=new Set(["ensure","finally_clause"]),Lr=new Set(["else","else_clause"]),xf=new Set(["raise_statement","return_statement","throw_statement"]),Zx=new Set(["block_comment","comment","line_comment"]);function Qx(e,t,n){let i=n.childForFieldName("condition")??kl(n),r=n.childForFieldName("consequence")??n.childForFieldName("body")??n.namedChildren.find(l=>xt.has(l.type)),o=n.childForFieldName("alternative")??n.namedChildren.find(l=>Lr.has(l.type));if(!i||!r){t.push(Nl(n,"conditional-fields-unresolved"));return}let s=tn(i,"predicate",i.text),a=tn(r,gf(r),"consequence");if(en(e,s,a,"predicate-consequence",{branchRole:"consequence"}),Ss(e,s,r,"consequence"),o){let l=tn(o,gf(o),"alternative");en(e,s,l,"predicate-alternative",{branchRole:"alternative"}),Ss(e,s,o,"alternative");return}en(e,s,Fl(s,"otherwise continue"),"predicate-fallthrough",{branchRole:"fallthrough"})}function eR(e,t,n){let i=n.childForFieldName("body")??n.namedChildren.find(s=>xt.has(s.type));if(!i){t.push(Nl(n,"loop-body-unresolved"));return}let r=n.childForFieldName("condition"),o=tn(r??n,"predicate",r?.text??Ht(n,i));en(e,o,tn(i,"outcome","iteration"),"loop-iteration",{branchRole:"iteration"}),Ss(e,o,i,"iteration"),en(e,o,Fl(o,"loop exits"),"loop-exit",{branchRole:"exit"})}function tR(e,t,n){let i=n.childForFieldName("body")??n.namedChildren.find(l=>xt.has(l.type)),r=n.childForFieldName("value")??n.childForFieldName("condition")??n.childForFieldName("subject")??kl(n),o=rR(i??n);if(!r||o.length===0){t.push(Nl(n,"switch-cases-unresolved"));return}let s=tn(r,"predicate",r.text),a=!1;for(let l of o){let c=sR(l);a||=c;let u=Ht(l,l.namedChildren.find(d=>vs(d)));en(e,s,tn(l,"outcome",u||(c?"default":"case")),c?"predicate-default":"predicate-case",{branchRole:c?"default":"case"}),Ss(e,s,l,c?"default":"case")}a||en(e,s,Fl(s,"no case matched"),"predicate-fallthrough",{branchRole:"fallthrough"})}function nR(e,t){let n=tn(t,"scope","try");for(let i of oR(t)){let r=Dr.has(i.type),o=tn(i,"handler",r?"finally":Ht(i,hs(i)));en(e,n,o,r?"finally-cleanup":"exception-handler",{branchRole:r?"finally":"catch"}),iR(e,o,i,r?"finally":"catch")}}function iR(e,t,n,i){for(let r of Ml(n)){let o=r.label.startsWith("throw")||r.label.startsWith("raise")?"throw":"return";en(e,t,r,o==="throw"?"handler-throw":"handler-return",{branchRole:i,terminalKind:o})}}function Ss(e,t,n,i){for(let r of Ml(n)){let o=r.label.startsWith("throw")||r.label.startsWith("raise")?"throw":"return";en(e,t,r,o==="throw"?"predicate-throw":"predicate-return",{branchRole:i,terminalKind:o})}}function en(e,t,n,i,r){e.push({controller:t,outcome:n,subtype:i,attributes:r})}function tn(e,t,n){return{kind:t,label:Pr(n).slice(0,Pl),startLine:e.startPosition.row,endLine:e.endPosition.row,implicit:!1}}function Fl(e,t){return{...e,kind:"outcome",label:t,implicit:!0}}function gf(e){return xf.has(e.type)?"terminal":"outcome"}function Ml(e){let t=[];return Al(e,e,n=>{xf.has(n.type)&&t.push(tn(n,"terminal",n.text))}),Rf(t)}function Al(e,t,n){n(t);for(let i of t.namedChildren)i!==e&&$n.has(i.type)||Al(e,i,n)}function rR(e){let t=[],n=i=>{for(let r of i.namedChildren)Tr.has(r.type)||(Cf.has(r.type)?t.push(r):n(r))};return n(e),t}function oR(e){let t=[],n=i=>{for(let r of i.namedChildren)Fr.has(r.type)||(bs.has(r.type)||Dr.has(r.type)?t.push(r):$n.has(r.type)||n(r))};return n(e),t}function sR(e){let t=Ht(e,e.namedChildren.find(n=>vs(n))).trim();return e.type==="switch_default"||/^(?:default\b|_\s*=>)/u.test(t)}function Nl(e,t){return{startLine:e.startPosition.row,endLine:e.endPosition.row,reason:t}}function aR(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 Rf(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 lR(e){return $n.has(e.type)||Rs.has(e.type)||Tr.has(e.type)||Fr.has(e.type)||bs.has(e.type)||Dr.has(e.type)}function Ef(e,t,n,i,r){let s=Hi(e,n,i)??e,a=hs(s),l=[],c=0,u=0,d=(b,R,C,L,I=!1,x=!0)=>{let P=I?C.trim():Pr(C);if(!P)return;let _=Math.max(n,b.startPosition.row),D=Math.min(i,b.endPosition.row);l.push({line:_,endLine:Math.max(_,D),depth:R,signals:Cs.filter(T=>L.includes(T)||T==="anchor"&&r.some(A=>A>=_&&A<=D)),text:P,copied:I}),x&&(c+=1,I&&(u+=1))},m=(b,R)=>{for(let C of b.namedChildren)w(C,R)},f=(b,R)=>{if(Ir.has(b.type)){p(b,R,"else if");return}if(Lr.has(b.type)){let C=b.namedChildren.find(I=>Ir.has(I.type));if(C){p(C,R,"else if");return}d(b,R,"else",["branch"],!1,!1);let L=hs(b)??b.namedChildren.find(I=>xt.has(I.type));if(L)w(L,R+1);else for(let I of b.namedChildren)w(I,R+1);return}d(b,R,"else",["branch"],!1,!1),w(b,R+1)},p=(b,R,C=b.type.startsWith("unless")?"unless":"if")=>{let L=b.childForFieldName("condition")??kl(b),I=b.childForFieldName("consequence")??b.childForFieldName("body")??b.namedChildren.find(_=>xt.has(_.type)),x=b.childForFieldName("alternative")??b.namedChildren.find(_=>Lr.has(_.type)),P=L?L.text:Ht(b,I);d(b,R,`${C} ${mR(P)}`,wr(L,["branch"])),I&&w(I,R+1),x&&f(x,R)},g=(b,R)=>{let C=b.childForFieldName("body")??b.namedChildren.find(L=>xt.has(L.type));d(b,R,Ht(b,C),wr(b,["loop"])),C&&w(C,R+1)},h=(b,R)=>{let C=b.childForFieldName("body")??b.namedChildren.find(L=>xt.has(L.type));d(b,R,Ht(b,C),wr(b,["branch"])),C&&w(C,R+1)},S=(b,R)=>{let C=b.namedChildren.find(L=>vs(L));d(b,R,Ht(b,C),["branch"],!1,!1);for(let L of b.namedChildren)(L===C||vs(L))&&w(L,R+1)},v=(b,R)=>{d(b,R,"try",[],!1);for(let C of b.namedChildren)xt.has(C.type)?w(C,R+1):(bs.has(C.type)||Dr.has(C.type))&&w(C,R)},y=(b,R,C)=>{let L=b.childForFieldName("body")??b.namedChildren.find(x=>xt.has(x.type)),I=C==="finally"?"finally":Ht(b,L);d(b,R,I,[C],!1,!1),L&&w(L,R+1)},E=(b,R)=>{let C=hs(b);d(b,R,Ht(b,C),wr(b,["binding"])),C&&w(C,R+1)},w=(b,R)=>{if(b.startPosition.row>i||b.endPosition.row<n||Zx.has(b.type)||b.type==="empty_statement")return;if(xt.has(b.type)){m(b,R);return}if(Ir.has(b.type)){p(b,R);return}if(Rs.has(b.type)){g(b,R);return}if(Tr.has(b.type)){h(b,R);return}if(Cf.has(b.type)){S(b,R);return}if(Fr.has(b.type)){v(b,R);return}if(bs.has(b.type)){y(b,R,"catch");return}if(Dr.has(b.type)){y(b,R,"finally");return}if(Lr.has(b.type)){f(b,R);return}if($n.has(b.type)){E(b,R);return}let L=!wf(b)||fR(b);d(b,R,b.text,wr(b),L)};return w(a&&a!==s?a:s,0),c===0?null:{constructKind:dR(s),signature:uR(s,a,t,n),lines:l,sourceStatements:c,copiedStatements:u}}function Hi(e,t,n){let i=e.namedChildren.filter(r=>r.startPosition.row<=t&&r.endPosition.row>=n);for(let r of i.sort(cR)){let o=Hi(r,t,n);if(o)return o}return $n.has(e.type)&&e.startPosition.row<=t&&e.endPosition.row>=n?e:null}function cR(e,t){return e.endPosition.row-e.startPosition.row-(t.endPosition.row-t.startPosition.row)||e.startPosition.row-t.startPosition.row}function hs(e){return e.childForFieldName("body")??e.childForFieldName("consequence")??e.namedChildren.find(t=>xt.has(t.type))??null}function uR(e,t,n,i){let r=Ht(e,t);return r||(n[i]??e.text).trim()}function dR(e){return e.type.includes("constructor")?"constructor":e.type.includes("method")||e.type==="method"?Ll(e,new Set(["class_body","class_declaration","class_definition"]))?"class method":"object method":e.type==="arrow_function"||e.type==="function_expression"||e.type==="lambda"?Ll(e,new Set(["object","pair"]))?"object member":"function value":e.type.includes("function")?Ll(e,$n)?"nested function":"module function":"source construct"}function Ll(e,t){let n=e.parent;for(;n;){if(t.has(n.type))return!0;n=n.parent}return!1}function kl(e){return e.namedChildren.find(t=>!xt.has(t.type)&&!Lr.has(t.type))??null}function Ht(e,t){if(!t)return Pr(e.text);let n=Math.max(0,t.startIndex-e.startIndex);return Pr(e.text.slice(0,n)).replace(/[:{]\s*$/u,"").trim()}function mR(e){let t=Pr(e);return t.startsWith("(")&&t.endsWith(")")?t.slice(1,-1).trim():t}function Pr(e){return e.trim().replace(/\r?\n[\t ]*/gu," ")}function wr(e,t=[]){let n=new Set(t);return e&&li(e,i=>{let r=hf[i.type];r&&n.add(r),i.type==="call_expression"&&(n.add("call"),Lf(i)&&n.add("shape")),_l.has(i.type)&&n.add("binding")}),Cs.filter(i=>n.has(i))}function fR(e){let t=!1;return li(e,n=>{t||!n.text.includes(`
|
|
39
|
+
`)||/(?:string|template|heredoc|raw_string)/u.test(n.type)&&(t=!0)}),t}function vs(e){return xt.has(e.type)||Ir.has(e.type)||Rs.has(e.type)||Tr.has(e.type)||Fr.has(e.type)||$n.has(e.type)||wf(e)}function wf(e){return/(?:statement|declaration|expression|assignment|return|throw|raise|break|continue|yield|with_item)$/u.test(e.type)||_l.has(e.type)}function pR(e,t,n){let i=0;for(let r=t;r<=n;r+=1)i+=(e[r]?.length??0)+10;return i}function gR(e){return e.constructKind.length+e.signature.length+80+e.lines.reduce((t,n)=>t+n.text.length+n.depth*2+10,0)}function If(e,t,n,i,r,o){let s=ae(e,t);if(!s)return null;let a=ie(e,t),l=Es(e,t,n,i),c=o?l?.startLine??n:n,u=o?l?.endLine??i:i,m=(l?.startLine===c&&l.endLine===u?Hi(s.rootNode,c,u):null)??Mr(s.rootNode,c,u);if(!m)return null;let f=new Map,p=new Map,g=new Map,h=(y,E)=>{if(y<c||y>u)return;let w=f.get(y)??new Set;w.add(E),f.set(y,w)};l&&h(l.startLine,"signature");for(let y of r)h(y,"anchor");li(m,y=>{let E=hf[y.type];if(E&&h(y.startPosition.row,E),E==="shape"&&hR(p,y,m,c,u),y.type==="call_expression"){let b=(y.childForFieldName("function")??y.namedChild(0))?.text.split(".").at(-1);if(Lf(y)){h(y.startPosition.row,"shape");let R=ys(y.text);R.length<=Dl&&g.set(y.startPosition.row,R)}if(b&&Yx.has(b)){h(y.startPosition.row,"lifecycle");let R=ys(y.text);R.length<=Dl&&g.set(y.startPosition.row,R)}}_l.has(y.type)&&h(y.startPosition.row,"binding")});let S=ee(e,t);for(let y of S?.callSites??[])y.line<c||y.line>u||(h(y.line,"call"),y.calleeLeaf==="catch"&&h(y.line,"catch"));let v=[...f.entries()].sort(([y],[E])=>y-E).map(([y,E])=>({line:y,signals:yf.filter(w=>E.has(w)),text:g.get(y)??ys(a[y]??"")})).filter(y=>y.text.length>0||y.signals.includes("anchor"));return{...l?{callable:l}:{},rangeStart:c,rangeEnd:u,sourceLines:a,candidates:v,shapes:[...p.values()].sort((y,E)=>y.startLine-E.startLine)}}function hR(e,t,n,i,r){if(t.startPosition.row<i||t.endPosition.row>r)return;let o=t.childForFieldName("key")??t.childForFieldName("name")??t.namedChild(0),s=ys(o?.text??"");if(!s||s.includes(`
|
|
40
|
+
`)||s.length>60)return;let a=yR(t,n);if(a.startPosition.row<i||a.endPosition.row>r)return;let l=`${a.startPosition.row}:${a.endPosition.row}`,c=e.get(l)??{startLine:a.startPosition.row,endLine:a.endPosition.row,fields:[]};c.fields.some(u=>u.name===s&&u.line===t.startPosition.row)||c.fields.push({name:s,line:t.startPosition.row}),e.set(l,c)}function yR(e,t){let n=e.parent;for(;n&&n!==t.parent;){if(Sf.has(n.type))return n;if(n===t)break;n=n.parent}return e.parent??e}function Es(e,t,n,i){return ee(e,t)?.callables.filter(r=>r.startLine<=n&&r.endLine>=i).sort((r,o)=>r.endLine-r.startLine-(o.endLine-o.startLine)||r.startLine-o.startLine)[0]}function Mr(e,t,n){if(e.startPosition.row>t||e.endPosition.row<n)return null;for(let i of e.namedChildren){let r=Mr(i,t,n);if(r)return r}return e}function li(e,t){t(e);for(let n of e.namedChildren)li(n,t)}function ys(e){return e.trim().replace(/\s+/gu," ")}function Lf(e){if(e.type!=="call_expression")return!1;let t=e.childForFieldName("arguments")??e.namedChildren.find(i=>i.type==="arguments"||i.type==="argument_list");if(!t)return!1;let n=!1;return li(t,i=>{Sf.has(i.type)&&(n=!0)}),n}function bR(e){let t={};for(let n of yf){let i=e.filter(r=>r.signals.includes(n)).length;i>0&&(t[n]=i)}return t}function SR(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 i=new Set(bf),r=o=>{let s=n.get(o.signals.join(","))??1,a=Math.min(...o.signals.map(u=>t[u]??1)),l=o.signals.some(u=>i.has(u))?3:1,c=Math.max(0,o.signals.length-1)*1e3;return l*(1e3/s+1e3/a)+c};return[...e].sort((o,s)=>r(s)-r(o)||s.line-o.line)}var _l=new Set(["lexical_declaration","variable_declarator","const_item","static_item","let_declaration","assignment"]);function vR(e,t,n){let i=[],r=/\b(?:describe|it|test)(?:\.(?:only|skip|todo))?\s*\(\s*(['"`])([^'"`]+)\1/u;for(let o=t;o<=n;o+=1){let s=r.exec(e[o]??"")?.[2];if(!(!s||i.includes(s))&&(i.push(s),i.length>=Wx))break}return i}var CR=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 Ui(e,t,n){let i=ae(e,t)?.rootNode??null,r=xR(i,n);if(!r)return null;let o=ie(e,t);if(o.length===0)return null;let s=Math.max(0,r.startPosition.row),a=r.endPosition.column===0?r.endPosition.row-1:r.endPosition.row;return{type:r.type,startLine:s,endLine:Math.min(o.length-1,Math.max(s,a))}}function Ar(e,t,n,i,r){let o=gt(e,t,i,r,[n]),s=o.startLine===o.endLine&&/(?:=>|\(|\{|\[|,)\s*$/u.test(ie(e,t)[o.startLine]??"");if(!s&&(o.startLine>i||o.endLine<r))return o;let a=Ui(e,t,n);return s&&a?{startLine:a.startLine,endLine:a.endLine}:a&&a.startLine>=i&&a.endLine<=r?{startLine:a.startLine,endLine:a.endLine}:{startLine:i,endLine:r}}function xR(e,t){if(!e||!Tf(e,t))return null;let n=Pf(e,t);for(;n;){if(CR.has(n.type))return n;n=n.parent}return null}function Pf(e,t){let n=e.namedChildren.filter(i=>Tf(i,t)).sort((i,r)=>Df(i)-Df(r));return n.length>0?Pf(n[0],t):e}function Tf(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function Df(e){return e.endIndex-e.startIndex}var RR=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 ws(e,t,n,i){if(!Number.isSafeInteger(n)||n<0)return null;if(!Number.isSafeInteger(i)||i<0)throw new RangeError(`contextLines must be a non-negative safe integer; received ${i}`);let r=ie(e,t);if(r.length===0||n>=r.length)return null;let o=Math.max(0,n-i),s=Math.min(r.length-1,n+i);return{relativePath:t,startLine:o,endLine:s,focusLine:n,source:r.slice(o,s+1).join(`
|
|
41
|
+
`)}}function Ff(e,t,n,i,r){let o=ws(e,t,n,i);if(!o)return null;let s=ae(e,t)?.rootNode??null;if(!s)return{...o,kind:"bounded-context"};let a=ER(s,n,r);if(a.length!==1)return{...o,kind:a.length===0?"non-call-reference":"bounded-context"};let l=a[0],c=ie(e,t),u=Math.max(0,l.startPosition.row),d=l.endPosition.column===0?l.endPosition.row-1:l.endPosition.row,m=Math.min(c.length-1,Math.max(u,d));return{relativePath:t,startLine:u,endLine:m,focusLine:n,source:c.slice(u,m+1).join(`
|
|
42
|
+
`),kind:"complete-call-expression"}}function Mf(e,t,n,i,r){if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`maxLines must be a positive safe integer; received ${r}`);let o=ie(e,t);if(o.length===0||n<0||n>=o.length)return null;let s=Math.min(o.length-1,i,n+r-1);return{relativePath:t,startLine:n,endLine:s,focusLine:n,source:o.slice(n,s+1).join(`
|
|
43
|
+
`)}}function jn(e,t,n,i,r=6){if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`maxLines must be a positive safe integer; received ${i}`);let o=ie(e,t);if(o.length===0||n<0||n>=o.length)return null;let s=Ui(e,t,n);if(!s){let g=ws(e,t,n,r);return g?{...g,unitType:null,unitStartLine:g.startLine,unitEndLine:g.endLine,omittedLines:0}:null}let a=s.startLine,l=s.endLine,c=l-a+1,u=Math.min(c,i),d=n-a-Math.floor(u/2),m=Math.max(0,Math.min(c-u,d)),f=a+m,p=f+u-1;return{relativePath:t,startLine:f,endLine:p,focusLine:n,source:o.slice(f,p+1).join(`
|
|
44
|
+
`),unitType:s.type,unitStartLine:a,unitEndLine:l,omittedLines:c-u}}function ER(e,t,n){let i=[];return Af(e,t,n,i),i.filter(r=>!i.some(o=>o!==r&&o.startIndex>=r.startIndex&&o.endIndex<=r.endIndex))}function Af(e,t,n,i){if(IR(e,t)){RR.has(e.type)&&wR(e)===n&&i.push(e);for(let r of e.namedChildren)Af(r,t,n,i)}}function wR(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 IR(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function $l(e,t,n={}){let{context:i=0}=n,r=Gf(t);if(r)return Kf(e,r.filePath,r.startLine,r.endLine,i);let o=Uf(e,t);if(o)return $f(e,o);let s=fe(e,t);return s?Nr(e,s,i):null}function DR(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 i=n.context??0,r=n.members??"exported",o=t.map(l=>PR(e,l,i,r)),s=o.flatMap(l=>l.results),a=s.map(l=>({relativePath:l.relativePath,startLine:l.startLine,endLine:l.endLine}));return{requested:t.length,matched:o.filter(l=>l.status==="matched").length,ambiguous:o.filter(l=>l.status==="ambiguous").length,missing:o.filter(l=>l.status==="missing").length,entries:o,bindingClosure:gs(s.map(l=>l.bindingClosure),a)}}function PR(e,t,n,i){let r=Gf(t);if(r){let u=Kf(e,r.filePath,r.startLine,r.endLine,n);return u?TR(e,t,u,n):Bl(e,t,"definition-source-unreadable")}let o=Uf(e,t);if(o)return MR(e,t,o,n,i);let s=rt(e,t);if(!s.match)return Bl(e,t,"definition-not-found");let a=HR(e,s),l=a.map(zf);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=Nr(e,d,n);return m?[m]:[]}):[],definitions:[],candidates:l,omittedCandidates:Math.max(0,s.total-l.length),suggestions:[]}}let c=Nr(e,s.match,n);return c?jR(t,c):Bl(e,t,"definition-source-unreadable")}function TR(e,t,n,i){let r=J(e,n.relativePath).filter(c=>!kf(c,n.relativePath)),o=FR(e,n,r),s=Of(o.map(c=>Nr(e,c,i)).filter(c=>c!==null)).filter(c=>!Hf(n,c)),a=new Set(s.map(c=>c.symbol)),l=o.filter(c=>!a.has(c.symbol)&&!(n.startLine<=c.startLine&&n.endLine>=c.endLine)).map(zf);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-l.length,returnedBodies:s.length,omittedDefinitions:l.length,omittedLedger:l}}}function FR(e,t,n){if(!kr(t.freshness))return[];if(n.length===0)return[];let i=wl(e,n,{additive:!1,semantic:!1}),r=new Map;for(let s of n){let a=r.get(s.symbol)??[];a.push(s),r.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 i.get(s.symbolId)??[])if(a.file===t.relativePath&&!(a.source==="ast-callsite"&&(a.chunkId<t.startLine||a.chunkId>t.endLine)))for(let l of r.get(a.symbol)??[])o.set(l.symbolId,l)}return Bf(e,[...o.values()],n)}function MR(e,t,n,i,r){let o=n.relativePath,s=NR(e,o),a=kr(n.freshness)?J(e,o).filter(g=>!kf(g,o)):[],l=a.filter(g=>Ct(e,g)),c=l.length>0?l:AR(s,a),u=r==="all"?[]:Bf(e,c,a),d=r==="all"||a.length===0?[$f(e,n)]:Of(u.map(g=>Nr(e,g,i)).filter(g=>g!==null)),m=_R(s,d),f=BR(o,s,d),p=OR(s);return{selector:t,status:"matched",kind:"file-source",totalCandidates:1,results:d,definitions:[],candidates:[],omittedCandidates:0,suggestions:[],fileCoverage:{members:r,basis:r==="all"||a.length===0?"complete-file-source":l.length>0?"explicit-exports-and-same-file-reference-closure":"top-level-and-same-file-reference-closure",totalDefinitions:p,returnedDefinitions:m,returnedBodies:d.length,omittedDefinitions:Math.max(0,p-m),omittedLedger:f}}}function AR(e,t){let n=new Set(e.map(i=>i.symbol));return t.filter(i=>n.has(i.symbol))}function NR(e,t){return Cl(e,t).flatMap(n=>kR(n,t)?n.children:[n])}function kf(e,t){return _f(t).has(e.leaf)}function kR(e,t){return _f(t).has(re(e.symbol))}function _f(e){let t=LR(e);return new Set([t,t.slice(0,Math.max(0,t.length-Nf(t).length))])}function Bf(e,t,n){if(t.length===0)return[];let i=wl(e,n,{additive:!0,semantic:!1}),r=new Map;for(let a of n){let l=r.get(a.symbol)??[];l.push(a),r.set(a.symbol,l)}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 l of i.get(a.symbolId)??[])for(let c of r.get(l.symbol)??[])o.has(c.symbolId)||s.push(c)}}return[...o.values()].sort($R)}function Of(e){let t=[...e].sort((i,r)=>i.relativePath.localeCompare(r.relativePath)||i.startLine-r.startLine||r.endLine-i.endLine),n=[];for(let i of t)n.some(r=>Hf(r,i))||n.push(i);return n}function $f(e,t){let n=t.text.split(`
|
|
45
|
+
`);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??jl(t.relativePath),source:t.text,freshness:t.freshness,...kr(t.freshness)?{bindingClosure:$i(e,t.relativePath,0,Math.max(0,n.length-1))}:{}}}function _R(e,t){return Is(e).filter(n=>t.some(i=>Ol(n,i))).length}function BR(e,t,n){let i=[];return jf(i,e,t,n,0),i}function jf(e,t,n,i,r){for(let o of n){if(i.some(a=>Ol(o,a)))continue;let s=Is(o.children).filter(a=>!i.some(l=>Ol(a,l))).length;e.push({symbol:o.symbol,shortName:o.shortName,relativePath:t,startLine:o.startLine,endLine:o.endLine,signature:o.signature,depth:r,nestedDefinitions:s}),jf(e,t,o.children,i,r+1)}}function Is(e){return e.flatMap(t=>[t,...Is(t.children)])}function OR(e){return Is(e).length}function Ol(e,t){return t.startLine<=e.startLine&&t.endLine>=e.endLine}function Hf(e,t){return e.relativePath===t.relativePath&&e.startLine<=t.startLine&&e.endLine>=t.endLine}function $R(e,t){return e.startLine-t.startLine||t.endLine-e.endLine||e.symbol.localeCompare(t.symbol)}function jR(e,t){return{selector:e,status:"matched",kind:"source",totalCandidates:1,results:[t],definitions:[],candidates:[],omittedCandidates:0,suggestions:[]}}function Bl(e,t,n){return{selector:t,status:"missing",kind:"source",totalCandidates:0,results:[],definitions:[],candidates:[],omittedCandidates:0,suggestions:es(e,t,5),reason:n}}function Uf(e,t){try{return ds(e,t)}catch(n){if(n instanceof Yd)return null;throw n}}function HR(e,t){if(!t.match)return[];let n=[t.match];for(let r of t.candidates){let o=J(e,r.relativePath).find(s=>s.symbol===r.symbol&&s.startLine===r.startLine);o&&n.push(o)}let i=new Set;return n.filter(r=>{let o=`${r.relativePath}:${r.startLine}:${r.endLine}:${r.symbol}`;return i.has(o)?!1:(i.add(o),!0)})}function zf(e){return{symbol:e.symbol,shortName:k(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function Gf(e){let t=e.match(/^(.+):(\d+)-(\d+)$/);if(!t)return null;let n=Number(t[2]),i=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(i)||i<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:i}}function Nr(e,t,n){let i=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),r=ds(e,t.relativePath);if(!r)return null;let s=r.text.split(`
|
|
46
|
+
`),a=t.endLine<=t.startLine?jn(e,t.relativePath,t.startLine,Number.MAX_SAFE_INTEGER):null,l=a?.unitType?a.unitStartLine:t.startLine,c=a?.unitType?a.unitEndLine:t.endLine,u=Math.max(0,l-n),d=Math.min(s.length-1,c+n),m=s.slice(u,d+1).join(`
|
|
47
|
+
`);return{symbol:t.symbol,shortName:k(t.symbol),relativePath:t.relativePath,startLine:u,endLine:d,language:i?.language??jl(t.relativePath),source:m,freshness:r.freshness,...kr(r.freshness)?{bindingClosure:$i(e,t.relativePath,u,d)}:{}}}function Kf(e,t,n,i,r){let o=ds(e,t);if(!o)return null;let s=e.get("SELECT language FROM documents WHERE relative_path = ?",o.relativePath),l=o.text.split(`
|
|
48
|
+
`);if(n>l.length)return null;let c=Math.max(0,n-1-r),u=Math.min(l.length-1,i-1+r),d=l.slice(c,u+1).join(`
|
|
49
|
+
`);return{symbol:`${o.relativePath}:${n}-${i}`,shortName:`${o.relativePath}:${n}-${i}`,relativePath:o.relativePath,startLine:c,endLine:u,language:s?.language??jl(o.relativePath),source:d,freshness:o.freshness,...kr(o.freshness)?{bindingClosure:$i(e,o.relativePath,c,u)}:{}}}function kr(e){return!!(e&&e.semantic.state!=="stale"&&e.semantic.basis!=="no-compiler-document")}function jl(e){switch(Nf(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 Ls(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath)??[];i.push(n),t.set(n.relativePath,i)}return t}function qf(e){let t=new Map,n=zR(e),i=new Map;return r=>{let o=UR(r),s=i.get(o);if(s!==void 0)return s;if(!n.has(r.file))return i.set(o,r.symbol),r.symbol;let a=t.get(r.file);a||(a=GR(J(e,r.file)),t.set(r.file,a));let l=KR(a,r);return i.set(o,l),l}}function UR(e){return`${e.file}\0${e.symbol}\0${e.line}`}function zR(e){return new Set(e.all("SELECT relative_path FROM documents").map(t=>t.relative_path))}function GR(e){let t=new Map,n=new Map;for(let i of e){let r=t.get(i.leaf);r?r.push(i):t.set(i.leaf,[i]);let o=n.get(i.startLine);o?o.push(i):n.set(i.startLine,[i])}return{definitions:e,byLeaf:t,byStartLine:n}}function KR(e,t){if(e.definitions.length===0)return t.symbol;let n=VR(t.symbol),i=qR(e.byLeaf,n),r=WR(i,t.line);if(r)return r.symbol;let o=e.byStartLine.get(t.line)??[];return o.length===1?o[0].symbol:t.symbol}function qR(e,t){let n=[],i=new Set;for(let r of t)for(let o of e.get(r)??[])i.has(o.symbolId)||(i.add(o.symbolId),n.push(o));return n}function WR(e,t){let n=null;for(let i of e)if(!(i.startLine>t||i.endLine<t)){if(i.startLine===t)return i;(!n||i.endLine-i.startLine<n.endLine-n.startLine)&&(n=i)}return n}function VR(e){let t=new Set([e]),i=e.split(/::|\.|#/).filter(Boolean).at(-1);return i&&t.add(i),t}function Wf(e,t){let i=Ce(e,t).map(r=>YR(t,r));return{usage:i,positions:XR(e,t,i)}}function Vf(e,t){return{importUsage(n){let i=e.importUsageFacts(n);if(!t||i.positions.length===0)return i.usage;let r=t.importDefinitionsForFile(n,i.positions);return r.available?JR(i.usage,r.sourcePaths):i.usage}}}function JR(e,t){return e.map((n,i)=>{let r=t.get(String(i));return r?{...n,sourcePath:r}:n})}function YR(e,t){let n=t.isTypeOnly===!0,i=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:i,isTypeUsed:n,isValueUsed:t.kind==="side-effect"||!n&&t.used,references:[]}}function XR(e,t,n){let i=ae(e,t);if(!i)return[];let r=ZR(i.rootNode),o=new Map;for(let a of r){let l=o.get(Ul(a.importedName,a.localName));l?l.push(a.position):o.set(Ul(a.importedName,a.localName),[a.position])}let s=[];return n.forEach((a,l)=>{let c=o.get(Ul(a.importedName,a.localName??a.importedName))?.shift();c&&s.push({...c,id:String(l),file:t})}),s}function ZR(e){let t=[];for(let n of e.descendantsOfType("use_declaration")){let i=n.namedChildren.find(r=>r.type!=="visibility_modifier");i&&t.push(...Ds(i,""))}return t.filter(n=>n.importedName!=="*")}function Ds(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":return[{importedName:e.text,localName:e.text,position:Hl(e,e.text)}];case"scoped_identifier":{let n=e.text.split("::").pop()??e.text;return[{importedName:n,localName:n,position:Hl(e,n)}]}case"scoped_use_list":{let n=e.namedChild(0),i=e.namedChild(1);if(!n||!i)return[];let r=fm(t,n.text);return i.namedChildren.flatMap(o=>Ds(o,r))}case"use_list":return e.namedChildren.flatMap(n=>Ds(n,t));case"use_as_clause":{let n=e.namedChild(0),i=e.namedChild(1);return!n||!i?[]:Ds(n,t).map(r=>({...r,localName:i.text}))}case"use_wildcard":{let n=e.namedChild(0),i="*";return[{importedName:i,localName:i,position:Hl(n??e,i)}]}default:return[]}}function Hl(e,t){let n=Math.max(0,e.text.lastIndexOf(t));return{id:"",file:"",line:e.startPosition.row,column:e.startPosition.column+n+QR(t)}}function QR(e){return Math.max(0,Math.min(e.length-1,1))}function Ul(e,t){return`${e}\0${t}`}import{spawnSync as zl}from"child_process";import{existsSync as Gl}from"fs";import{fileURLToPath as eE}from"url";var Kl=15e3,ql=8;function Zf(e,t={}){let n=t.status??Km,i=iE(e,n),r=rE(e,n),o=oE(e,n),s=t.referenceResolver||t.calleeResolver||t.signatureResolver||!tE(t)?null:qm(e,n,{fallbackReferenceResolver:i,fallbackCalleeResolver:r,fallbackSignatureResolver:o}),a=t.referenceResolver??s??i,l=t.calleeResolver??s??r,c=t.signatureResolver??s??o,u=t.importUsageResolver??Vf(t.sourceImportUsageResolver??nE(),t.importDefinitionResolver??s),d=t.calleeSymbolResolver,m=t.sourceZeroCalleeOracle,f=t.scipOccurrenceCalleeOracle,p=new Map,g=new Map,h=null,S=null,v=()=>(h??=n(e),h),y=()=>{let C=v();return C.dependencyAvailable?S??C:C},E=C=>{if(C.length===0)return new Map;let L=Br(C);try{let I=a.referencesForDefinitions(L),x=v();return S=Ps(x,I),I.available?new Map(I.references):rs(L,I.references)}catch(I){let x=v();return S=_r(x,I),ci(L)}},w=C=>{if(C.length===0)return new Map;let L=Br(C),I=L.filter(Jf);if(I.length===0)return ui(L);let x=new Map,P=Xf(I,f),_=[];for(let D of I)g.has(D.symbolId)?x.set(D.symbolId,g.get(D.symbolId)??[]):P.has(D.symbolId)?x.set(D.symbolId,P.get(D.symbolId)??[]):Yf(D,m)?x.set(D.symbolId,[]):_.push(D);if(_.length===0)return zi(L,x,void 0);try{let D=l.calleesForDefinitions(_),T=v();S=Ps(T,D);let A=zi(_,D.callees,d);for(let[W,le]of A)x.set(W,le);return zi(L,x,void 0)}catch(D){let T=v();return S=_r(T,D),ui(L)}},b=(C,L)=>{let I=Br(C),x=Br(L),P=x.filter(Jf),_=new Map,D=Xf(P,f),T=[];for(let A of P)D.has(A.symbolId)?_.set(A.symbolId,D.get(A.symbolId)??[]):Yf(A,m)?_.set(A.symbolId,[]):T.push(A);if(I.length===0&&T.length===0)return{references:ci(I),callees:zi(x,_,void 0)};try{let A=s?s.referencesAndCalleesForDefinitions(I,T):cE(a,l,{referenceDefinitions:I,calleeDefinitions:T}),W=v();S=Ps(W,A);let le=A.available?new Map(A.references):rs(I,A.references);for(let[Y,N]of A.callees)_.set(Y,N);let q=zi(x,_,d);for(let[Y,N]of q)g.set(Y,N);return{references:le,callees:q}}catch(A){let W=v();return S=_r(W,A),{references:ci(I),callees:ui(x)}}},R=C=>{if(C.length===0)return new Map;let L=Br(C);try{let I=c.signaturesForDefinitions(L),x=v();return S=Ps(x,I),Qf(L,I.signatures)}catch(I){let x=v();return S=_r(x,I),Ts(L)}};return{language:"rust",availability:y,dispose:()=>{s?.dispose()},importUsage:C=>{let L=p.get(C);if(L)return L;try{let I=u.importUsage(C);return p.set(C,I),I}catch(I){let x=v();return S=_r(x,I),[]}},referencesFor:C=>E([C]).get(C.symbolId)??[],referencesForDefinitions:E,referencesAndCalleesForDefinitions:b,calleesFor:C=>w([C]).get(C.symbolId)??[],calleesForDefinitions:w,signatureFor:C=>R([C]).get(C.symbolId)??null}}function Ps(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 _r(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 tE(e){if(e.usePersistentSession!==void 0)return e.usePersistentSession;let t=process.env.SCIP_RUST_SEMANTIC_SESSION;return t!=="0"&&t!=="false"}function nE(){return{importUsageFacts:()=>({usage:[],positions:[]})}}function Br(e){return e.map(t=>{let n=t;return{...t,leaf:typeof n.leaf=="string"?n.leaf:re(t.symbol),parentTypeName:n.parentTypeName??null,isFunctionLike:typeof n.isFunctionLike=="boolean"?n.isFunctionLike:ke(t.symbol),isTypeLike:n.isTypeLike??!1,kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosingSymbol??null}})}function Jf(e){return e.isFunctionLike}function Yf(e,t){if(!t)return!1;try{return t(e)}catch{return!1}}function Xf(e,t){if(!t||e.length===0)return new Map;try{return t(e)}catch{return new Map}}function iE(e,t){return{referencesForDefinitions:n=>sE(e,t,n)}}function rE(e,t){return{calleesForDefinitions:n=>aE(e,t,n)}}function oE(e,t){return{signaturesForDefinitions:n=>lE(e,t,n)}}function sE(e,t,n){let i=t(e);if(!i.available||!i.resolvedBinary)return{available:!1,resolvedBinary:i.resolvedBinary,reason:Jl(i),references:ci(n)};let r=Wl();if(!Gl(r))return{available:!1,resolvedBinary:i.resolvedBinary,reason:`Rust semantic worker was not found at ${r}. Run npm run build before using built semantic Rust queries.`,references:ci(n)};let o=Gi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Kl),s=Fs(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),a=Gi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,ql),l=Fs(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=ss(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!0}),u={projectRoot:e,rustAnalyzerBinary:i.resolvedBinary,definitions:[...n],requestTimeoutMs:o,...s>0?{referenceRetryTimeoutMs:s}:{},diagnosticsTimeoutMs:l,settleDelayMs:c,concurrency:a},d=zl(process.execPath,[r],{cwd:e,input:JSON.stringify(u),encoding:"utf8",maxBuffer:50*1024*1024,windowsHide:!0,timeout:os(n.length,Wm(o,u.referenceRetryTimeoutMs),a)}),m=Yl(d.stdout);if(m)return{...Vl(m),resolvedBinary:i.resolvedBinary,references:rs(n,new Map(m.references),new Set(m.incompleteReferenceSymbolIds??[]))};let f=d.error instanceof Error?d.error.message:d.stderr.trim()||`Rust semantic worker exited with status ${d.status??"unknown"}.`;return{available:!1,resolvedBinary:i.resolvedBinary,reason:f,references:ci(n)}}function aE(e,t,n){let i=t(e);if(!i.available||!i.resolvedBinary)return{available:!1,resolvedBinary:i.resolvedBinary,reason:Jl(i),callees:ui(n)};let r=Wl();if(!Gl(r))return{available:!1,resolvedBinary:i.resolvedBinary,reason:`Rust semantic worker was not found at ${r}. Run npm run build before using built semantic Rust queries.`,callees:ui(n)};let o=Gi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Kl),s=Gi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,ql),a=Fs(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),l=ss(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!0}),c={projectRoot:e,rustAnalyzerBinary:i.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:l,concurrency:s,includeReferences:!1,includeCallees:!0},u=zl(process.execPath,[r],{cwd:e,input:JSON.stringify(c),encoding:"utf8",maxBuffer:50*1024*1024,windowsHide:!0,timeout:os(n.length,o,s)}),d=Yl(u.stdout);if(d)return{...Vl(d),resolvedBinary:i.resolvedBinary,callees:zi(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:i.resolvedBinary,reason:m,callees:ui(n)}}function lE(e,t,n){let i=t(e);if(!i.available||!i.resolvedBinary)return{available:!1,resolvedBinary:i.resolvedBinary,reason:Jl(i),signatures:Ts(n)};let r=Wl();if(!Gl(r))return{available:!1,resolvedBinary:i.resolvedBinary,reason:`Rust semantic worker was not found at ${r}. Run npm run build before using built semantic Rust queries.`,signatures:Ts(n)};let o=Gi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Kl),s=Gi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,ql),a=Fs(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),l=ss(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!1,includeSignatures:!0}),c={projectRoot:e,rustAnalyzerBinary:i.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:l,concurrency:s,includeReferences:!1,includeCallees:!1,includeSignatures:!0},u=zl(process.execPath,[r],{cwd:e,input:JSON.stringify(c),encoding:"utf8",maxBuffer:50*1024*1024,windowsHide:!0,timeout:os(n.length,o,s)}),d=Yl(u.stdout);if(d)return{...Vl(d),resolvedBinary:i.resolvedBinary,signatures:Qf(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:i.resolvedBinary,reason:m,signatures:Ts(n)}}function cE(e,t,n){let i=n.referenceDefinitions.length>0?e.referencesForDefinitions(n.referenceDefinitions):{available:!0,references:ci(n.referenceDefinitions)},r=n.calleeDefinitions.length>0?t.calleesForDefinitions(n.calleeDefinitions):{available:!0,callees:ui(n.calleeDefinitions)},o={resolvedBinary:i.resolvedBinary??r.resolvedBinary,references:i.references,callees:r.callees};return i.available&&r.available?{available:!0,...o}:{available:!1,reason:(i.available?void 0:i.reason)??(r.available?void 0:r.reason)??"Rust semantic resolution was unavailable.",...o}}function ci(e){return new Map(e.map(t=>[t.symbolId,[]]))}function ui(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Ts(e){return new Map(e.map(t=>[t.symbolId,null]))}function zi(e,t,n){let i=0,r=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&&(i+=1),r+=a.length,o.set(s.symbolId,a.map(l=>({...l,symbol:n?n(l):l.symbol})))}return o},()=>({definitions:e.length,rows:i,callees:r,resolveSymbols:!!n}))}function Qf(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function Wl(){return eE(new URL("./rust-semantic-worker.js",import.meta.url))}function Vl(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function Jl(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function Yl(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 i={references:n.references,incompleteReferenceSymbolIds:Array.isArray(n.incompleteReferenceSymbolIds)?n.incompleteReferenceSymbolIds.filter(r=>typeof r=="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,...i}:{available:!1,reason:String(n.reason),...i}}catch{return null}}function Gi(e,t){return is(e)??t}function Fs(e,t){if(!e)return t;let n=Number(e);return Number.isInteger(n)&&n>=0?n:t}import{existsSync as uE}from"fs";import{deserializeSCIP as dE,SymbolRole as mE}from"@c4312/scip";var Xl=new WeakMap;function tp(e,t){let n=t.filter(fE);if(n.length===0)return new Map;let i=!1,r=0,o=0;return $("rust.scip-occurrence.callees",()=>{let s=hE(e);if(i=!!s,!s)return new Map;let a=new Map;for(let l of n){let c=pE(e,s,l);c!==null&&(a.set(l.symbolId,c),r+=1,o+=c.length)}return a},()=>({definitions:t.length,candidates:n.length,indexAvailable:i,resolvedDefinitions:r,resolvedCallees:o}))}function fE(e){return!(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||!e.isFunctionLike||e.leaf==="main"||at(e.symbol))}function pE(e,t,n){let i=ee(e,n.relativePath);if(!i||i.language!=="rust")return null;let r=i.callables.find(c=>c.startLine!==n.startLine||c.endLine!==n.endLine?!1:c.name===n.leaf||n.leaf.endsWith(c.name)||c.name.endsWith(n.leaf));if(!r)return null;let o=i.callSites.filter(c=>c.line>=r.startLine&&c.line<=r.endLine);if(o.length===0)return null;let s=(t.occurrencesByFile.get(n.relativePath)??[]).filter(c=>c.line>=r.startLine&&c.line<=r.endLine&&c.callee.symbol!==n.symbol);if(s.some(c=>c.traitImplMember)||!gE(o,s))return null;let a=[],l=new Set;for(let c of s){let u=`${c.callee.symbol}\0${c.callee.file}\0${c.callee.line}`;l.has(u)||(l.add(u),a.push(c.callee))}return a}function gE(e,t){let n=ep(e),i=ep(t);if(n.size!==i.size)return!1;for(let[r,o]of n)if(i.get(r)!==o)return!1;return!0}function ep(e){let t=new Map;for(let n of e){let i=n.calleeLeaf??n.leaf;if(!i)continue;let r=`${n.line}\0${i}`;t.set(r,(t.get(r)??0)+1)}return t}function hE(e){if(Xl.has(e))return Xl.get(e)??null;let t=yE(e);return Xl.set(e,t),t}function yE(e){if(!e.generation.indexPath||!uE(e.generation.indexPath))return null;try{let t=ze(e).filter(o=>o.symbol.startsWith("rust-analyzer ")&&o.relativePath.endsWith(".rs")&&o.isFunctionLike),n=new Map(t.map(o=>[o.symbol,o])),i=dE(jo(e.generation.indexPath,{inputKind:"SCIP occurrence-callee index",maxBytes:$o})),r=new Map;for(let o of i.documents??[]){let s=o.relativePath;if(!s||!s.endsWith(".rs")||e.isIgnored(s))continue;let a=[];for(let l of o.occurrences??[]){if(!l.symbol||(l.symbolRoles&mE.Definition)!==0)continue;let c=n.get(l.symbol);if(!c)continue;let u=l.range?.[0];Number.isInteger(u)&&a.push({line:u,leaf:c.leaf,traitImplMember:at(c.symbol),callee:{symbol:c.symbol,file:c.relativePath,line:c.startLine,callsiteLine:u}})}r.set(s,a)}return{occurrencesByFile:r}}catch{return null}}var Ms=class{sessions=new WeakMap;getOrCreate(t,n,i){let r=bE(t,n),o=this.sessions.get(t);o||(o=new Map,this.sessions.set(t,o));let s=o.get(r);if(s)return s.hits+=1,s.lastUsedAtMs=Date.now(),s.provider;let a=Date.now(),l=i();return o.set(r,{key:r,language:n,projectRoot:t.config.projectRoot,provider:l,createdAtMs:a,lastUsedAtMs:a,hits:1}),l}sessionsFor(t){return[...this.sessions.get(t)?.values()??[]]}clear(t){let n=this.sessions.get(t);if(n)for(let i of n.values())i.provider.dispose?.();this.sessions.delete(t)}};function bE(e,t){return`${e.config.projectRoot}:${t}-workspace`}import{randomUUID as SE}from"crypto";import{existsSync as vE}from"fs";import{dirname as CE}from"path";function np(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}var xE=12e4,RE=5;function sp(e,t,n={}){let i=new Zl(e,n),r=null,o=null,s=process.env.CODEBASEIQ_SKIP_WATCH_SERVICE==="1",a=()=>(r??=Qm(e,t),r),l=(d,m,f)=>{if(s)return f();try{return m(i.request(d))}catch{return s=!0,f()}},c=(d,m)=>l({kind:"references",definitions:[...d],...m?.exact?{exact:!0}:{}},f=>op(f),()=>a().referencesForDefinitions?.(d,m)??new Map(d.map(f=>[f.symbolId,a().referencesFor(f)]))),u=d=>l({kind:"callees",definitions:[...d]},m=>op(m),()=>a().calleesForDefinitions?.(d)??new Map(d.map(m=>[m.symbolId,a().calleesFor(m)])));return{language:"typescript",availability:()=>(o??=l({kind:"availability"},IE,()=>a().availability()),o),importUsage:d=>l({kind:"import-usage",file:d},m=>m,()=>a().importUsage(d)),referencesFor:d=>ip(c([d]),d,"reference"),referencesForDefinitions:c,referenceFragmentsForFiles:d=>l({kind:"reference-fragments",files:[...d]},m=>wE(m),()=>a().referenceFragmentsForFiles?.(d)??new Map),calleesFor:d=>ip(u([d]),d,"callee"),calleesForDefinitions:u,signatureFor:d=>l({kind:"signature",definition:d},LE,()=>a().signatureFor(d)),dispose:()=>r?.dispose?.()}}function ip(e,t,n){if(!e.has(t.symbolId))throw new Error(`TypeScript ${n} evidence is incomplete for ${t.symbol}.`);return e.get(t.symbolId)}var Zl=class{constructor(t,n={}){this.db=t;this.runtime=n.runtime??PE,this.timeoutMs=n.timeoutMs??DE(),this.mailboxLimits=n.mailboxLimits??{},this.cacheDir=CE(t.config.dbPath),this.projectRoot=Zd(t.config.projectRoot)}db;runtime;timeoutMs;cacheDir;projectRoot;mailboxLimits;request(t){let n=Hm(this.cacheDir),i=Ym(this.cacheDir),r=bl(n.statePath);if(!rp(r,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,l=(this.runtime.monotonicNow??Uo)()+this.timeoutMs,c=Jd(),u=Om("typescript-semantic-v4",{generation:o,profileEnvironment:c,request:t}),d=$m(u),m=jm(i,{mailboxVersion:Bm,operationKey:u,clientId:this.runtime.randomId(),enqueuedAtMs:s,deadlineAtMs:a,protocolVersion:ls,id:d,generation:o,profileEnvironment:c,request:t},{nowMs:s,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??Uo)()<=l;){if(vE(m.responsePath))return EE(Ud(m.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript semantic mailbox response"}),d,o,u);let f=bl(n.statePath);if(!rp(f,this.projectRoot,this.runtime))throw new Error("TypeScript semantic service stopped while processing a request.");this.runtime.sleep(RE)}throw new Error(`TypeScript semantic service timed out after ${this.timeoutMs}ms.`)}};function rp(e,t,n){let i=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptSemantic?.protocolVersion===ls&&n.isProcessAlive(e.pid)&&(!e.processIdentity||i!=null&&zd(e.processIdentity,i))}function EE(e,t,n,i){let r=JSON.parse(e);if(r.protocolVersion!==ls||r.id!==t||r.operationKey!==i||r.ok===!0&&r.generation!==n)throw new Error("TypeScript semantic service wrote an incompatible response.");if(r.ok===!0)return r.response;throw new Error(typeof r.error=="string"?r.error:"TypeScript semantic service request failed.")}function op(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid numeric map.");return new Map(e)}function wE(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid string map.");return new Map(e)}function IE(e){let t=np(e);if(!t)throw new Error("TypeScript semantic service wrote invalid availability.");return t}function LE(e){if(e!==null&&typeof e!="string")throw new Error("TypeScript semantic service wrote an invalid signature.");return e}function DE(){let e=Number(process.env.SCIP_TYPESCRIPT_SEMANTIC_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:xE}var PE={now:Date.now,monotonicNow:Uo,randomId:SE,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:Xd,readProcessIdentity:Gd};var Ql=new Ms;nm({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>Ql.clear(e)});im({name:"semantic-provider",close:e=>Ql.clear(e)});function di(e,t){let n=Ke(t)??"typescript";return Ql.getOrCreate(e,n,()=>n==="rust"?Zf(e.config.projectRoot,{sourceImportUsageResolver:{importUsageFacts:i=>Wf(e,i)},calleeSymbolResolver:qf(e),sourceZeroCalleeOracle:i=>TE(e,i),scipOccurrenceCalleeOracle:i=>tp(e,i)}):sp(e,t))}function Ke(e){return e?ye(e)==="rust"?"rust":Xo(e)?"typescript":null:"typescript"}function TE(e,t){let n=ee(e,t.relativePath);if(!n||n.language!=="rust")return!1;let i=n.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine&&r.name===t.leaf)??n.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return i?!n.callSites.some(r=>r.line>=i.startLine&&r.line<=i.endLine):!1}var FE=/^[A-Za-z_][A-Za-z0-9_]*$/,ap=/\bDefault::default\b/g,ME=/^\.\.\s*Default::default\b/;function lp(e,t){let n=new Map,i=new Map;for(let r of t){let o=ec(e,r,i);o!==null&&n.set(r.symbolId,o)}return n}function ec(e,t,n=new Map){let i=NE(t.symbol);if(!i)return null;let r=ts(e,[t.symbolId]);if(r.length===0)return null;let o=new RegExp(`(^|[^A-Za-z0-9_])${He(i)}::default\\b`,"g"),s=new RegExp(`(^|[^A-Za-z0-9_])${He(i)}\\s*$`),a=AE(e,t.symbolId),l=[];for(let c of r){let u=kE(e,c.relative_path,n);if(u===null)return null;let d=u.split(/\r?\n/),m=0,f=[],p=0;for(let g=c.chunk_start;g<=c.chunk_end&&g<d.length;g+=1){let S=d[g]??"",v=new Set;o.lastIndex=0;let y;for(;y=o.exec(S);)l.push({file:c.relative_path,line:g,column:y.index+y[1].length+i.length+2}),p+=1;for(let E=0;E<S.length;E+=1){let w=ME.exec(S.slice(E));if(w){if(a&&f.includes(m)){let R=E+w[0].lastIndexOf("default");l.push({file:c.relative_path,line:g,column:R}),v.add(R),p+=1}E+=w[0].length-1;continue}let b=S[E];if(b==="{"){let R=s.test(S.slice(0,E));m+=1,R&&f.push(m);continue}if(b==="}")for(m=Math.max(0,m-1);f.length>0&&f[f.length-1]>m;)f.pop()}for(ap.lastIndex=0;y=ap.exec(S);){let E=y.index+9;if(!v.has(E))return null}}if(p===0)return null}return Um(l)}function AE(e,t){return e.get("SELECT 1 AS present FROM mentions WHERE symbol_id = ? AND role = 1 LIMIT 1",t)?.present===1}function NE(e){let t=/impl#\[([^\]]+)\]\[Default\]default\(\)\./.exec(e)?.[1]??null;return!t||!FE.test(t)?null:t}function kE(e,t,n){if(n.has(t))return n.get(t)??null;let i=e.get("SELECT text FROM documents WHERE relative_path = ?",t),r=typeof i?.text=="string"?i.text:_E(e,t);return n.set(t,r),r}function _E(e,t){try{return nt(e.config.projectRoot,t,{inputKind:"indexed Rust source file"})}catch(n){if(!St(n))throw n;return null}}var As=new WeakMap;function pp(e){As.delete(e)}function gp(e){let t=As.get(e);return{incompleteSymbolIds:new Set(t?.incompleteSymbolIds),unavailableSymbolIds:new Set(t?.unavailableSymbolIds)}}function ic(e,t){if(t.incompleteSymbolIds.size===0&&t.unavailableSymbolIds.size===0)return;let n=As.get(e)??{incompleteSymbolIds:new Set,unavailableSymbolIds:new Set};for(let i of t.incompleteSymbolIds)n.incompleteSymbolIds.add(i);for(let i of t.unavailableSymbolIds)n.unavailableSymbolIds.add(i);As.set(e,n)}var BE="typescript-import-usage-v1",OE="typescript-signatures-v1",tc=Fe("semantic-prefetched-callees",{clearGroups:["whole-project","source-file","semantic-provider"]}),cp=hr({kind:"semantic-import-usage",invalidation:Je("semantic-import-usage"),serialize:e=>JSON.stringify(e),deserialize:wp}),up=hr({kind:"semantic-signatures",invalidation:Je("semantic-signatures"),serialize:e=>JSON.stringify(e),deserialize:qE}),dp=vt({kind:"typescript-import-usage",invalidation:Je("typescript-import-usage"),serialize:e=>JSON.stringify(e),deserialize:wp}),mp=vt({kind:"typescript-signatures",invalidation:Je("typescript-signatures"),serialize:e=>JSON.stringify(e),deserialize:WE});function kt(e){let t=new Map,n=new Set;return{capability:(i,r)=>Ip(e,i,r),importUsage:i=>jE(e,i),references:i=>bp(e,i),materializeReferences:(i,r)=>vp(e,i,t,n,r),callerMap:i=>HE(e,i,t,n),calleeMap:i=>xp(e,i),signature:i=>GE(e,i)}}function $E(e,t){if(t.size===0)return;let n=tc.get(e,()=>new Map);for(let[i,r]of t)n.set(i,[...r])}function hp(e,t){if(!tc.has(e))return{hits:[],misses:[...t]};let n=tc.get(e,()=>new Map),i=[],r=[];for(let o of t)n.has(o.symbolId)?i.push({definition:o,callees:n.get(o.symbolId)??[]}):r.push(o);return{hits:i,misses:r}}function $r(e,t){return kt(e).importUsage(t)}function jE(e,t){if(Ke(t)==="typescript"){let o="fallback",s=0,a=0,l=0,c=0;return $("typescript.import-usage.materialize",()=>{let u=Sr(e,t,BE);if(u?.key){s=1;let m=dp.read(e,t,u.key);if(m)return o="hit",a=1,m;l=1;let f=vn(e,t);if(!f)return o="unavailable",[];let p=f.importUsage(t);return dp.write(e,t,u.key,p),o="computed",p}c=1;let d=vn(e,t);return d?(o="direct-fallback",d.importUsage(t)):(o="unavailable",[])},()=>({state:o,eligible:s,cacheHits:a,cacheMisses:l,fallbacks:c}))}let n=Ep(e,"semantic-import-usage",t);if(n){let o=cp.read(e,t,n);if(o)return o}let i=vn(e,t);if(!i)return[];let r=i.importUsage(t);return n&&cp.write(e,t,n,r),r}function yp(e,t){return kt(e).references(t)}function bp(e,t){let n=ec(e,t);if(n)return n;let i=Gm(e,t);if(i)return i;let r=vn(e,t.relativePath);return r?r.referencesFor(t):[]}function Sp(e,t){let n=Cn(e,t),i=n.incompleteSymbolIds.size+n.unavailableSymbolIds.size;if(i>0)throw new Error(`Exact semantic caller evidence is incomplete for ${i} definition(s).`);return n.callers}function Cn(e,t,n=i=>di(e,i)){let i=new Map,r=new Set,o=new Set,s=new Map;for(let l of t){let c=Ke(l.relativePath);if(!c)continue;let u;try{u=n(l.relativePath)}catch{o.add(l.symbolId);continue}if(!u.availability().available){o.add(l.symbolId);continue}if(c==="typescript"){let d=s.get(u)??[];d.push(l),s.set(u,d);continue}nc(e,i,l,bp(e,l))}for(let[l,c]of s){let u=gl(e,c,n),d=u?.references??(l.referencesForDefinitions?l.referencesForDefinitions(c,{exact:!0}):new Map(c.map(m=>[m.symbolId,l.referencesFor(m)])));!u&&ft()&&pl(e,c,d,n);for(let m of c){if(!d.has(m.symbolId)){r.add(m.symbolId);continue}nc(e,i,m,d.get(m.symbolId)??[])}}let a={callers:i,incompleteSymbolIds:r,unavailableSymbolIds:o};return ic(e,a),a}function HE(e,t,n=new Map,i=new Set){let r=new Map,o=vp(e,t,n,i),s=0;return $("semantic.callers.from-references",()=>{for(let a of t)s+=nc(e,r,a,n.get(a.symbolId)??[])},()=>({definitions:t.length,materialized:o.definitions,inMemoryHits:o.inMemoryHits,incompleteInMemoryHits:o.incompleteInMemoryHits,resultRows:r.size,callerFiles:s})),r}function vp(e,t,n,i,r={}){let o=gn(e),s=[],a=[],l=[],c=0,u=0,d=0,m=0,f=0,p=0,g=0,h=0,S=0,v=0,y=0,E=0,w=[],b=new Map,R=t.filter(L=>Ke(L.relativePath)==="typescript"&&!n.has(L.symbolId)&&!i.has(L.symbolId)),C=gl(e,R,L=>di(e,L));if(C){S=R.length,v=C.cacheHits,y=C.cacheMisses,E=C.computedFiles;for(let L of R)n.set(L.symbolId,C.references.get(L.symbolId)??[])}if($("semantic.references.cache-scan",()=>{for(let[L,I]of Ls(t)){let x=[];for(let D of I)n.has(D.symbolId)?u+=1:i.has(D.symbolId)?h+=1:x.push(D);if(x.length===0){g+=1;continue}let P=UE(e,o,L);if(!P){for(let D of x)Ke(D.relativePath)||(c+=1),l.push(D);continue}p+=1;let _=om(e,L,P);for(let D of x){let T=_.get(D.symbol)??null;if(T!==null){let A=zE(T);if(A){d+=1,n.set(D.symbolId,A);continue}m+=1}a.push({definition:D,cacheFingerprint:P})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:c,cacheHits:d,parseFailures:m,misses:a.length,unkeyed:l.length,inMemoryHits:u,incompleteInMemoryHits:h,fullyInMemoryFiles:g,cacheReadFiles:p})),a.length>0||l.length>0){w=[...l,...a.map(L=>L.definition)],b=$("semantic.references.compute-misses",()=>{let L=Ns(e,w,r);return f=L.size,L},()=>({definitions:w.length,misses:a.length,unkeyed:l.length,rows:f}));for(let L of w)b.has(L.symbolId)?(n.set(L.symbolId,b.get(L.symbolId)??[]),i.delete(L.symbolId)):i.add(L.symbolId);for(let{definition:L,cacheFingerprint:I}of a)b.has(L.symbolId)&&Ip(e,"semantic-references",L.relativePath).available&&s.push({relativePath:L.relativePath,symbol:L.symbol,projectFingerprint:I,payload:JSON.stringify(b.get(L.symbolId)??[])})}return s.length>0&&$("semantic.references.cache-write",()=>sm(e,s),()=>({entries:s.length})),b.size>0&&pl(e,w,b,L=>di(e,L)),{definitions:t.length,inMemoryHits:u,incompleteInMemoryHits:h,cacheHits:d,misses:a.length,unkeyed:l.length,skippedUnsupportedLanguage:c,parseFailures:m,computed:f,incomplete:i.size,cacheWrites:s.length,fragmentDefinitions:S,fragmentCacheHits:v,fragmentCacheMisses:y,fragmentComputedFiles:E}}function UE(e,t,n){if(!t)return null;let i=Ke(n);return i==="typescript"?jt(JSON.stringify({kind:"semantic-references",language:i,schema:"typescript-references-v2-incomplete-scan",projectFingerprint:t})):i==="rust"?jt(JSON.stringify({kind:"semantic-references",language:i,engine:oi(e.config.projectRoot),projectFingerprint:t})):null}function Ns(e,t,n={}){let i=ft(),r=new Map,o=0,s=0,a=0,l=0,c=0,u=0,d=0,m=0,f=0;return $("semantic.references.provider-loop",()=>{let p=lp(e,t),g=zm(e,t),h=new Map,S=n.prefetchCallees?new Map:null,v=[];for(let E of t){let w,b=()=>(w??=vn(e,E.relativePath),w);if(S){let I=b();if(I?.referencesAndCalleesForDefinitions){let x=S.get(I);x?x.push(E):S.set(I,[E]),f+=1}}let R=p.get(E.symbolId);if(R){a+=1,l+=R.length,Or(r,E.symbolId,R,i,I=>{d+=1,m+=I});continue}let C=g.get(E.symbolId);if(C){c+=1,u+=C.length,Or(r,E.symbolId,C,i,I=>{d+=1,m+=I});continue}let L=b();if(!L){i&&(s+=1);continue}if(i&&(o+=1),L.referencesForDefinitions){let I=h.get(L);I?I.push(E):h.set(L,[E])}else v.push({provider:L,definition:E})}let y=new Set;if(S)for(let[E,w]of S){if(!E.referencesAndCalleesForDefinitions)continue;let b=h.get(E)??[],R=E.referencesAndCalleesForDefinitions(b,w);y.add(E),$E(e,R.callees);for(let C of b){if(!R.references.has(C.symbolId))continue;let L=R.references.get(C.symbolId)??[];Or(r,C.symbolId,L,i,I=>{d+=1,m+=I})}}for(let[E,w]of h){if(y.has(E))continue;let b=E.referencesForDefinitions(w);for(let R of w){if(!b.has(R.symbolId))continue;let C=b.get(R.symbolId)??[];Or(r,R.symbolId,C,i,L=>{d+=1,m+=L})}}for(let{provider:E,definition:w}of v){let b=E.referencesFor(w);Or(r,w.symbolId,b,i,R=>{d+=1,m+=R})}return r},()=>({definitions:t.length,providerHits:o,providerMisses:s,rustDefaultFastPathRows:a,rustDefaultFastPathReferences:l,rustScipOccurrenceFastPathRows:c,rustScipOccurrenceFastPathReferences:u,prefetchCalleeDefinitions:f,definitionsWithReferences:d,referenceCount:m,rows:r.size}))}function ks(e,t,n={}){let i=Ns(e,t,n),r=Cp(e,t,i);return ic(e,r),{rows:i,...r}}function Or(e,t,n,i,r){e.set(t,n),i&&n.length>0&&r(n.length)}function nc(e,t,n,i){let r=0;for(let o of i){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&&(r+=1)}return r}function zE(e){try{return JSON.parse(e)}catch{return null}}function _s(e,t,n){let i=xp(e,t,n),r=Cp(e,t,i,n);return ic(e,r),{rows:i,...r}}function Cp(e,t,n,i){let r=new Set,o=new Set;for(let s of t)if(!(n.has(s.symbolId)||!Ke(s.relativePath)))try{(i?i(s.relativePath):di(e,s.relativePath)).availability().available?r.add(s.symbolId):o.add(s.symbolId)}catch{o.add(s.symbolId)}return{incompleteSymbolIds:r,unavailableSymbolIds:o}}function xp(e,t,n){let i=ft(),r=new Map,o=0,s=0,a=0,l=0;return $("semantic.callees.provider-loop",()=>{let c=new Map,u=[];for(let d of t){let m=n?n(d.relativePath):vn(e,d.relativePath);if(m&&!m.availability().available){i&&(s+=1);continue}if(!m){i&&(s+=1);continue}i&&(o+=1);let f=d;if(m.calleesForDefinitions){let p=c.get(m);p?p.push(f):c.set(m,[f])}else u.push({provider:m,definition:f})}for(let[d,m]of c){let f=d.calleesForDefinitions(m);for(let p of m){if(!f.has(p.symbolId))continue;let g=f.get(p.symbolId)??[];fp(r,p.symbolId,g,i,h=>{a+=1,l+=h})}}for(let{provider:d,definition:m}of u){let f=d.calleesFor(m);fp(r,m.symbolId,f,i,p=>{a+=1,l+=p})}return r},()=>({definitions:t.length,providerHits:o,providerMisses:s,definitionsWithCallees:a,calleeCount:l,rows:r.size}))}function fp(e,t,n,i,r){e.set(t,n),i&&n.length>0&&r(n.length)}function Rp(e,t){return kt(e).signature(t)}function GE(e,t){if(Ke(t.relativePath)==="typescript"){let s="fallback",a=0,l=0,c=0,u=0;return $("typescript.signature.materialize",()=>{let d=Sr(e,t.relativePath,OE);if(d?.key){a=1;let f=mp.read(e,t.relativePath,d.key)??{};if(Object.prototype.hasOwnProperty.call(f,t.symbol))return s="hit",l=1,f[t.symbol]??null;c=1;let p=vn(e,t.relativePath);if(!p)return s="unavailable",null;let g=p.signatureFor(t);return mp.write(e,t.relativePath,d.key,{...f,[t.symbol]:g}),s="computed",g}u=1;let m=vn(e,t.relativePath);return m?(s="direct-fallback",m.signatureFor(t)):(s="unavailable",null)},()=>({state:s,eligible:a,cacheHits:l,cacheMisses:c,fallbacks:u}))}let n=Ep(e,"semantic-signatures",t.relativePath),i=KE(t);if(n){let s=up.read(e,i,n);if(s)return s.signature}let r=vn(e,t.relativePath);if(!r)return null;let o=r.signatureFor(t);return n&&up.write(e,i,n,{signature:o}),o}function Ep(e,t,n){let i=gn(e);if(!i)return null;let r=Ke(n);return r!=="rust"?null:jt(JSON.stringify({kind:t,language:r,engine:oi(e.config.projectRoot),projectFingerprint:i}))}function KE(e){return`${e.relativePath}\0${e.symbol}`}function wp(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:null}catch{return null}}function qE(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 WE(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 Ip(e,t,n){let i=Ke(n);if(!i)return{slot:t,language:"typescript",available:!1,reason:"semantic evidence is only available for TypeScript or Rust files"};try{return{slot:t,language:i,...di(e,n).availability()}}catch(r){return{slot:t,language:i,available:!1,reason:r instanceof Error?r.message:String(r)}}}function vn(e,t){if(!Ke(t))return null;let n=di(e,t);return n.availability().available?n:null}var pe={references:yp,referenceMap:Ns,referenceEvidenceMap:ks,callerMap:(e,t)=>kt(e).callerMap(t),calleeMap:rc,calleeEvidenceMap:Lp};function rc(e,t,n={}){return Lp(e,t,n).rows}function Lp(e,t,n={}){let i=ft(),r=new Map,o=hp(e,t),s=[],a=[],l=0,c=0,u=0,d=0,m=0,f=0,p=0,g=new Set,h=new Set;for(let{definition:b,callees:R}of o.hits)m+=1,r.set(b.symbolId,R),R.length>0&&(f+=1,p+=R.length);let S=VE(e,o.hits);if(S.entries.length>0&&$("semantic.callees.prefetch-cache-write",()=>ml(e,S.entries),()=>({entries:S.entries.length,sourceMissing:S.sourceMissing,skippedUnsupportedLanguage:S.skippedUnsupportedLanguage})),$("semantic.callees.cache-scan",()=>{for(let[b,R]of Ls(o.misses)){if(!Ke(b)){i&&(l+=R.length);continue}let C=se(e,b);if(!C){i&&(c+=R.length),a.push(...R);continue}let L=Ft(e,b,C),I=Dp(e,b);if(!I){a.push(...R);continue}let x=rm(e,b,L,I);for(let P of R){let _=x.get(P.symbol)??null;if(_!==null){let D=YE(_);if(D){i&&(u+=1),r.set(P.symbolId,D);continue}i&&(d+=1)}s.push({def:P,contentHash:L,depsDigest:I})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:l,sourceMissing:c,cacheHits:u,parseFailures:d,misses:s.length,unkeyed:a.length,inMemoryHits:m,inMemoryRows:f,inMemoryCalleeCount:p,resultRows:r.size})),s.length===0&&a.length===0)return{rows:r,incompleteSymbolIds:g,unavailableSymbolIds:h};let v=[...a,...s.map(b=>b.def)],y=0,E=$("semantic.callees.compute-misses",()=>{let b=_s(e,v,n.resolveProvider);for(let R of b.incompleteSymbolIds)g.add(R);for(let R of b.unavailableSymbolIds)h.add(R);return y=b.rows.size,b.rows},()=>({definitions:v.length,misses:s.length,unkeyed:a.length,rows:y}));for(let[b,R]of E)r.set(b,R);let w=s.filter(b=>E.has(b.def.symbolId)&&kt(e).capability("semantic-callees",b.def.relativePath).available).map(b=>({relativePath:b.def.relativePath,symbol:b.def.symbol,contentHash:b.contentHash,depsDigest:b.depsDigest,payload:JSON.stringify(E.get(b.def.symbolId)??[])}));return w.length>0?$("semantic.callees.cache-write",()=>ml(e,w),()=>({entries:w.length})):$("semantic.callees.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",misses:s.length})),{rows:r,incompleteSymbolIds:g,unavailableSymbolIds:h}}function VE(e,t){let n=[],i=new Map,r=0,o=0;for(let{definition:s,callees:a}of t){if(!Ke(s.relativePath)){o+=1;continue}if(!i.has(s.relativePath)){let c=se(e,s.relativePath),u=c?Dp(e,s.relativePath):null;i.set(s.relativePath,c&&u?{contentHash:Ft(e,s.relativePath,c),depsDigest:u}:null)}let l=i.get(s.relativePath);if(!l){r+=1;continue}n.push({relativePath:s.relativePath,symbol:s.symbol,contentHash:l.contentHash,depsDigest:l.depsDigest,payload:JSON.stringify(a)})}return{entries:n,sourceMissing:r,skippedUnsupportedLanguage:o}}var JE="typescript-callees-v3-incomplete-scan";function Dp(e,t){let n=Ke(t);if(n==="typescript")return Sr(e,t,JE)?.key??null;let i=ZE(e,t);return n==="rust"?jt(JSON.stringify({kind:"semantic-callees",language:n,engine:oi(e.config.projectRoot),positionMapping:"nearby-leaf-v2-callsite-line",depsDigest:i})):i}function YE(e){try{return JSON.parse(e)}catch{return null}}var XE=Fi("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function ZE(e,t){return XE.get(e,t,()=>{let i=[...Be(e).get(t)??[]].sort().map(r=>`${r}:${Ft(e,r,se(e,r))}`);return jt(i.join("|"))})}function b2(e,t,n={}){let i=fe(e,t);if(!i)return[];let o=!ke(i.symbol)&&!e.isIgnored(i.relativePath)?[{relativePath:i.relativePath,line:i.startLine}]:[],s=On(e,i,{semantic:n.semantic,semanticEvidence:pe}).map(u=>({relativePath:u.file,line:u.line})),a=QE(e,i),l=new Set,c=[];for(let u of[...o,...s,...a]){let d=`${u.relativePath}:${u.line}`;l.has(d)||(l.add(d),c.push(u))}return c}function QE(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=ew(t.symbol);if(n.length===0)return[];let i=[];for(let r of he(e,{extensions:[".rb"],includeIgnored:!1})){let o=se(e,r);if(!o)continue;let s=o.split(`
|
|
50
|
+
`);for(let a=0;a<s.length;a++){let l=s[a]??"";n.some(c=>new RegExp(`@${c}\\b|\\b${c}:`).test(l))&&i.push({relativePath:r,line:a})}}return i}function ew(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,""),i=n.split("_").filter(Boolean),r=new Set;return n&&r.add(n),i.length>=1&&r.add(i[i.length-1]),i.length>=2&&r.add(i.slice(-2).join("_")),[...r]}import{statSync as tw}from"fs";function mi(e){let t=e.get("SELECT COUNT(*) as c FROM documents").c,n=e.get("SELECT COUNT(*) as c FROM global_symbols").c,i=e.get("SELECT COUNT(*) as c FROM mentions WHERE role = 1").c,r=e.get("SELECT COUNT(*) as c FROM mentions WHERE role != 1").c;return{documents:t,symbols:n,definitions:i,references:r,...nw(e.generation.databasePath)}}function nw(e){try{let t=tw(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function iw(e,t){return xl(e).filter(n=>rw({pattern:t,relativePath:n})).map(n=>({relativePath:n}))}function rw(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 i=pn(n.pattern),r=pn(n.relativePath);if(!/[*?]/.test(i))return r.includes(i);let o=i.includes("/")?i:`**/${i}`;return Bs(o.split("/"),r.split("/"))}function Bs(e,t){if(e.length===0)return t.length===0;let[n,...i]=e;return n==="**"?Bs(i,t)||t.length>0&&Bs(e,t.slice(1)):t.length===0||!ow(n??"",t[0]??"")?!1:Bs(i,t.slice(1))}function ow(e,t){let n="^";for(let i of e)i==="*"?n+="[^/]*":i==="?"?n+="[^/]":n+=sw(i);return n+="$",new RegExp(n).test(t)}function sw(e){return/[\\^$.*+?()[\]{}|]/.test(e)?`\\${e}`:e}function Tp(e,t,n){let i=[],r=[],o=new Map;for(let s of[...e].sort(n)){let a=s.channel??"default",l=t[a]??Number.MAX_SAFE_INTEGER,c=o.get(a)??0;if(c>=l){r.push(s);continue}i.push(s),o.set(a,c+1)}return{selected:i,omitted:r}}function Os(e,t,n,i,r=!1){let o=[...e],s=[],a=new Set,l=0;for(;o.length>0&&s.length<t;){let c=o.filter(m=>l+m.evidenceCharacters<=n||r&&s.length===0);if(c.length===0)break;let u=c.filter(m=>m.roles.includes("location")||m.roles.includes("definition")).sort(i);c.sort((m,f)=>Pp(f,a)-Pp(m,a)||i(m,f));let d=u[0]??c[0];s.push(d),l+=d.evidenceCharacters;for(let m of Fp(d))a.add(m.key);o.splice(o.indexOf(d),1)}return{selected:s,omitted:o.sort(i)}}function Pp(e,t){let n=Fp(e).reduce((o,s)=>o+(t.has(s.key)?0:s.weight),0),i=Math.max(0,8-e.priority)*20,r=Math.min(500,Math.ceil(e.evidenceCharacters/160));return n+i-r}function Fp(e){return[...e.reasons.map(aw),...e.roles.map(t=>({key:`role:${t}`,weight:lw(t)})),{key:`file:${e.relativePath}`,weight:180},{key:`scope:${cw(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 aw(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 lw(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 cw(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}var Mp=64,Ap=12;function oc(e,t,n={}){if(t.length===0)throw new Error("The source search pattern must not be empty.");let i=n.context??6;if(!Number.isSafeInteger(i)||i<0)throw new RangeError(`context must be a non-negative safe integer; received ${i}`);let r=n.limit??12;if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`limit must be a positive safe integer; received ${r}`);let o=n.regexp?as(t,"source search pattern",n.ignoreCase?"iu":"u"):null,s=n.ignoreCase?t.toLocaleLowerCase():t,a=ms(e,{scope:n.scope}),l=[],c=[];for(let h of a.files){let S=h.relativePath,v=mw(h.text);if(v.length===0)continue;let y=h.freshness.semantic.state!=="stale"&&h.freshness.semantic.basis!=="no-compiler-document"?J(e,S):[],E=ee(e,S)?.callables??[],w=0;for(let b=0;b<v.length;b+=1){let R=v[b]??"",C=R.endsWith("\r")?R.slice(0,-1):R;if(!(o?o.test(C):(n.ignoreCase?C.toLocaleLowerCase():C).includes(s)))continue;w+=1;let I=Ge(y,b),x=uw(E,b),P=I&&!Le(I.symbol)?I:null,_=P?.startLine??x?.startLine??I?.startLine??b,D=P?.endLine??x?.endLine??I?.endLine??b,T=Ar(e,S,b,_,D);l.push({relativePath:S,focusLine:b,ownerSymbol:P?.symbol??null,ownerShort:P?k(P.symbol):x?.name??(I?k(I.symbol):null),ownerStartLine:T.startLine,ownerEndLine:T.endLine,fileKind:V(S),freshness:h.freshness})}w>0&&c.push({relativePath:S,matchingLines:w,returnedMatches:0,freshness:h.freshness})}l.sort(kp);let u=l.length>Mp?Np(l,Mp):l,d=r===Number.MAX_SAFE_INTEGER?l:n.ranking?Np(l,r):l.slice(0,r),m=new Map(a.files.map(h=>[h.relativePath,h.text])),f=d.flatMap(h=>{let S=m.get(h.relativePath),v=S===void 0?null:dw(h.relativePath,S,h.focusLine,i);return v?[{...v,...h}]:[]}),p=new Map;for(let h of f)p.set(h.relativePath,(p.get(h.relativePath)??0)+1);for(let h of c)h.returnedMatches=p.get(h.relativePath)??0;let g=fw(c);return{pattern:t,mode:n.regexp?"regexp":"literal",identities:l,...u.length<l.length?{identityManifest:u}:{},identityCoverage:{mode:u.length===l.length?"complete":"bounded",returned:u.length,total:l.length,omitted:l.length-u.length},matches:f,matchingLines:l.length,matchingFiles:c.length,omittedMatches:Math.max(0,l.length-f.length),fileCoverage:c,scopeHints:g.slice(0,Ap),omittedScopeHints:Math.max(0,g.length-Ap),scannedFiles:a.files.length,textCoverage:{basis:"current-project-text-files",candidateFiles:a.candidateFiles,scannedTextFiles:a.files.length,scannedBytes:a.scannedBytes,skippedBinaryPaths:a.skippedBinaryPaths,skippedUnreadablePaths:a.skippedUnreadablePaths,skippedOversizedPaths:a.skippedOversizedPaths,semanticFiles:{aligned:a.files.filter(h=>h.freshness.semantic.state==="aligned").length,stale:a.files.filter(h=>h.freshness.semantic.state==="stale").length,unavailable:a.files.filter(h=>h.freshness.semantic.state==="unavailable").length}}}}function uw(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,i)=>n.endLine-n.startLine-(i.endLine-i.startLine)||n.startLine-i.startLine)[0]??null}function dw(e,t,n,i){let r=t.split(`
|
|
51
|
+
`),o=t.endsWith(`
|
|
52
|
+
`)?r.length-1:r.length;if(n<0||n>=o)return null;let s=Math.max(0,n-i),a=Math.min(o-1,n+i);return{relativePath:e,startLine:s,endLine:a,focusLine:n,source:r.slice(s,a+1).join(`
|
|
53
|
+
`)}}function mw(e){if(e.length===0)return[];let t=e.split(`
|
|
54
|
+
`);return e.endsWith(`
|
|
55
|
+
`)&&t.pop(),t}function fw(e){let t=new Map;for(let n of e){let i=pw(n.relativePath),r=t.get(i)??{matchingLines:0,matchingFiles:0};r.matchingLines+=n.matchingLines,r.matchingFiles+=1,t.set(i,r)}return[...t.entries()].map(([n,i])=>({scope:n,...i})).sort((n,i)=>i.matchingLines-n.matchingLines||i.matchingFiles-n.matchingFiles||n.scope.localeCompare(i.scope))}function pw(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function Np(e,t){let n=e.map((r,o)=>({...r,priority:$s(r.fileKind),sequence:o,evidenceCharacters:1,roles:["search"],reasons:["search"],symbols:r.ownerSymbol?[r.ownerSymbol]:[],behaviorSignals:[]})),i=[];for(let r of[0,1,2]){let o=t-i.length;if(o===0)break;let s=n.filter(a=>$s(a.fileKind)===r);i.push(...Os(s,o,Number.MAX_SAFE_INTEGER,kp).selected)}return i.map(({priority:r,sequence:o,evidenceCharacters:s,roles:a,reasons:l,symbols:c,behaviorSignals:u,...d})=>d)}function kp(e,t){return $s(e.fileKind)-$s(t.fileKind)||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||e.relativePath.localeCompare(t.relativePath)||e.focusLine-t.focusLine}function $s(e){switch(e){case"entry":case"source":case"worker":return 0;case"barrel":return 1;case"test":return 2}}var sc=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 jr(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 ct(e){return new Set(jr(e).flatMap(ac).filter(t=>t.length>=3))}function ac(e){let t=js(e);return t.length>4&&t.endsWith("e")?[t,t.slice(0,-1)]:[t]}function js(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")?_p(t.slice(0,-2)):t.length>5&&t.endsWith("ing")?_p(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 _p(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}var Bp=new WeakMap,Op=new WeakMap,$p=new WeakMap,jp=new WeakMap,Hp=new WeakMap;function Up(e,t){let n=Op.get(e);n||(n=new Map,Op.set(e,n));let i=n.get(t);if(i)return i;let r=ae(e,t)?.rootNode;if(!r)return n.set(t,[]),[];let o=new Set;Ut(r,c=>{if(c.type!=="call_expression")return;let u=c.childForFieldName("function")??c.namedChild(0),d=/^([A-Za-z_$][\w$]*(?:\.Service)?)\.of$/u.exec(u?.text.replace(/\s+/gu,"")??"");d&&o.add(d[1])});let s=Ce(e,t).filter(c=>!!c.sourcePath),a=new Set;for(let c of o){let u=/^([A-Za-z_$][\w$]*)\.Service$/u.exec(c);if(u){for(let d of s)d.localName===u[1]&&a.add(d.sourcePath);continue}if(c==="Service"){J(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 l=uc([...a]).sort();return n.set(t,l),l}function Un(e,t,n={}){let r=Jt(e,t)?.filter(f=>!n.ranges||n.ranges.some(p=>f.line>=p.startLine&&f.line<=p.endLine));if(!r)return{targets:[],unresolvedCallsites:0};let o=Ce(e,t).filter(f=>!!f.sourcePath),s=Fw(se(e,t)??""),a=ae(e,t)?.rootNode??null,l=a?hw(a):zp(),c=new Map,u=Xt(e),d=[],m=0;for(let f of r){if(!f.memberAccess)continue;let p=Yt(t,u.get(f.calleeLeaf)??[]);if(n.excludeIndexedTargets!==!1&&Bn(e,t,p,!0,f.calleeQualifier))continue;let g=f.calleeQualifier,h=Pw(e,t,f,o);if(h){d.push(h);continue}let S=gw(e,t,f,o,yw(l,f.calleeQualifier,f.line));if(S.length>0){d.push(...S);continue}let v=bw(e,t,f);if(v.length>0){d.push(...v);continue}let y=g?s.get(g)??g:null,w=(y?uc(o.filter(R=>(R.localName??R.importedName)===y).map(R=>R.sourcePath)):[]).flatMap(R=>{let C=c.get(R);return C||(C=Mt(e,R)??[],c.set(R,C)),C.filter(L=>L.name===f.calleeLeaf).map(L=>({file:R,callable:L}))});if(w.length!==1){m+=1;continue}let b=w[0];d.push({calleeLeaf:f.calleeLeaf,line:f.line,sourceFile:t,targetFile:b.file,targetStartLine:b.callable.startLine,targetEndLine:b.callable.endLine,resolution:"direct-import-receiver",strength:"candidate"})}return{targets:d,unresolvedCallsites:m}}function gw(e,t,n,i,r){let o=n.calleeQualifier;if(!o||!/^[A-Za-z_$][\w$]*$/u.test(o))return[];if(r.size!==1)return[];let s=[...r][0],a=uc(i.filter(u=>u.localName===s||u.importedName===s).map(u=>u.sourcePath));if(a.length!==1)return[];let l=a[0],c=xw(e,l,n.calleeLeaf);return c.map(u=>({calleeLeaf:u.name,line:n.line,sourceFile:t,targetFile:u.file,targetStartLine:u.startLine,targetEndLine:u.endLine,serviceFile:l,resolutionAlternativeCount:c.length,resolution:"imported-service-object-member",strength:"candidate"}))}function zp(){return{declarations:new Map,callbacks:[]}}function hw(e){let t=zp();return Ut(e,n=>{if(n.type==="variable_declarator"){let l=n.childForFieldName("name")??n.namedChild(0),c=n.childForFieldName("value")??n.namedChild(1);if(l?.type!=="identifier"||!c)return;let u=new Set;if(Ut(c,d=>{if(d.type!=="member_expression")return;let m=d.childForFieldName("object")??d.namedChild(0),f=d.childForFieldName("property")??d.namedChild(1);m?.type==="identifier"&&f?.text==="Service"&&u.add(m.text)}),u.size===1){let d=t.declarations.get(l.text)??[];d.push({line:n.startPosition.row,alias:[...u][0]}),t.declarations.set(l.text,d)}return}if(!["arrow_function","function_expression","generator_function"].includes(n.type))return;let i=n.childForFieldName("parameters")??n.childForFieldName("parameter");if(!i)return;let r=n.parent;for(;r&&r.type!=="call_expression";)r=r.parent;if(!r)return;let o=r.childForFieldName("function")??r.namedChild(0),s=/^([A-Za-z_$][\w$]*)\.Service\.use$/u.exec(o?.text??"");if(!s)return;let a=new Set;Ut(i,l=>{l.type==="identifier"&&a.add(l.text)}),a.size!==0&&t.callbacks.push({startLine:n.startPosition.row,endLine:n.endPosition.row,receivers:a,alias:s[1]})}),t}function yw(e,t,n){if(!t||!/^[A-Za-z_$][\w$]*$/u.test(t))return new Set;let i=new Set((e.declarations.get(t)??[]).filter(r=>r.line<=n).map(r=>r.alias));for(let r of e.callbacks)r.startLine<=n&&r.endLine>=n&&r.receivers.has(t)&&i.add(r.alias);return i}function bw(e,t,n){let i=n.calleeQualifier;if(!i||!/^[A-Za-z_$][\w$]*$/u.test(i))return[];let r=ae(e,t)?.rootNode;if(!r)return[];let o=Sw(e,t,r,n.line,n.calleeLeaf,i),s=o?Cw(o,i):null;if(!s)return[];if(!vw(s))return[];let a=(Mt(e,t)??[]).filter(f=>f.startLine<=s.startPosition.row&&f.endLine>=s.endPosition.row).sort((f,p)=>f.endLine-f.startLine-(p.endLine-p.startLine))[0];if(!a)return[];let l=J(e,t).filter(f=>f.isFunctionLike&&f.leaf===a.name);if(l.length!==1)return[];let c=l[0],u=jp.get(e);u||(u=new Map,jp.set(e,u));let d=`${c.symbol}\0${n.calleeLeaf}`,m=u.get(d);if(!m){let f=[];for(let p of Cr(e,c)){let g=ae(e,p.file)?.rootNode;if(!g)continue;let h=g.descendantsOfType("call_expression").filter(y=>y.startPosition.row>p.line||y.endPosition.row<p.line?!1:(y.childForFieldName("function")??y.namedChild(0))?.text.replace(/\s+/gu,"").replace(/<[^<>]*>$/u,"").match(/[A-Za-z_$][\w$]*$/u)?.[0]===c.leaf);if(h.length!==1)continue;let v=h[0].childForFieldName("arguments")?.namedChildren.find(y=>fi(y).type==="object");if(v)for(let y of fi(v).namedChildren){if(y.type==="shorthand_property_identifier"&&y.text===n.calleeLeaf){f.push(...Hs(e,p.file,n.calleeLeaf,y,y));continue}if(y.type!=="pair")continue;let E=y.childForFieldName("key")??y.namedChild(0),w=y.childForFieldName("value")??y.namedChild(1);Us(E?.text)!==n.calleeLeaf||!w||f.push(...Hs(e,p.file,n.calleeLeaf,w,y))}}m=f.filter((p,g,h)=>h.findIndex(S=>S.file===p.file&&S.startLine===p.startLine&&S.endLine===p.endLine&&S.name===p.name)===g),u.set(d,m)}return m.map(f=>({calleeLeaf:f.name,line:n.line,sourceFile:t,targetFile:f.file,targetStartLine:f.startLine,targetEndLine:f.endLine,resolutionAlternativeCount:m.length,resolution:"factory-callback-member",strength:m.length===1?"exact":"candidate"}))}function Sw(e,t,n,i,r,o){let s=$p.get(e);s||(s=new Map,$p.set(e,s));let a=s.get(t);if(!a){a=new Map;for(let l of n.descendantsOfType("call_expression")){let c=l.childForFieldName("function")??l.namedChild(0),u=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(c?.text.replace(/\s+/gu,"")??"");if(u)for(let d=l.startPosition.row;d<=l.endPosition.row;d+=1){let m=`${d}\0${u[1]}\0${u[2]}`,f=a.get(m);(!f||l.endIndex-l.startIndex<f.endIndex-f.startIndex)&&a.set(m,l)}}s.set(t,a)}return a.get(`${i}\0${o}\0${r}`)??null}function vw(e){return e.descendantsOfType("return_statement").some(t=>{let n=t.childForFieldName("argument")??t.namedChild(0);return!!(n&&fi(n).type==="object")})}function Cw(e,t){let n=e.parent;for(;n;){if(/(?:function|method|lambda)/u.test(n.type)||n.type==="arrow_function"){let i=n.childForFieldName("parameters")??n.childForFieldName("parameter"),r=!1;if(i&&Ut(i,o=>{o.type==="identifier"&&o.text===t&&(r=!0)}),r)return n}n=n.parent}return null}function Hs(e,t,n,i,r){if(i.type==="identifier")return(Mt(e,t)??[]).filter(l=>l.name===i.text).map(l=>({...l,file:t}));let o=lc(e,t,i.text);if(o.length>0)return o;if(!cc(i))return[];let a=(Mt(e,t)??[]).filter(l=>l.startLine>=r.startPosition.row&&l.endLine<=r.endPosition.row&&(l.name===n||l.name.startsWith("source@"))).sort((l,c)=>l.endLine-l.startLine-(c.endLine-c.startLine))[0];return[a?{...a,file:t}:{name:n,file:t,startLine:r.startPosition.row,endLine:r.endPosition.row}]}function xw(e,t,n){let i=Hp.get(e);i||(i=new Map,Hp.set(e,i));let r=`${t}\0${n}`,o=i.get(r);if(o)return o;let s=ww(e,t).flatMap(a=>Rw(e,a,t,n));return i.set(r,s),s}function Rw(e,t,n,i){let r=ae(e,t)?.rootNode,o=Mt(e,t)??[];if(!r)return[];let s=Iw(e,t,n);if(s.size===0)return[];let a=new Set,l=[],c=[],u=[];return Ut(r,m=>{if(Ew(m,s)){if(m.type==="pair"){let f=m.childForFieldName("key")??m.namedChild(0),p=m.childForFieldName("value")??m.namedChild(1);if(Us(f?.text)!==i||!p)return;if(p.type==="identifier")a.add(p.text);else if(cc(p))l.push({name:i,startLine:m.startPosition.row,endLine:m.endPosition.row});else{let g=Lw(e,t,p.text),h=lc(e,t,p.text);if(g.length>0)u.push(...g);else if(h.length>0)u.push(...h);else{let S=Dw(m);S&&c.push(S)}}return}m.type==="shorthand_property_identifier"&&m.text===i&&a.add(i)}}),[...o.filter(m=>a.has(m.name)).map(m=>({...m,file:t})),...l.map(m=>({...m,file:t})),...c.map(m=>({...m,file:t})),...u].filter((m,f,p)=>p.findIndex(g=>g.file===m.file&&g.name===m.name&&g.startLine===m.startLine&&g.endLine===m.endLine)===f)}function Ew(e,t){let n=e,i=null;for(;n;){if(n.type==="object"&&(i=n),n.type==="call_expression"){if(!i)return!1;let r=n.childForFieldName("function")??n.namedChild(0);return r?t.has(r.text.replace(/\.of$/u,""))&&r.text.endsWith(".of"):!1}n=n.parent}return!1}function ww(e,t){let n=Bp.get(e);n||(n=new Map,Bp.set(e,n));let i=n.get(t);if(i)return i;let r=new Set([t]),o=J(e,t).filter(a=>a.leaf==="Service"&&a.isTypeLike);for(let a of o)for(let l of Cr(e,a))r.add(l.file);let s=[...r].sort();return n.set(t,s),s}function Iw(e,t,n){let i=new Set;Pt(t,n)&&i.add("Service");for(let r of Ce(e,t)){if(!r.sourcePath||!Pt(r.sourcePath,n))continue;if(r.kind==="namespace"&&r.localName){i.add(`${r.localName}.Service`);continue}(r.importedName==="default"?r.localName:r.importedName)==="Service"?i.add(r.localName??r.importedName):r.localName&&r.importedName!=="default"&&i.add(`${r.localName}.Service`)}return i}function lc(e,t,n){let i=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!i)return[];let r=ae(e,t)?.rootNode;if(!r)return[];let o=Gp(r,i[1]),s=o?Kp(o):null;if(!s)return[];let a=s.childForFieldName("function")??s.namedChild(0),l=a?qp(e,t,a.text):[];if(l.length!==1)return[];let c=l[0],u=ae(e,c.relativePath)?.rootNode;if(!u)return[];let d=Wp(u,c.startLine,c.endLine);if(!d)return[];let m=[];for(let f of d.descendantsOfType("return_statement")){let p=f.childForFieldName("argument")??f.namedChild(0);if(!p)continue;let g=fi(p);if(g.type==="object")for(let h of g.namedChildren){if(h.type==="shorthand_property_identifier"&&h.text===i[2]){for(let y of Mt(e,c.relativePath)??[])y.name===i[2]&&m.push({...y,file:c.relativePath});continue}if(h.type!=="pair")continue;let S=h.childForFieldName("key")??h.namedChild(0),v=h.childForFieldName("value")??h.namedChild(1);if(!(Us(S?.text)!==i[2]||!v))if(v.type==="identifier")for(let y of Mt(e,c.relativePath)??[])y.name===v.text&&m.push({...y,file:c.relativePath});else cc(v)&&m.push({name:i[2],startLine:h.startPosition.row,endLine:h.endPosition.row,file:c.relativePath})}}return m.filter((f,p,g)=>g.findIndex(h=>h.file===f.file&&h.name===f.name&&h.startLine===f.startLine&&h.endLine===f.endLine)===p)}function Lw(e,t,n){let i=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!i)return[];let r=ae(e,t)?.rootNode;if(!r)return[];let o=Gp(r,i[1]),s=o?Kp(o):null,a=s?.childForFieldName("function")??s?.namedChild(0),l=a?qp(e,t,a.text):[];if(l.length!==1||!s)return[];let c=l[0],u=ae(e,c.relativePath)?.rootNode;if(!u)return[];let d=Wp(u,c.startLine,c.endLine);if(!d)return[];let m=new Set,f=d.childForFieldName("parameters")??d.childForFieldName("parameter");if(f&&Ut(f,R=>{R.type==="identifier"&&m.add(R.text)}),m.size===0)return[];let p=lc(e,t,n);if(p.length===0)return[];let g=(Mt(e,c.relativePath)??[]).filter(R=>R.startLine>=c.startLine&&R.endLine<=c.endLine),h=(Jt(e,c.relativePath)??[]).filter(R=>R.line>=c.startLine&&R.line<=c.endLine),S=new Set,v=p.map(R=>({name:R.name,startLine:R.startLine,endLine:R.endLine})),y=new Set;for(;v.length>0&&y.size<32;){let R=v.shift(),C=`${R.name}\0${R.startLine}\0${R.endLine}`;if(!y.has(C)){y.add(C);for(let L of h.filter(I=>I.line>=R.startLine&&I.line<=R.endLine)){if(L.memberAccess&&L.calleeQualifier&&m.has(L.calleeQualifier)){S.add(L.calleeLeaf);continue}if(L.memberAccess)continue;let I=g.filter(x=>x.name===L.calleeLeaf);I.length===1&&v.push(I[0])}}}if(S.size===0)return[];let w=s.childForFieldName("arguments")?.namedChildren.find(R=>fi(R).type==="object");if(!w)return[];let b=[];for(let R of fi(w).namedChildren){if(R.type==="shorthand_property_identifier"&&S.has(R.text)){b.push(...Hs(e,t,R.text,R,R));continue}if(R.type!=="pair")continue;let C=R.childForFieldName("key")??R.namedChild(0),L=R.childForFieldName("value")??R.namedChild(1),I=Us(C?.text);!I||!S.has(I)||!L||b.push(...Hs(e,t,I,L,R))}return b.filter((R,C,L)=>L.findIndex(I=>I.file===R.file&&I.name===R.name&&I.startLine===R.startLine&&I.endLine===R.endLine)===C)}function Gp(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 Kp(e){return e.type==="call_expression"?e:e.descendantsOfType("call_expression")[0]??null}function qp(e,t,n){let i=n.replace(/\s+/gu,"").replace(/<[^<>]*>$/u,""),r=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(i);if(r){let d=Ce(e,t).filter(p=>p.localName===r[1]&&p.sourcePath);if(d.length!==1||!d[0].sourcePath)return[];let m=d[0].sourcePath,f=_n(e,m,r[2]).filter(p=>p.isFunctionLike);return f.length>0?f:(Mt(e,m)??[]).filter(p=>p.name===r[2]).map(p=>({...p,relativePath:m}))}if(!/^[A-Za-z_$][\w$]*$/u.test(i))return[];let o=J(e,t).filter(d=>d.leaf===i&&d.isFunctionLike);if(o.length>0)return o;let s=(Mt(e,t)??[]).filter(d=>d.name===i).map(d=>({...d,relativePath:t}));if(s.length>0)return s;let a=Ce(e,t).filter(d=>d.localName===i&&d.sourcePath&&d.kind!=="namespace");if(a.length!==1||!a[0].sourcePath)return[];let l=a[0].sourcePath,c=a[0].importedName==="default"?i:a[0].importedName,u=_n(e,l,c).filter(d=>d.isFunctionLike);return u.length>0?u:(Mt(e,l)??[]).filter(d=>d.name===c).map(d=>({...d,relativePath:l}))}function Wp(e,t,n){let i=null;return Ut(e,r=>{!/(?:function|method|lambda)/u.test(r.type)&&r.type!=="arrow_function"||r.startPosition.row>t||r.endPosition.row<n||(!i||r.endIndex-r.startIndex<i.endIndex-i.startIndex)&&(i=r)}),i}function cc(e){return["arrow_function","function_expression","generator_function"].includes(e.type)||e.descendantsOfType(["arrow_function","function_expression","generator_function"]).length>0}function Dw(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 Us(e){return e?e.replace(/^(?:['"])(.*)(?:['"])$/u,"$1"):null}function Pw(e,t,n,i){let r=/^this\.([A-Za-z_$][\w$]*)$/u.exec(n.calleeQualifier??"");if(!r)return null;let o=ae(e,t)?.rootNode;if(!o)return null;let s=Tw(o,n.line);if(!s)return null;let a=new Set;if(Ut(s,g=>{if(g.type!=="assignment_expression")return;let h=g.childForFieldName("left")??g.namedChild(0),S=g.childForFieldName("right")??g.namedChild(g.namedChildCount-1);if(h?.text.replace(/\s+/gu,"")!==`this.${r[1]}`||!S)return;let v=fi(S);if(v.type!=="new_expression")return;let E=(v.childForFieldName("constructor")??v.namedChild(0))?.text.match(/[A-Za-z_$][\w$]*$/u)?.[0];E&&a.add(E)}),a.size!==1)return null;let l=[...a][0],c=i.filter(g=>g.localName===l);if(c.length!==1)return null;let u=c[0].importedName==="default"?l:c[0].importedName,d=c[0].importedName==="default"?_n(e,c[0].sourcePath,l):[],m=d.length===1?d[0].leaf:u,f=J(e,c[0].sourcePath).filter(g=>g.isFunctionLike&&g.leaf===n.calleeLeaf&&gm(g.symbol)===m);if(f.length!==1)return null;let p=f[0];return{calleeLeaf:n.calleeLeaf,line:n.line,sourceFile:t,targetFile:p.relativePath,targetStartLine:p.startLine,targetEndLine:p.endLine,targetSymbol:p.symbol,resolution:"constructed-member-receiver",strength:"exact"}}function Tw(e,t){let n=[];return Ut(e,i=>{["class","class_declaration","class_definition"].includes(i.type)&&i.startPosition.row<=t&&i.endPosition.row>=t&&n.push(i)}),n.sort((i,r)=>i.endPosition.row-i.startPosition.row-(r.endPosition.row-r.startPosition.row))[0]??null}function fi(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 Ut(e,t){t(e);for(let n of e.namedChildren)Ut(n,t)}function Fw(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 i of e.matchAll(n)){let r=i[1],o=i[2];r&&o&&t.set(r,o)}return t}function uc(e){let t=[];for(let n of e)t.some(i=>Pt(i,n))||t.push(n);return t}import{existsSync as Aw}from"fs";import{SymbolRole as Nw}from"@c4312/scip";import{deserializeSCIP as Mw}from"@c4312/scip";function Vp(e,t){return Mw(jo(e,{inputKind:t,maxBytes:$o}))}var dc=new WeakMap;function xn(e,t,n,i){let r=ee(e,t),o=(r?.callSites??[]).filter(f=>f.line>=n&&f.line<=i);if(!r||o.length===0)return{available:!!r,targets:[],resolvedCallsites:0,unresolvedCallsites:0};let s=fc(e);if(!s)return{available:!1,targets:[],resolvedCallsites:0,unresolvedCallsites:o.length};let a=(s.byFile.get(t)??[]).filter(f=>f.sourceLine>=n&&f.sourceLine<=i).map(f=>({...f,calleeLeaf:f.definition.leaf})),l=Jp(o.map(f=>({line:f.line,leaf:f.calleeLeaf}))),c=Jp(a.map(f=>({line:f.sourceLine,leaf:f.calleeLeaf}))),u=new Set([...l].flatMap(([f,p])=>c.get(f)===p?[f]:[])),d=a.filter(f=>u.has(Xp(f.sourceLine,f.calleeLeaf))),m=[...u].reduce((f,p)=>f+(l.get(p)??0),0);return{available:!0,targets:d,resolvedCallsites:m,unresolvedCallsites:Math.max(0,o.length-m)}}function mc(e,t,n,i){let r=fc(e);return r?{available:!0,targets:(r.byFile.get(t)??[]).filter(o=>o.sourceLine>=n&&o.sourceLine<=i)}:{available:!1,targets:[]}}function Yp(e,t,n,i){let r=fc(e);return r?{available:!0,targets:(r.byFile.get(t)??[]).filter(o=>o.sourceLine>=n&&o.sourceLine<=i&&zs(e,o.definition)).map(o=>({...o,calleeLeaf:o.definition.leaf}))}:{available:!1,targets:[]}}function fc(e){if(dc.has(e))return dc.get(e)??null;let t=kw(e);return dc.set(e,t),t}function kw(e){if(!e.generation.indexPath||!Aw(e.generation.indexPath))return null;try{let t=ze(e),n=new Map(t.map(o=>[o.symbol,o])),i=Vp(e.generation.indexPath,"SCIP source-range call-target index"),r=new Map;for(let o of i.documents??[]){let s=o.relativePath;if(!s||e.isIgnored(s))continue;let a=[];for(let l of o.occurrences??[]){if(!l.symbol||(l.symbolRoles&Nw.Definition)!==0)continue;let c=n.get(l.symbol),u=l.range?.[0];!c||!Number.isInteger(u)||a.push({sourceLine:u,definition:c})}r.set(s,a)}return{byFile:r}}catch{return null}}function zs(e,t){if(!t.isFunctionLike)return!1;let n=ee(e,t.relativePath);return!n||n.callables.some(i=>i.name===t.leaf&&i.startLine===t.startLine&&i.endLine===t.endLine)?!0:_w(t)}function _w(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 Jp(e){let t=new Map;for(let n of e){let i=Xp(n.line,n.leaf);t.set(i,(t.get(i)??0)+1)}return t}function Xp(e,t){return`${e}\0${t}`}import{existsSync as Gs,readdirSync as eg}from"fs";import{join as Hr}from"path";var Bw={files:new Set,pathPrefixes:[]},Ow={reasonsByFile:new Map},pc=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,$w=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,tg=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],jw=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),Hw=4,Uw=Fe("package-surface",{clearGroups:["whole-project"]}),zw=Fe("package-operational-surface",{clearGroups:["whole-project"]});function ng(e){return Uw.get(e,()=>Kw(e.config.projectRoot))}function En(e,t){let n=ng(e);return n.files.has(t)?!0:n.pathPrefixes.some(i=>t.startsWith(i))}function ig(e,t){return ng(e).files.has(t)}function Gw(e){return zw.get(e,()=>qw(e.config.projectRoot))}function rg(e,t){return Gw(e).reasonsByFile.get(t)??[]}function Kw(e){let t=new Set,n=[];for(let{manifest:i,packageRoot:r}of og(e))for(let o of Ww(i))cg(e,r,o,t,n);return t.size===0&&n.length===0?Bw:{files:t,pathPrefixes:n}}function qw(e){let t=new Map;for(let{manifest:n,packageRoot:i}of og(e)){let r=Vw(n);for(let s of r)Zp(e,i,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 l of Jw(a))Zp(e,i,l,`package script "${s}"`,t)}}return t.size===0?Ow:{reasonsByFile:t}}function og(e){let t=[],n=ag(e,"");return n&&t.push({manifest:n,packageRoot:""}),sg(e,"",t,0),t}function sg(e,t,n,i){if(i>=Hw)return;let r=Hr(e,t);if(Gs(r))for(let o of eg(r,{withFileTypes:!0})){if(!o.isDirectory()||jw.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=ag(e,s);a&&n.push({manifest:a,packageRoot:s}),sg(e,s,n,i+1)}}function ag(e,t){let n;try{n=nt(e,Hr(t,"package.json"),{maxBytes:8*1024*1024,inputKind:"package manifest"})}catch(i){if(!St(i))throw i;return null}try{let i=JSON.parse(n);return i&&typeof i=="object"?i:null}catch{return null}}function Ww(e){let t=[];for(let i of["main","module","types","browser"])typeof e[i]=="string"&&t.push(e[i]);let n=e.bin;if(typeof n=="string")t.push(n);else if(n&&typeof n=="object")for(let i of Object.values(n))typeof i=="string"&&t.push(i);return lg(e.exports,t),t}function Vw(e){let t=e.bin;return typeof t=="string"?[t]:!t||typeof t!="object"?[]:Object.values(t).filter(n=>typeof n=="string")}function Jw(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 i of e.matchAll(n)){let r=i[1];r&&!r.startsWith("node_modules/")&&!r.startsWith("./node_modules/")&&t.push(r)}return t}function Zp(e,t,n,i,r){let o=new Set;cg(e,t,n,o,[]);for(let s of o){let a=r.get(s)??[];a.includes(i)||a.push(i),r.set(s,a)}}function lg(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))lg(n,t)}function cg(e,t,n,i,r){let o=n.replace(/\\/g,"/").replace(/^\.\//,"");if(o===""||o.startsWith(".."))return;let s=o.indexOf("*");if(s>=0){let l=o.slice(0,s);for(let c of Qp(l))c!==""&&r.push(Rn(t,c));return}let a=o.replace($w,"");for(let l of Qp(a)){l===a&&l===o&&i.add(Rn(t,o));for(let c of tg)Yw(e,i,t,l+c)}i.add(Rn(t,o))}function Qp(e){let t=[e];return pc.test(e)&&(t.push(e.replace(pc,"src/")),t.push(e.replace(pc,""))),t}function Yw(e,t,n,i){let r=Rn(n,i);if(t.add(r),!i.startsWith("src/")||Gs(Hr(e,r)))return;let o=tg.find(u=>i.endsWith(u));if(!o)return;let s=i.slice(0,-o.length);Xw(e,t,n,s,o);let a=s.lastIndexOf("/");if(a<=4)return;let l=s.slice(0,a),c=s.slice(a+1);for(let u of ug(e,n,l,`${c}${o}`))t.add(u)}function Xw(e,t,n,i,r){let o=Rn(n,`${i}/index${r}`);Gs(Hr(e,o))&&t.add(o)}function ug(e,t,n,i){let r=Hr(e,t,n);if(!Gs(r))return[];let o=[];for(let s of eg(r,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...ug(e,t,a,i)):s.isFile()&&s.name===i&&o.push(Rn(t,a))}return o}function Rn(e,t){return e?`${e}/${t}`:t}import{existsSync as gc,readdirSync as Zw}from"fs";import{dirname as Qw,join as hc}from"path";var eI={rootFiles:new Set,sourcePrefixes:[]},tI=new Set([".git",".codebaseiq","node_modules","target"]),nI=6,iI=Fe("rust-library-surface",{clearGroups:["whole-project"]});function dg(e,t,n){if(!n.endsWith(".rs")||!sI(rI(e),n))return!1;let i=J(e,n).find(r=>r.symbol===t);return i?aI(ie(e,n)[i.startLine]??""):!1}function rI(e){return iI.get(e,()=>oI(e.config.projectRoot))}function oI(e){let t=new Set,n=new Set;for(let i of lI(e)){let r=nt(e,hc(i,"Cargo.toml"),{maxBytes:8388608,inputKind:"Cargo manifest"}),o=cI(r),s=Rn(i,"src/lib.rs"),a=o?Rn(i,o):!uI(r)&&Tt(e,s)?s:null;if(!a)continue;t.add(a);let l=Qw(a).replaceAll("\\","/");n.add(l==="."?"":`${l}/`)}return t.size===0?eI:{rootFiles:t,sourcePrefixes:[...n].sort()}}function sI(e,t){return t.endsWith(".rs")?e.rootFiles.has(t)?!0:dI(t)?!1:e.sourcePrefixes.some(n=>t.startsWith(n)):!1}function aI(e){return/^\s*pub\s+(?!\()/.test(e)}function lI(e){if(!gc(e))return[];let t=[];return mg(e,"",t,0),t}function mg(e,t,n,i){let r=hc(e,t);if(gc(r)&&(gc(hc(r,"Cargo.toml"))&&n.push(t),!(i>=nI)))for(let o of Zw(r,{withFileTypes:!0})){if(!o.isDirectory()||tI.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name;mg(e,s,n,i+1)}}function cI(e){let t=!1;for(let n of e.split(`
|
|
56
|
+
`)){let i=n.replace(/\s+#.*$/,"").trim(),r=/^\[([^\]]+)\]$/.exec(i);if(r){t=r[1]==="lib";continue}if(!t)continue;let o=/^path\s*=\s*["']([^"']+)["']/.exec(i)?.[1];if(o)return o.replaceAll("\\","/").replace(/^\.\//,"")}return null}function uI(e){let t=!1;for(let n of e.split(`
|
|
57
|
+
`)){let i=n.replace(/\s+#.*$/,"").trim(),r=/^\[([^\]]+)\]$/.exec(i);if(r){t=r[1]==="package";continue}if(t&&/^autolib\s*=\s*false\b/.test(i))return!0}return!1}function dI(e){return/(?:^|\/)src\/main\.rs$/.test(e)||/(?:^|\/)src\/bin\//.test(e)||/(?:^|\/)(?:examples|tests|benches)\//.test(e)}function Ki(e){return V(e)==="barrel"}function pg(e){return mI.get(e,()=>{let n=he(e,{includeIgnored:!1}).filter(s=>{let a=V(s);return a==="entry"||a==="worker"});if(n.length===0)return new Set;let i=Be(e),r=new Set,o=new Set;for(;n.length>0;){let s=n.shift();if(!r.has(s)){r.add(s),V(s)==="barrel"&&o.add(s);for(let a of i.get(s)??[])r.has(a)||n.push(a)}}return o})}var mI=Fe("live-barrels",{clearGroups:["whole-project"]});function yc(e,t){return pg(e).has(pt(t))}function gg(e){let t=pg(e);return he(e,{includeIgnored:!1}).filter(n=>Ki(n)&&!t.has(n)&&!fI(e,n))}function fI(e,t){let n=pt(t),i=Nn(e).forFile(n,{facts:!0}).facts?.callables;return i&&i.length>0?!0:(e.get(`SELECT COUNT(*) AS n
|
|
58
|
+
FROM defn_enclosing_ranges der
|
|
59
|
+
JOIN documents d ON d.id = der.document_id
|
|
60
|
+
WHERE d.relative_path = ?
|
|
61
|
+
AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function Ye(e,t){let n=pt(t),i=V(t);return i==="entry"||i==="worker"||bc(n)||yc(e,n)}function qi(e,t,n){let i=pt(n),r=[];En(e,i)&&r.push("package-surface-file"),hI(e,t,i)&&r.push("transitive-package-surface"),dg(e,t,i)&&r.push("rust-public-library"),II(t,i)&&r.push("framework-entrypoint");let o=e.config.entryRoots;return o&&(o.files?.some(s=>pt(s)===i)&&r.push("configured-file"),o.pathPrefixes?.some(s=>i.startsWith(pt(s)))&&r.push("configured-path-prefix"),o.qualifiedVars?.some(s=>PI(t,s))&&r.push("configured-qualified-var"),o.symbolPatterns?.some(s=>{try{return as(s,"entryRoots.symbolPatterns entry").test(t)}catch{return!1}})&&r.push("configured-symbol-pattern")),r}function Ue(e,t,n){return qi(e,t,n).length>0}var pI=Fe("package-surface-reachability",{clearGroups:["whole-project"]}),gI=Fe("explicit-package-surface-reachability",{clearGroups:["whole-project"]});function hI(e,t,n){let i=yI(e).get(n);return i===void 0?!1:i===null||i.has(re(t))}function hg(e,t,n){let i=bI(e).get(n);return i===void 0?!1:i===null||i.has(re(t))}function yI(e){return pI.get(e,()=>yg(e,t=>En(e,t)))}function bI(e){return gI.get(e,()=>yg(e,t=>ig(e,t)))}function yg(e,t){let n=new Map,i=[];for(let r of he(e,{includeIgnored:!1}))t(r)&&(n.set(r,null),i.push(r));for(;i.length>0;){let r=i.shift(),o=n.get(r);if(o!==void 0)for(let s of br(e,r)){if(!s.sourcePath||e.isIgnored(s.sourcePath))continue;let a=SI(o,s);a!==void 0&&vI(n,s.sourcePath,a)&&i.push(s.sourcePath)}}return n}function SI(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(i=>e.has(i))?null:void 0;let n=t.names.filter(i=>e.has(i));return n.length>0?new Set(n):void 0}function vI(e,t,n){if(!e.has(t))return e.set(t,n),!0;let i=e.get(t);if(i===void 0)return!1;if(i===null||n===null)return i===null?!1:(e.set(t,null),!0);let r=!1;for(let o of n)i.has(o)||(i.add(o),r=!0);return r}var bg=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),CI=new Set(["default","generateMetadata","generateStaticParams"]),xI=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),RI=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),EI=new Set(["load","actions","entries",...bg]),wI=new Set(["default"]);function II(e,t){let n=re(e);return n===""?!1:Sg(t)?bg.has(n):vg(t)?CI.has(n):Cg(t)?xI.has(n):xg(t)?RI.has(n):Rg(t)?EI.has(n):DI(t)?wI.has(n):!1}function bc(e){return Sg(e)||vg(e)||Cg(e)||LI(e)||xg(e)||Rg(e)}function Sg(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function vg(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Cg(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function LI(e){let t="(?:middleware|proxy|instrumentation)\\.(?:ts|js|mts|mjs)";return new RegExp(`^(?:src/)?${t}$`).test(e)||new RegExp(`(?:^|/)src/${t}$`).test(e)||new RegExp(`(?:^|/)(?:apps|services|packages)/[^/]+/(?:src/)?${t}$`).test(e)}function xg(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Rg(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function DI(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function PI(e,t){let n=t.lastIndexOf("/");if(n<0)return!1;let i=t.slice(0,n),r=t.slice(n+1);return e.includes(fg(i)+"/")&&e.includes(fg(r)+".")}function fg(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function Eg(e,t,n={}){let i=new Map;if(t&&t.length===0)return i;let r=he(e,{includeIgnored:!1}),o=Xt(e),s=t??ze(e),a=new Set(s.map(c=>c.symbolId)),l=_I(s);return TI(e,i,r,o,a,l),FI(e,i,s,a),kI(e,i,r,o,a,l),n.semantic!==!1&&n.semanticEvidence&&OI(i,n.semanticEvidence.callerMap(e,BI(s))),i}function TI(e,t,n,i,r,o){for(let s of n){if(!ye(s))continue;let a=Jt(e,s);if(a)for(let l of a){if(o&&!o.has(l.calleeLeaf))continue;let c=Yt(s,i.get(l.calleeLeaf)??[]);if(!c||c.length===0)continue;let u=Bn(e,s,c,l.memberAccess,l.calleeQualifier);u&&r.has(u.symbolId)&&u.file!==s&&Sc(t,u.symbolId,s)}}}function FI(e,t,n,i){let r=AI(n);for(let o of MI(e,i))e.isIgnored(o.relative_path)||NI(o,r.get(o.symbol_id))||Sc(t,o.symbol_id,o.relative_path)}function MI(e,t){return ts(e,t?[...t]:void 0)}function AI(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 NI(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function kI(e,t,n,i,r,o){for(let s of n){if(ye(s)!=="rust")continue;let a=Ai(e,s,{includeRustAttributeNames:!0});if(a.length!==0)for(let{name:l}of a){if(o&&!o.has(l))continue;let c=i.get(l);if(c)for(let u of c)r.has(u.symbolId)&&u.file!==s&&Sc(t,u.symbolId,s)}}}function Sc(e,t,n){let i=e.get(t);i||(i=new Set,e.set(t,i)),i.add(n)}function _I(e){let t=new Set;for(let n of e){let i="leaf"in n&&typeof n.leaf=="string"?n.leaf:"symbol"in n&&typeof n.symbol=="string"?re(n.symbol):"";i&&t.add(i)}return t.size>0?t:null}function BI(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function OI(e,t){for(let[n,i]of t){let r=e.get(n);r||(r=new Set,e.set(n,r));for(let o of i)r.add(o)}}function vc(e,t,n={}){return Eg(e,t,n)}function Ur(e,t,n={}){return Fm(e,t,n)}function wg(e,t,n={}){let i=vc(e,t,{semantic:n.semantic,semanticEvidence:n.semanticEvidence});return n.sourceFallback===!1?i:pi(i,Ur(e,t))}function pi(e,t){let n=new Map;for(let[i,r]of e)n.set(i,new Set(r));for(let[i,r]of t){let o=n.get(i)??new Set;for(let s of r)o.add(s);n.set(i,o)}return n}function Ig(e,t,n){let i=t.identifierResolution==="strict"?yl:Tm,r=t.candidateNames?Lm(t.candidateNames):null,o=0,s=0,a=0,l=0,c="";for(let u of t.paths)if(o+=1,c=u,!(!ye(u)&&!(t.includeVueSfc&&um(u)))&&!e.isIgnored(u)&&!t.skipPath?.(u))try{if(r&&!Dm(se(e,u),r))continue;s+=1;let m=(p,g,h,S)=>{if(t.candidateNames&&!t.candidateNames.has(p))return;a+=1;let v=t.resolveTargets?t.resolveTargets({sourceFile:u,name:p,kind:g,defaultTargets:S}):S();for(let y of v)l+=1,n({sourceFile:u,name:p,target:y,occurrences:h,kind:g})},f=Oi(e,u);for(let[p,g]of f)m(p,"identifier",g.length,()=>i(e,u,p));for(let p of Ai(e,u,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let g=p.kind==="cross-language-dispatch"?()=>yl(e,u,p.name):()=>i(e,u,p.name);m(p.name,p.kind,p.occurrences,g)}}finally{t.afterPath?.(u),o%10===0&&$("source-reference-scan.progress",()=>{},()=>({scannedPaths:o,currentPath:c,candidateMatchedPaths:s,visitedNames:a,visitedHits:l}))}}function de(e){return e.endLine-e.startLine+1}function Lg(e,t={}){let{scope:n,files:i,minLoc:r=1,maxLoc:o=Number.POSITIVE_INFINITY,excludeSymbol:s,excludeEntrySurfaces:a=!1,excludeTypesFiles:l=!1,excludeRootedSymbols:c=!1,requireFunctionLikeSymbol:u=!1,requireCallableSymbol:d=!1,excludeRustTraitImplMembers:m=!1,includeSuppressed:f=!1,sortByLocDesc:p=!1}=t,g=[],h=$I(e,{scope:n,files:i,requireFunctionLikeSymbol:u,requireCallableSymbol:d}),S=new Map,v=new Map,y=w=>{let b=S.get(w);if(b!==void 0)return b;let R=Ye(e,w);return S.set(w,R),R},E=w=>{let b=v.get(w);if(b!==void 0)return b;let R=V(w);return v.set(w,R),R};for(let w of h){let b=w.relativePath;if(e.isIgnored(b)||a&&y(b)||!jI(w,{requireFunctionLikeSymbol:u,requireCallableSymbol:d})||s!==void 0&&w.symbol===s)continue;let R=de(w);R<r||R>o||l&&HI(b)||c&&Ue(e,w.symbol,b)||m&&at(w.symbol)||E(b)!=="test"&&(ki(w.symbol)||!f&&qo(e,b,w.startLine)||g.push(w))}return p?g.sort((w,b)=>de(b)-de(w)):g}function $I(e,t){return t.files!==void 0?[...new Set(t.files.map(i=>i.replace(/\\/g,"/")))].sort().filter(i=>!t.scope||i.includes(t.scope)).flatMap(i=>J(e,i)):t.requireCallableSymbol?vr(e,{scope:t.scope,symbolMatches:it,sqlPrefilter:"callable"}):t.requireFunctionLikeSymbol?vr(e,{scope:t.scope,symbolMatches:ke,sqlPrefilter:"function-like"}):vm(e,t.scope)}function jI(e,t){return t.requireCallableSymbol?it(e.symbol):t.requireFunctionLikeSymbol?ke(e.symbol):e.isFunctionLike}function HI(e){return(e.split("/").pop()??"").includes("types")}var U=class{constructor(t){this.db=t}db;scopedDefinitions(t){return Sm(this.db,t)}definitionsForFile(t){return J(this.db,t)}productionCallableDefinitions(t={}){return Lg(this.db,t)}calleeMap(t,n={}){return this.calleeEvidenceMap(t,n).rows}calleeEvidenceMap(t,n={}){return Er(this.db,t,{...n,semanticEvidence:pe})}crossFileCallerMap(t,n={}){return vc(this.db,t,{...n,semanticEvidence:pe})}sourceFallbackCallerFiles(t,n={}){return Ur(this.db,t,n)}callerFileMap(t,n={}){return wg(this.db,t,{...n,semanticEvidence:pe})}frameworkReferencedSymbolIds(t){let n=new Map;for(let r of t){if(!r.leaf)continue;let o=n.get(r.leaf)??[];o.push(r.symbolId),n.set(r.leaf,o)}let i=new Set;for(let r of he(this.db,{includeIgnored:!1}))if(ye(r)==="rust")for(let{name:o}of Ai(this.db,r,{includeRustAttributeNames:!0}))for(let s of n.get(o)??[])i.add(s);return i}symbolsWithNonSelfCallees(t,n={}){if(t.length===0)return new Set;let i=new Map(t.map(s=>[s.symbolId,s.symbol])),r=this.calleeEvidenceMap(t,n),o=new Set([...r.rows.entries()].filter(([s,a])=>{let l=i.get(s);return a.some(c=>c.symbol!==l)}).map(([s])=>s));for(let s of r.incompleteSymbolIds)o.add(s);for(let s of r.unavailableSymbolIds)o.add(s);return o}fileDependencyGraph(t){return Be(this.db,t)}fileKind(t){return V(t)}hasSuppressionComment(t){return qo(this.db,t.relativePath,t.startLine)}sourceFiles(){return Mi(this.db)}scanSourceReferences(t,n){Ig(this.db,t,n)}callableSignature(t){let n=Nn(this.db).forFile(t.relativePath,{facts:!0}).facts?.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};var UI=16,zI=4,Cc=3e3,GI=800,KI=new Set(["assignment","const_declaration","const_item","field_declaration","lexical_declaration","local_declaration_statement","local_variable_declaration","static_item","variable_declaration"]);function Ag(e,t,n={}){let i=n.maxSteps??UI;if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`maxSteps must be a positive safe integer; received ${i}`);let r=new Map(t.nodes.map(F=>[F.id,F])),o=ZI(n.focusLocations??[]),s=new Set,a=new Map(t.edges.map(F=>[F.id,F])),l=wn(t.paths.flatMap(F=>F.nodeIds)),c=wn(t.anchors.filter(F=>F.status==="matched").flatMap(F=>F.nodeIds)),u=t.nodes.filter(F=>F.disposition==="emitted"&&F.attributes.upstreamCausalPath===!0).sort((F,Z)=>Number(Z.attributes.upstreamCausalDistance??0)-Number(F.attributes.upstreamCausalDistance??0)||F.id.localeCompare(Z.id)).map(F=>F.id),d=new Set(u),m=Math.max(0,i-c.length),p=qI(t,c,o,m).slice(0,m),g=new Set(p),h=new Set(p),S=new Set([...l,...u,...c]),v=t.edges.filter(F=>F.disposition==="emitted"&&F.kind!=="structural-membership"),y=t.edges.filter(F=>F.disposition!=="excluded"&&F.disposition!=="unsupported"&&F.kind!=="structural-membership"),E=new Set([...t.paths.flatMap(F=>F.edgeIds),...v.filter(F=>d.has(F.fromNodeId)&&d.has(F.toNodeId)).map(F=>F.id)]),w=t.paths.some(F=>F.edgeIds.length>0),b=new Set(c);for(let F of p)b.add(F);for(let F of t.paths){let Z=F.nodeIds[0],X=a.get(F.edgeIds[0]??""),Se=F.nodeIds[1];Z&&Se&&X?.fromNodeId===Z&&X.toNodeId===Se&&b.add(Z)}if(t.paths.every(F=>F.nodeIds.length===0))for(let F of t.anchors)for(let Z of F.nodeIds)b.add(Z);let R=iL(c,y,r,zI),C=wn(v.filter(F=>F.kind==="call"&&c.includes(F.fromNodeId)).map(F=>F.toNodeId)),L=new Set(wn([...R,...w?[]:C]));for(let F of L)b.add(F);let I=wn(v.flatMap(F=>S.has(F.fromNodeId)||S.has(F.toNodeId)?[F.fromNodeId,F.toNodeId]:[])),x=t.nodes.filter(F=>F.disposition==="emitted"&&F.kind!=="structural-region"&&v.some(Z=>Z.fromNodeId===F.id||Z.toNodeId===F.id)).map(F=>F.id),P=wn([...u,...l,...c,...p,...L,...I,...x]).filter(F=>r.has(F)),_=[];for(let F of P)w&&!S.has(F)&&!g.has(F)&&!L.has(F)||_.length>=i&&!S.has(F)||_.push(F);let D=new Set(_),T=new Map(_.map(F=>[F,oL(F)])),A=new Set([...l,...u]),W=new Set(t.anchors.flatMap(F=>F.nodeIds)),le=_.map((F,Z)=>{let X=r.get(F),Se=XI(X,o);for(let tt of Se)s.add(Wi(X.location.file,tt));return{id:T.get(F),nodeId:F,order:Z,role:W.has(F)?"anchor":A.has(F)?"connector":"junction",kind:X.kind,label:X.label,location:X.location,behavior:WI(e,X,W.has(F),[...new Set([...Se,...YI(e,X,y,r,E,b)])],Se,b.has(X.id)&&(Se.length===0||W.has(X.id)),L.has(X.id),h.has(X.id)&&Se.length===0)}}),q=new Map;for(let F of t.paths)for(let Z=0;Z<F.edgeIds.length;Z+=1){let X=a.get(F.edgeIds[Z]),Se=F.nodeIds[Z],tt=F.nodeIds[Z+1];!X||!Se||!tt||q.set(X.id,X.fromNodeId===Se&&X.toNodeId===tt?"forward":"reverse")}let N=y.filter(F=>D.has(F.fromNodeId)&&D.has(F.toNodeId)).sort((F,Z)=>rL(F,Z,t)).map((F,Z)=>({id:sL(F.id),edgeId:F.id,order:Z,kind:F.kind,fromStepId:T.get(F.fromNodeId),toStepId:T.get(F.toNodeId),directed:!0,pathTraversal:q.get(F.id)??"adjacent",evidence:F.evidence})),K=new Map(N.map(F=>[F.edgeId,F.id])),te=t.paths.map(F=>({id:F.id,status:F.status,stepIds:F.nodeIds.flatMap(Z=>{let X=T.get(Z);return X?[X]:[]}),transitionIds:F.edgeIds.flatMap(Z=>{let X=K.get(Z);return X?[X]:[]})})),me=le.flatMap(F=>F.location?[`${F.location.file}:${F.location.line+1}`]:[]),ge=t.anchors.some(F=>F.status==="ambiguous"),ce=te.some(F=>F.status==="connected"||F.status==="candidate"),be=te.some(F=>F.status==="partial");return{status:le.length===0?"unavailable":ge?"ambiguous":ce&&!be?"connected":be?"partial":"connected",steps:le,transitions:N,paths:te,coverage:{candidateNodes:P.length,returnedNodes:_.length,omittedNodeIds:P.filter(F=>!D.has(F)),returnedTransitions:N.length,withheldStatements:le.reduce((F,Z)=>F+(Z.behavior?.coverage.omittedStatements??0),0),requestedFocusLocations:o,matchedFocusLocations:o.filter(F=>s.has(Wi(F.file,F.line))),unmatchedFocusLocations:o.filter(F=>!s.has(Wi(F.file,F.line)))},behaviorCommand:Mg(me,"behavior"),exactSourceCommand:Mg(me,"source")}}function qI(e,t,n,i){if(i<=0||n.length===0)return[];let r=new Set(t),o=new Set(n.map(s=>Wi(s.file,s.line)));return wn(e.edges.filter(s=>s.disposition!=="excluded"&&s.disposition!=="unsupported"&&["call","runtime-boundary"].includes(s.kind)&&r.has(s.fromNodeId)&&s.evidence.some(a=>!["candidate","unknown"].includes(a.strength)&&a.location&&o.has(Wi(a.location.file,a.location.line)))).sort((s,a)=>{let l=s.evidence.find(u=>u.location)?.location,c=a.evidence.find(u=>u.location)?.location;return(l?.file??"").localeCompare(c?.file??"")||(l?.line??Number.MAX_SAFE_INTEGER)-(c?.line??Number.MAX_SAFE_INTEGER)||s.id.localeCompare(a.id)}).map(s=>s.toNodeId)).slice(0,i)}function WI(e,t,n,i,r,o,s,a){if(!t.location||!["symbol","source-construct","runtime-boundary-participant"].includes(t.kind))return null;let l=t.location.endLine??t.location.line,c=ie(e,t.location.file),u=i.length>0?i:[t.location.line],d=t.kind==="runtime-boundary-participant"?gt(e,t.location.file,0,Math.max(0,c.length-1),[t.location.line]):gt(e,t.location.file,t.location.line,l,u),m=i.filter(L=>L>=d.startLine&&L<=d.endLine),f=ji(e,t.location.file,d.startLine,d.endLine,m),p=f??(m.length>0?ji(e,t.location.file,d.startLine,d.endLine,m,{requireSavings:!1}):null),g=m.length>0?QI(e,t,d.startLine,d.endLine,m,p,o):null,h=c.slice(d.startLine,d.endLine+1).join(`
|
|
62
|
+
`).length,S=Sn(e,t.location.file,d.startLine,d.endLine),v=c.slice(d.startLine,d.endLine+1).some((L,I)=>L.length>GI&&(S.get(d.startLine+I)??[]).some(x=>["binding","branch","loop","call","return","throw","mutation"].includes(x))),y=L=>VI(e,t,d.startLine,d.endLine,r.filter(I=>I>=d.startLine&&I<=d.endLine),L),E=(s||t.kind==="runtime-boundary-participant"||t.anchorIds.length>0)&&h<=Cc,w=n&&(m.length===0||E);if(f&&(a||w))return y(Dg(f));if(!a&&!w&&g&&!v&&!E&&g.renderedCharacters<(p?.outlineCharacters??h))return y(g);if(f)return y(Dg(f));let b=c.slice(d.startLine,d.endLine+1),R=b.join(`
|
|
63
|
+
`),C=Sn(e,t.location.file,d.startLine,d.endLine);return y({kind:"source",constructKind:"source construct",signature:b.find(L=>L.trim().length>0)?.trim()??t.label,lines:b.map((L,I)=>({line:d.startLine+I,endLine:d.startLine+I,depth:0,signals:C.get(d.startLine+I)??[],text:L,copied:!0})),coverage:{sourceStatements:b.length,representedStatements:b.length,copiedStatements:b.length,omittedStatements:0},rawCharacters:R.length,renderedCharacters:R.length})}function VI(e,t,n,i,r,o){if(!t.location)return o;let s=mc(e,t.location.file,n,i);if(!s.available)return o;let a=Sn(e,t.location.file,n,i),l=ie(e,t.location.file),c=new Set(r);for(let v of r){let y=Ks(l[v]??"");if(!y)continue;let E=yn(e,t.location.file,y).find(w=>w>v&&w<=i);E!==void 0&&c.add(E)}let u=[...new Map(s.targets.flatMap(v=>{let y=v.definition,E=y.relativePath===t.location.file&&y.startLine<=i&&y.endLine>=n;if(y.isTypeLike||E)return[];let w=zs(e,y),b=r.length>0&&w&&a.get(v.sourceLine)?.includes("return"),R=w&&c.has(v.sourceLine);return w&&!b&&!R?[]:[[y.symbol,{definition:y,kind:b?"return-value-transformer":R?"focused-causal-target":"compiler-referenced-declaration"}]]})).values()].sort((v,y)=>v.definition.relativePath.localeCompare(y.definition.relativePath)||v.definition.startLine-y.definition.startLine||v.definition.symbol.localeCompare(y.definition.symbol)),d=[],m=u.filter(({kind:v})=>v!=="compiler-referenced-declaration").map(({definition:v})=>({owner:v,depth:1})),f=new Set,p=new Set(u.map(({definition:v})=>v.symbol));for(;m.length>0;){let v=m.shift();if(!v||f.has(v.owner.symbol))continue;f.add(v.owner.symbol);let{owner:y,depth:E}=v,w=mc(e,y.relativePath,y.startLine,y.endLine);if(!w.available)continue;let b=Sn(e,y.relativePath,y.startLine,y.endLine),R=ie(e,y.relativePath);for(let C of w.targets){let L=C.definition,I=L.relativePath===y.relativePath&&L.startLine<=y.endLine&&L.endLine>=y.startLine;if(L.isTypeLike||I)continue;let x=zs(e,L),P=Ks(R[C.sourceLine]??""),_=x&&P!==null&&yn(e,y.relativePath,P).some(T=>T>C.sourceLine&&T<=y.endLine&&(b.get(T)??[]).some(A=>["branch","return","throw"].includes(A))),D=x&&((b.get(C.sourceLine)??[]).some(T=>["branch","return","throw"].includes(T))||_);x&&!D||(p.has(L.symbol)||(p.add(L.symbol),d.push({definition:L,kind:x?"focused-causal-target":"compiler-referenced-declaration"})),x&&E<2&&m.push({owner:L,depth:E+1}))}}let g=[...new Map([...u,...d].map(v=>[v.definition.symbol,v])).values()].sort((v,y)=>v.definition.relativePath.localeCompare(y.definition.relativePath)||v.definition.startLine-y.definition.startLine||v.definition.symbol.localeCompare(y.definition.symbol)),h=[],S=[];for(let{definition:v,kind:y}of g){let E=y==="compiler-referenced-declaration"?JI(e,v.relativePath,v.startLine,v.endLine):{startLine:v.startLine,endLine:v.endLine},w=ie(e,v.relativePath).slice(E.startLine,E.endLine+1).join(`
|
|
64
|
+
`),b=y==="compiler-referenced-declaration"?null:ji(e,v.relativePath,v.startLine,v.endLine,[]),R=b?[b.signature,...b.lines.map(P=>`${P.line+1}${P.signals.length>0?`[${P.signals.join(",")}]`:""} ${P.text}`)].join(" | "):null,C=R&&R.length<w.length?R:w,L={symbol:v.symbol,label:v.leaf,file:v.relativePath,line:E.startLine,endLine:E.endLine},I=y==="compiler-referenced-declaration"?1e3:8e3,x=y==="compiler-referenced-declaration"?12:120;if(C.length>I||E.endLine-E.startLine>x){S.push({...L,reason:"source-too-large"});continue}h.push({kind:y,...L,text:C})}return{...o,...h.length===0?{}:{supportingDeclarations:h},...S.length===0?{}:{omittedSupportingDeclarations:S}}}function JI(e,t,n,i){let r=ae(e,t);if(!r)return{startLine:n,endLine:i};let o=[];Ng(r.rootNode,a=>{KI.has(a.type)&&a.startPosition.row<=n&&a.endPosition.row>=i&&o.push(a)});let s=o.sort((a,l)=>a.endPosition.row-a.startPosition.row-(l.endPosition.row-l.startPosition.row)||a.endIndex-a.startIndex-(l.endIndex-l.startIndex))[0];return s?{startLine:s.startPosition.row,endLine:s.endPosition.row}:{startLine:n,endLine:i}}function Ng(e,t){t(e);for(let n of e.namedChildren)Ng(n,t)}function Dg(e){return{kind:"outline",constructKind:e.constructKind,signature:e.signature,lines:e.lines,coverage:e.coverage,rawCharacters:e.rawCharacters,renderedCharacters:e.outlineCharacters}}function YI(e,t,n,i,r,o){if(!t.location||!["symbol","source-construct","runtime-boundary-participant"].includes(t.kind))return[];let s=new Set,a=new Set(ee(e,t.location.file)?.callSites.map(l=>l.line)??[]);if(t.kind==="runtime-boundary-participant"&&s.add(t.location.line),o.has(t.id))for(let l of xr(e,{files:[t.location.file]}))l.source.startLine>=t.location.line&&l.source.startLine<=(t.location.endLine??t.location.line)&&s.add(l.source.startLine);for(let l of n){if(l.fromNodeId!==t.id&&l.toNodeId!==t.id)continue;let c=i.get(l.fromNodeId===t.id?l.toNodeId:l.fromNodeId),u=o.has(t.id)&&["call","reference","runtime-boundary"].includes(l.kind)&&l.fromNodeId===t.id,d=(c?.anchorIds.length??0)>0;if(!r.has(l.id)&&!u&&!d)continue;let m=l.evidence.flatMap(S=>S.location?.file===t.location.file?[S.location.line]:[]),f=m.filter(S=>a.has(S));for(let S of f.length>0?f:m)s.add(S);let p=c?.attributes.leaf;if(typeof p!="string"||p.length===0)continue;let g=yn(e,t.location.file,p).filter(S=>S>=t.location.line&&S<=(t.location.endLine??t.location.line)),h=g.find(S=>a.has(S))??g[0];h!==void 0&&s.add(h)}return[...s].sort((l,c)=>l-c)}function XI(e,t){if(!e.location)return[];let n=e.location.endLine??e.location.line;return t.filter(i=>i.file===e.location.file&&i.line>=e.location.line&&i.line<=n).map(i=>i.line)}function ZI(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(Wi(n.file,n.line),{file:n.file,line:n.line})}return[...t.values()].sort((n,i)=>n.file.localeCompare(i.file)||n.line-i.line)}function Wi(e,t){return`${e}\0${t}`}function QI(e,t,n,i,r,o,s){if(!t.location)return null;let a=ie(e,t.location.file),l=Sn(e,t.location.file,n,i),c=[...l].filter(([,D])=>D.length>0).map(([D])=>D).sort((D,T)=>D-T),u=r.map(D=>(l.get(D)??[]).length>0?D:c.find(T=>T>D&&T-D<=8)??D),d=new Set([...r,...u]),m=s?Tl(e,t.location.file,n,i,{minimumBodyLines:0}):null,f=o?[...new Map(u.flatMap(D=>o.lines.filter(T=>T.text.length<=500&&T.signals.some(A=>["branch","loop","catch","finally"].includes(A))&&D>=T.line&&D<=T.endLine).sort((T,A)=>T.endLine-T.line-(A.endLine-A.line)||T.line-A.line).slice(0,2).map(T=>[`${T.line}\0${T.endLine}`,T]))).values()]:xs(e,t.location.file,n,i,u);for(let D of m?.lines??[])d.add(D.line);for(let D of f)d.add(D.line);for(let[D,T]of l)T.includes("call")&&T.includes("shape")&&d.add(D);let p=[];for(let D of u){let T=Ks(a[D]??"");if(!T)continue;let A=yn(e,t.location.file,T).filter(N=>N>D&&N<=i),W=A[0];W!==void 0&&d.add(W);let le=A.find(N=>(l.get(N)??[]).some(K=>K==="branch"||K==="loop"));if(le===void 0)continue;d.add(le);let q=(o?.lines??[]).find(N=>N.line===le)??{line:le,endLine:Math.min(i,le+40),depth:0,signals:l.get(le)??[],text:(a[le]??"").trim(),copied:!0},Y=o?.lines??a.slice(q.line,q.endLine+1).map((N,K)=>{let te=q.line+K;return{line:te,endLine:te,depth:0,signals:l.get(te)??[],text:N.trim(),copied:!0}});p.push({focusLine:D,governingUse:le,lines:Y.filter(N=>N.line>=q.line&&N.line<=q.endLine&&N.text.length<=500&&N.signals.some(K=>["binding","branch","call","mutation"].includes(K)))})}for(let D of p.sort((T,A)=>A.governingUse-A.focusLine-(T.governingUse-T.focusLine)||T.focusLine-A.focusLine).slice(0,2))for(let T of D.lines.slice(0,14))d.add(T.line);let g=new Set(["binding","branch","loop","call","return","throw","mutation"]);for(let D of f)for(let T of o?.lines??[])T.line<D.line||T.line>D.endLine||T.signals.some(A=>g.has(A))&&d.add(T.line);let h=a.slice(n,i+1).flatMap((D,T)=>{let A=Ks(D);return A?[{name:A,line:n+T}]:[]}),S=!0;for(;S;){S=!1;for(let D of h)if([...d].some(A=>tL(a[A]??"",D.name))){d.has(D.line)||(d.add(D.line),S=!0);for(let A of yn(e,t.location.file,D.name))A<n||A>i||d.has(A)||(l.get(A)??[]).some(W=>g.has(W))&&(d.add(A),S=!0)}}for(let D of o?.lines??[])if(D.signals.some(T=>["branch","loop","catch","finally"].includes(T))&&d.has(D.line))for(let T of o?.lines??[])T.line<D.line||T.line>D.endLine||T.signals.some(A=>g.has(A))&&d.add(T.line);let v=ee(e,t.location.file),y=new Set(v?.callSites.map(D=>D.line)??[]),E=l,w=new Map([...o?.lines??[],...f].filter(D=>D.signals.some(T=>["branch","loop","catch","finally"].includes(T))).map(D=>[D.line,D])),b=new Map((o?.lines??[]).filter(D=>D.text.length<=500&&D.signals.includes("shape")&&(D.signals.includes("call")||D.signals.includes("mutation")||D.signals.includes("return"))).sort((D,T)=>D.endLine-D.line-(T.endLine-T.line)||D.line-T.line).map(D=>[D.line,D])),R=new Map((m?.lines??[]).map(D=>[D.line,D.signals.filter(T=>T!=="lifecycle")])),C=[...d].filter(D=>D>=n&&D<=i).sort((D,T)=>D-T).map(D=>{let T=w.get(D)??b.get(D);return{line:D,endLine:T?.endLine??D,depth:T?.depth??0,signals:eL([...E.get(D)??[],...o?.lines.filter(A=>D>=A.line&&D<=A.endLine).flatMap(A=>A.signals)??[],...R.get(D)??[],...r.includes(D)?["anchor"]:[],...y.has(D)?["call"]:[]]),text:T?.text??(a[D]??"").trim(),copied:T?.copied??!0}}).filter(D=>D.text.length>0);if(C.length===0)return null;let L=m?.candidateLines??Tl(e,t.location.file,n,i,{minimumBodyLines:0})?.candidateLines??0,I=Math.max(o?.coverage.sourceStatements??0,L,C.length),x=o?.signature??(a[n]??t.label).trim(),P=x.length+C.reduce((D,T)=>D+T.text.length+T.signals.join(",").length+12,0),_=a.slice(n,i+1).join(`
|
|
65
|
+
`).length;return{kind:"connector-slice",constructKind:o?.constructKind??"source construct",signature:x,lines:C,coverage:{sourceStatements:I,representedStatements:C.length,copiedStatements:C.length,omittedStatements:Math.max(0,I-C.length)},rawCharacters:_,renderedCharacters:P}}function eL(e){let t=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],n=new Set(e);return t.filter(i=>n.has(i))}function Ks(e){return/\b(?:const|let|var)\s+([\p{L}_$][\p{L}\p{N}_$]*)\s*(?:=|\bof\b|\bin\b)/u.exec(e)?.[1]??null}function tL(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");return new RegExp(`(?:^|[^\\p{L}\\p{N}_$])${n}(?:$|[^\\p{L}\\p{N}_$])`,"u").test(e)}function nL(e,t,n){return wn(e.flatMap(i=>{let r=n.get(i),o=t.filter(s=>s.kind==="call"&&s.toNodeId===i).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 l=Pg(a.edge)-Pg(s.edge);if(l!==0)return l;let c=Tg(s.node,r)?0:1,u=Tg(a.node,r)?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 c-u||d-m||s.node.label.localeCompare(a.node.label)});return o[0]?[o[0].node.id]:[]}))}function Pg(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 Tg(e,t){return!e.location||!t?.location?!1:Fg(e.location.file)===Fg(t.location.file)}function Fg(e){return e.split("/").filter(Boolean).slice(0,2).join("/")}function iL(e,t,n,i){let r=new Set(e),o=new Set,s=[],a=wn(e);for(let l=0;l<i&&a.length>0;l+=1){let c=a.filter(d=>!o.has(d));for(let d of c)o.add(d);let u=nL(c,t,n);a=[];for(let d of u)!r.has(d)&&!s.includes(d)&&s.push(d),o.has(d)||a.push(d)}return s}function rL(e,t,n){let i=new Map(n.paths.flatMap(r=>r.edgeIds).map((r,o)=>[r,o]));return(i.get(e.id)??Number.MAX_SAFE_INTEGER)-(i.get(t.id)??Number.MAX_SAFE_INTEGER)||e.id.localeCompare(t.id)}function oL(e){return`step:${e}`}function sL(e){return`transition:${e}`}function Mg(e,t){return e.length===0?null:`codebaseiq inspect ${e.map(n=>`--at ${aL(n)}`).join(" ")} --view ${t}`}function aL(e){return`'${e.replace(/'/gu,`'"'"'`)}'`}function wn(e){return[...new Set(e)]}var kg=4,lL=3,cL=12,uL=48,dL=64,yi=10,gi=6,mL=24,fL=320,xc=6,pL=12,gL=1,hL=4,yL=7,bL=12,Lc="source-construct:",SL=96,vL=32,_g=4,CL=32,xL=8;function RL(e,t,n={}){let i=Yg(t),r=cD(t);if(i.length===0)throw new Error("Anchor discovery requires at least one non-trivial repository term.");let o=n.limit??kg,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 U(e),l=a.scopedDefinitions(n.scope).filter(N=>!Le(N.symbol)),c=[...l],u=new Map(c.map(N=>[N.symbol,N])),d=new Map;for(let N of l)Bg(d,N,i);let m=ms(e,{scope:n.scope});for(let N of m.files){let te=J(e,N.relativePath).filter(ge=>!Le(ge.symbol));if(te.length===0)continue;let me=Jg(N.text);for(let ge=0;ge<me.length;ge+=1){let ce=ct(me[ge]??""),be=i.filter(Z=>ce.has(Z));if(be.length===0)continue;let F=Ge(te,ge);if(!(!F||Le(F.symbol)))for(let Z of be)zr(d,F,Z,"source",N.relativePath,ge)}}let f=Og(d),p=[...d.values()].map(N=>qs(N,f,r)).sort(Xe),g=wL(m.files,p,i),h=-1;for(let N of g){let K=J(e,N.relativePath),te=K.filter(F=>!Le(F.symbol)),me=ee(e,N.relativePath)?.callables??[],ge=new Map,ce=F=>{let Z=`${F.startLine}\0${F.endLine}\0${F.name}`,X=ge.get(Z);if(X)return X;let Se=EL(N.relativePath,K,F,()=>h--);return Se?(ge.set(Z,Se),c.push(Se),u.set(Se.symbol,Se),Bg(d,Se,i),Se):null};for(let F of me){let Z=ct(F.name);i.some(X=>Z.has(X))&&ce(F)}if(me.length===0)continue;let be=Jg(N.text);for(let F=0;F<be.length;F+=1){let Z=ct(be[F]??""),X=i.filter(Ti=>Z.has(Ti));if(X.length===0)continue;let Se=IL(me,F),tt=Se?ce(Se):null;if(!tt)continue;let ni=$g(te,F);if($g(ni?[ni,tt]:[tt],F)?.symbol===tt.symbol)for(let Ti of X)zr(d,tt,Ti,"source",N.relativePath,F)}}let S=Og(d),v=new Map(m.files.map(N=>[N.relativePath,N.text.split(/\r?\n/u)]));for(let N of d.values()){let K=v.get(N.definition.relativePath);K&&(N.sourceCharacters=K.slice(N.definition.startLine,N.definition.endLine+1).join(`
|
|
66
|
+
`).length)}let y=[...d.values()].map(N=>qs(N,S,r)).sort(Xe),E=Math.min(y.length,Math.max(cL,o*lL)),w=s?y:Vi([...y.slice(0,E),...[...y].sort(Ec).slice(0,Math.max(uL,E)),...nD(y,i),...iD(y,i,S)]),b=w.length,R=w.map(N=>u.get(N.symbol)).filter(N=>N?.isFunctionLike===!0),C=LL(c),L=DL(e,a,w,R,u,C,new Set(d.keys()),n.semantic!==!1),I=FL(L,w,d,S,u),x=ML(I,S,i),P=qL(e,a,L,d,S,c,u,n.semantic!==!1),D=[...NL(e,a,I,u,S,n.semantic!==!1),...x,...I,...P].map(N=>({...N,queryPathMatches:oD(N)})).sort((N,K)=>hi(N,K,S)),T=s?D:sD(D,o,S),A=i.filter(N=>S.has(N)),W=i.filter(N=>!S.has(N)),le=Math.max(0,y.length-b),q=Math.max(0,D.length-T.length)+le,Y=s?y.length:Math.min(y.length,o+kg);return{query:t,queryPathFragments:r,normalizedTerms:i,matchedTerms:A,unmatchedTerms:W,groups:T,candidateRoots:y,candidateRootCount:y.length,analyzedRootCount:b,omittedRootCount:le,omittedGroupCount:q,scannedFiles:m.files.length,scannedBytes:m.scannedBytes,recoveryCommand:q===0?null:`codebaseiq anchors ${Ys(t)}${n.scope?` --scope ${Ys(n.scope)}`:""} --limit ${Y}`}}function Yg(e){let t=jr(e).filter(n=>!sc.has(n.toLocaleLowerCase())).map(js).filter(n=>n.length>=3&&!sc.has(n));return[...new Set(t)]}function Bg(e,t,n){let i=ct(t.leaf),r=ct(t.relativePath),o=ct(t.documentation??"");for(let a of n)i.has(a)&&zr(e,t,a,"symbol"),r.has(a)&&zr(e,t,a,"path"),o.has(a)&&zr(e,t,a,"documentation");let s=e.get(t.symbol);s&&(s.symbolPhraseLength=dD(t.leaf,n))}function zr(e,t,n,i,r,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(i),r!==void 0&&o!==void 0&&a.locations.set(`${r}\0${o}`,{file:r,line:o}),s.matches.set(n,a),e.set(t.symbol,s)}function Og(e){let t=new Map;for(let n of e.values())for(let i of n.matches.keys())t.set(i,(t.get(i)??0)+1);return t}function EL(e,t,n,i){let r=t[0]?.documentId;if(r===void 0||t.find(a=>a.isFunctionLike&&a.leaf===n.name&&a.startLine===n.startLine&&a.endLine===n.endLine))return null;let s=i();return{documentId:r,symbolId:s,symbol:`${Lc}${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 wL(e,t,n){let i=new Set(t.slice(0,SL).map(s=>s.file)),r=new Set(n),o=e.map(s=>{let a=ct(s.relativePath),l=s.relativePath.slice(s.relativePath.lastIndexOf("/")+1).replace(/\.[^.]+$/u,""),c=ct(l),u=[...a].filter(m=>r.has(m)).length,d=[...c].filter(m=>r.has(m)).length;return{file:s,score:d*4+u}}).filter(s=>s.score>0).sort((s,a)=>a.score-s.score||zt(V(s.file.relativePath))-zt(V(a.file.relativePath))||s.file.relativePath.localeCompare(a.file.relativePath)).slice(0,vL);for(let s of o)i.add(s.file.relativePath);return e.filter(s=>i.has(s.relativePath))}function IL(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,i)=>n.endLine-n.startLine-(i.endLine-i.startLine)||n.startLine-i.startLine)[0]}function LL(e){let t=new Map;for(let n of e){if(!nn(n))continue;let i=`${n.relativePath}\0${rn(n.leaf)}`,r=t.get(i)??[];r.push(n),t.set(i,r)}return t}function $g(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,i)=>n.endLine-n.startLine-(i.endLine-i.startLine)||Number(nn(i))-Number(nn(n))||n.startLine-i.startLine||n.symbol.localeCompare(i.symbol))[0]}function nn(e){return e.symbol.startsWith(Lc)}function zn(e){return nn(e)?e.leaf:k(e.symbol)}function qs(e,t,n=[]){let i=e.definition,r=[...e.matches.entries()].map(([c,u])=>({term:c,sources:[...u.sources].sort(mD),locations:[...u.locations.values()].sort(Qg).slice(0,3)})).sort((c,u)=>c.term.localeCompare(u.term)),o=r.filter(c=>c.sources.some(u=>u!=="source")).map(c=>c.term),s=r.filter(c=>c.sources.includes("symbol")).map(c=>c.term),a=r.reduce((c,u)=>c+1/Math.max(1,t.get(u.term)??1),0),l=r.filter(c=>c.sources.includes("symbol")).reduce((c,u)=>c+1/Math.max(1,t.get(u.term)??1),0);return{symbol:i.symbol,label:zn(i),leaf:i.leaf,file:i.relativePath,line:i.startLine,endLine:i.endLine,kind:i.isFunctionLike?"callable":i.isTypeLike?"type":"symbol",fileKind:V(i.relativePath),matches:r,focusLocations:gD(e,t),matchedTerms:r.map(c=>c.term),symbolMatchedTerms:s,symbolPhraseLength:e.symbolPhraseLength,identityMatchedTerms:o,rarity:a,symbolRarity:l,queryPathMatches:uD(i.relativePath,n),...e.sourceCharacters===void 0?{}:{sourceCharacters:e.sourceCharacters}}}function DL(e,t,n,i,r,o,s,a){let l=i.filter(g=>!nn(g)),c=t.calleeMap(l,{additive:!1,semantic:a}),u=new Map,d=new Map;for(let g of n){let h=r.get(g.symbol),S=h?nn(h)?jg(e,h,r,o,1):Ws(e,h,c.get(h.symbolId)??[],r,1,s):[];u.set(g.symbol,S);for(let v of S){let y=r.get(v.toSymbol);y?.isFunctionLike&&(!h||!nn(h)||nn(y))&&d.set(y.symbol,y)}}let m=[...d.values()],f=t.calleeMap(m.filter(g=>!nn(g)),{additive:!1,semantic:a}),p=new Map;for(let g of m)p.set(g.symbol,nn(g)?jg(e,g,r,o,2):Ws(e,g,f.get(g.symbolId)??[],r,2,s));return n.map(g=>{let h=u.get(g.symbol)??[],S=h.flatMap(y=>p.get(y.toSymbol)??[]),v=In([...h,...S]);return{root:g,relations:v,nodeSymbols:new Set([g.symbol,...v.flatMap(y=>[y.fromSymbol,y.toSymbol])])}})}function Ws(e,t,n,i,r,o=new Set){let s=new Map;for(let a of n){let l=i.get(a.symbol);if(!l?.isFunctionLike||l.symbol===t.symbol||a.source==="ast-callsite"&&!TL(e,t,l,a.callsiteLine))continue;let c=s.get(l.symbol);(!c||lD(a,c)<0)&&s.set(l.symbol,a)}return[...s.entries()].map(([a,l])=>{let c=i.get(a);return{kind:"call",fromSymbol:t.symbol,fromLabel:k(t.symbol),fromFile:t.relativePath,toSymbol:c.symbol,toLabel:k(c.symbol),toFile:c.relativePath,depth:r,strength:Ic(l.source),evidence:l.source,callsiteLine:l.callsiteLine??PL(e,t,c)}}).sort((a,l)=>Number(o.has(l.toSymbol))-Number(o.has(a.toSymbol))||on(a,l)).slice(0,dL)}function jg(e,t,n,i,r){let o=xn(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:zn(t),fromFile:t.relativePath,toSymbol:a.symbol,toLabel:zn(a),toFile:a.relativePath,depth:r,strength:"exact",evidence:"scip-occurrence-callsite",callsiteLine:s.sourceLine}]});for(let s of Un(e,t.relativePath,{ranges:[{startLine:t.startLine,endLine:t.endLine}],excludeIndexedTargets:!1}).targets){let a=[...i.get(`${s.targetFile}\0${rn(s.calleeLeaf)}`)??[],...J(e,s.targetFile).filter(l=>l.isFunctionLike&&rn(l.leaf)===s.calleeLeaf)].find(l=>l.startLine===s.targetStartLine&&l.endLine===s.targetEndLine);!a||a.symbol===t.symbol||o.push({kind:"call",fromSymbol:t.symbol,fromLabel:zn(t),fromFile:t.relativePath,toSymbol:a.symbol,toLabel:zn(a),toFile:a.relativePath,depth:r,strength:s.strength==="exact"?"exact":"derived",evidence:"ast-member-import-candidate",callsiteLine:s.line})}for(let s of ee(e,t.relativePath)?.callSites??[]){if(s.line<t.startLine||s.line>t.endLine||s.memberAccess)continue;let a=(i.get(`${t.relativePath}\0${rn(s.calleeLeaf)}`)??[]).filter(c=>c.symbol!==t.symbol);if(a.length!==1)continue;let l=a[0];o.push({kind:"call",fromSymbol:t.symbol,fromLabel:zn(t),fromFile:t.relativePath,toSymbol:l.symbol,toLabel:zn(l),toFile:l.relativePath,depth:r,strength:"derived",evidence:"ast-callsite",callsiteLine:s.line})}return In(o).sort(on)}function PL(e,t,n){let i=rn(n.leaf);return ee(e,t.relativePath)?.callSites.find(r=>r.line>=t.startLine&&r.line<=t.endLine&&rn(r.calleeLeaf)===i)?.line??null}function TL(e,t,n,i){if(i===void 0)return!1;let r=rn(n.leaf);return ee(e,t.relativePath)?.callSites.some(o=>o.line===i&&rn(o.calleeLeaf)===r)??!1}function rn(e){return e.replace(/^#/u,"").replace(/\(\)$/u,"")}function FL(e,t,n,i,r){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},l=(u,d)=>{let m=a(u),f=a(d);m!==f&&(s[f]=m)};for(let u of e){let d=o.get(u.root.symbol);if(d!==void 0)for(let m of u.nodeSymbols){let f=o.get(m);f!==void 0&&l(d,f)}}let c=new Map;for(let u=0;u<t.length;u+=1){let d=a(u),m=c.get(d)??[];m.push(t[u]),c.set(d,m)}return[...c.values()].map((u,d)=>{let m=new Set(u.map(y=>y.symbol)),f=In(e.filter(y=>m.has(y.root.symbol)).flatMap(y=>y.relations)).sort(on),p=new Map(u.map(y=>[y.symbol,y]));for(let y of new Set(f.flatMap(E=>[E.fromSymbol,E.toSymbol]))){let E=n.get(y);if(E)p.has(y)||p.set(y,qs(E,i));else{let w=r.get(y);w&&p.set(y,Zg(w))}}let g=QL(u,f,p),h=u.filter(y=>f.some(E=>E.fromSymbol===y.symbol)).length,S=[...new Set(u.flatMap(y=>y.matchedTerms))].sort(),v=ZL(f,g,m,p);return{id:`anchor-set:${d+1}:${Kr(u[0])}`,kind:"connected-flow",roots:[...u].sort(Xe),keyAnchors:g,candidateOwnerCount:g.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:[],matchedTerms:S,relations:v,relationCount:f.length,orchestrationRootCount:h,omittedRelations:Math.max(0,f.length-yi),systemMapCommand:Wr(g,f,S)}})}function ML(e,t,n){let i=new Map(n.map((o,s)=>[o,s])),r=[];for(let o=0;o<e.length;o+=1){let s=e[o],a=Hg(s);if(a.size!==0)for(let l=o+1;l<e.length;l+=1){let c=e[l],u=Hg(c),d=[...a].filter(w=>u.has(w));if(d.length===0||![...a].some(w=>!u.has(w))||![...u].some(w=>!a.has(w)))continue;let m=AL(s,c);if(m.length<2)continue;let f=In([...s.relations,...c.relations]).sort(on),p=f.slice(0,yi),g=Vi([...s.roots,...c.roots]).sort(Xe),h=[...new Set([...s.matchedTerms,...c.matchedTerms])].sort(),S=d.sort((w,b)=>(i.get(w)??Number.MAX_SAFE_INTEGER)-(i.get(b)??Number.MAX_SAFE_INTEGER)||w.localeCompare(b)),v=+(s.relationCount>0)+ +(c.relationCount>0),y=+((s.orchestrationRootCount??0)>0)+ +((c.orchestrationRootCount??0)>0),E=Math.min(...S.map(w=>t.get(w)??Number.MAX_SAFE_INTEGER));r.push({sharedOrder:Math.min(...S.map(w=>i.get(w)??Number.MAX_SAFE_INTEGER)),sharedFrequency:E,connectedSides:v,orchestrationSides:y,group:{id:`parallel-paths:${Kr(s.roots[0])}:${Kr(c.roots[0])}`,kind:"parallel-paths",roots:g,keyAnchors:m,candidateOwnerCount:m.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:[...s.upstreamEntries,...c.upstreamEntries],matchedTerms:h,relations:p,relationCount:f.length,parallelConnectedSides:v,parallelOrchestrationSides:y,parallelSharedPathTerms:S,parallelSharedPathFrequency:E,orchestrationRootCount:(s.orchestrationRootCount??0)+(c.orchestrationRootCount??0),omittedRelations:Math.max(0,f.length-p.length),systemMapCommand:Wr(m,f,h)}})}}return r.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||hi(o.group,s.group,t)).slice(0,bL).map(o=>o.group)}function Hg(e){return new Set(e.roots.flatMap(t=>t.matches.filter(n=>n.sources.includes("path")).map(n=>n.term)))}function AL(e,t){return Vi([Ug(e),Ug(t)].filter(n=>n!==void 0))}function Ug(e){let t=new Set(e.keyAnchors.map(i=>i.symbol)),n=new Map;for(let i of e.relations)!t.has(i.fromSymbol)||!t.has(i.toSymbol)||n.set(i.fromSymbol,(n.get(i.fromSymbol)??0)+1);return[...e.keyAnchors].sort((i,r)=>+((n.get(r.symbol)??0)>0)-+((n.get(i.symbol)??0)>0)||zg(r)-zg(i)||r.identityMatchedTerms.length-i.identityMatchedTerms.length||r.symbolMatchedTerms.length-i.symbolMatchedTerms.length||(n.get(r.symbol)??0)-(n.get(i.symbol)??0)||Xe(i,r))[0]}function zg(e){return e.matchedTerms.length+e.identityMatchedTerms.length*2+(e.queryPathMatches?.length??0)*4}function NL(e,t,n,i,r,o){let s=ns(e);if(!s||s.links.length===0||n.length<2)return[];let a=new Map(s.observations.map(f=>[f.id,f])),l=new Map,c=new Map,u=[...n].sort((f,p)=>hi(f,p,r)).slice(0,pL),d=s.links.filter(f=>f.strength!=="candidate").sort((f,p)=>Gn(p.strength)-Gn(f.strength)||p.matchedKeyParts.length-f.matchedKeyParts.length||f.id.localeCompare(p.id));for(let f of u)for(let p of d){let g=a.get(p.from),h=a.get(p.to);if(!g||!h||!kL(f,g,i))continue;let S=_L(f,g,i);if(!S)continue;let v=l.get(h.id)??$L(e,t,h,i,o,hL);if(l.set(h.id,v),v.reachedSymbols.size===0)continue;let y=n.filter(D=>D.id!==f.id&&BL(D).some(T=>v.reachedSymbols.has(T))&&Rc(S,D)>=2).sort((D,T)=>Rc(S,T)-Rc(S,D)||hi(D,T,r)).slice(0,gL);if(y.length===0)continue;let E=[f.id,g.id,...y.map(D=>D.id).sort()].join("\0");if(c.has(E))continue;let w=new Set(y.flatMap(qr)),b=GL(Gr(h),w,v.relations);if(b.length===0)continue;let R=zL(g,h,p.joinRule,p.matchedKeyParts,p.strength),C=In([R,...v.relations,...f.relations,...y.flatMap(D=>D.relations)]),L=KL([R,...b],C,f,y),I=Vi([S,...y.flatMap(D=>D.roots)]).sort(Xe),x=Vi([S,...y.flatMap(D=>D.keyAnchors)]).slice(0,yL),P=[...new Set([...S.matchedTerms,...y.flatMap(D=>D.matchedTerms)])].sort(),_=OL(e,t,S,i,o);I.length===0||x.length<2||c.set(E,{id:`cross-boundary-set:${Kr(S)}:${c.size+1}`,kind:"cross-boundary-flow",roots:I,keyAnchors:x,candidateOwnerCount:x.length,omittedCandidateOwners:[],ownerRecoveryCommands:[],upstreamEntries:_,matchedTerms:P,relations:L,relationCount:C.length,omittedRelations:Math.max(0,C.length-L.length),systemMapCommand:Wr(x,C,P)})}let m=new Map;for(let[f,p]of c){let g=f.slice(0,f.indexOf("\0")),h=m.get(g);(!h||hi(p,h,r)<0)&&m.set(g,p)}return[...m.values()]}function kL(e,t,n){let i=new Set(qr(e));return t.owner.symbol&&i.has(t.owner.symbol)?!0:[...i].map(r=>n.get(r)).some(r=>r?.relativePath===t.source.file&&r.startLine<=t.source.startLine&&r.endLine>=t.source.endLine)}function _L(e,t,n){let i=Vi([...e.roots,...e.keyAnchors]);if(t.owner.symbol){let r=i.find(o=>o.symbol===t.owner.symbol);if(r)return r}return i.find(r=>{let o=n.get(r.symbol);return o?.relativePath===t.source.file&&o.startLine<=t.source.startLine&&o.endLine>=t.source.endLine})??null}function qr(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 BL(e){return[...new Set([...e.roots,...e.keyAnchors].map(t=>t.symbol))]}function Rc(e,t){let n=ct(e.leaf),i=[...t.roots,...t.keyAnchors].map(o=>ct(o.leaf)),r=0;for(let o of i){let s=0;for(let a of n)o.has(a)&&(s+=1);r=Math.max(r,s)}return r}function OL(e,t,n,i,r){let o=i.get(n.symbol);if(!o?.isFunctionLike)return[];let s=t.callerFileMap([o],{semantic:r,sourceFallback:!0}).get(o.symbolId);if(!s)return[];let a=ct(n.leaf);return[...s].filter(l=>l!==n.file&&V(l)!=="test").flatMap(l=>{let c=ee(e,l);return(c?.callSites??[]).filter(u=>rn(u.calleeLeaf)===rn(n.leaf)).flatMap(u=>{let d=(c?.callables??[]).filter(f=>f.startLine<=u.line&&f.endLine>=u.line).sort((f,p)=>f.endLine-f.startLine-(p.endLine-p.startLine)||f.startLine-p.startLine)[0];if(!d)return[];let m=[...ct(d.name)].filter(f=>a.has(f)).length;return m>=2?[{name:d.name,file:l,line:d.startLine,endLine:d.endLine,callsiteLine:u.line,overlap:m}]:[]})}).sort((l,c)=>c.overlap-l.overlap||l.file.localeCompare(c.file)||l.line-c.line).slice(0,1).map(({name:l,file:c,line:u,endLine:d,callsiteLine:m})=>({name:l,file:c,line:u,endLine:d,callsiteLine:m}))}function $L(e,t,n,i,r,o){let s=jL(e,n,i),a=s.map(({definition:m,evidence:f,line:p})=>({kind:"call",fromSymbol:Gr(n),fromLabel:Vs(n),fromFile:n.source.file,toSymbol:m.symbol,toLabel:k(m.symbol),toFile:m.relativePath,depth:1,strength:f==="scip-occurrence-callsite"?"exact":"derived",evidence:f,callsiteLine:p})),l=HL(e,n);a.push(...l.relations);let c=Xg([...s.map(m=>m.definition),...l.definitions]),u=c,d=new Set(u.map(m=>m.symbol));for(let m=2;m<=o+1&&u.length>0;m+=1){let f=t.calleeMap(u,{additive:!1,semantic:r}),p=new Map;for(let g of u){let h=Ws(e,g,f.get(g.symbolId)??[],i,m);a.push(...h);for(let S of h){let v=i.get(S.toSymbol);v?.isFunctionLike&&!d.has(v.symbol)&&p.set(v.symbol,v)}}u=[...p.values()];for(let g of u)d.add(g.symbol)}return{entryDefinitions:c,relations:In(a),reachedSymbols:new Set([...c.map(m=>m.symbol),...a.flatMap(m=>[m.fromSymbol,m.toSymbol])])}}function jL(e,t,n){let i=t.owner.symbol?n.get(t.owner.symbol):void 0;if(i?.isFunctionLike&&!Le(i.symbol))return[{definition:i,evidence:"scip-occurrence-callsite",line:t.source.startLine}];let r=ie(e,t.source.file),o=gt(e,t.source.file,0,Math.max(0,r.length-1),[t.source.startLine]),s=xn(e,t.source.file,o.startLine,o.endLine).targets.map(u=>({definition:u.definition,evidence:"scip-occurrence-callsite",line:u.sourceLine})),a=ee(e,t.source.file),l=Xt(e),c=(a?.callSites??[]).flatMap(u=>{if(u.line<o.startLine||u.line>o.endLine)return[];let d=Yt(t.source.file,l.get(u.calleeLeaf)??[]),m=Bn(e,t.source.file,d,u.memberAccess,u.calleeQualifier),f=m?n.get(m.symbol):void 0;return f?.isFunctionLike?[{definition:f,evidence:"ast-callsite",line:u.line}]:[]});return UL([...s,...c])}function HL(e,t){let n=ie(e,t.source.file),i=gt(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine]),r=Un(e,t.source.file,{ranges:[i],excludeIndexedTargets:!1}).targets,o=[],s=[];for(let a of r){let l=`source-construct:${a.targetFile}:${a.targetStartLine}:${a.targetEndLine}:${a.calleeLeaf}`;s.push({kind:"call",fromSymbol:Gr(t),fromLabel:Vs(t),fromFile:t.source.file,toSymbol:l,toLabel:a.calleeLeaf,toFile:a.targetFile,depth:1,strength:"derived",evidence:"ast-member-import-candidate",callsiteLine:a.line});let c=xn(e,a.targetFile,a.targetStartLine,a.targetEndLine).targets;for(let u of c)o.push(u.definition),s.push({kind:"call",fromSymbol:l,fromLabel:a.calleeLeaf,fromFile:a.targetFile,toSymbol:u.definition.symbol,toLabel:k(u.definition.symbol),toFile:u.definition.relativePath,depth:2,strength:"exact",evidence:"scip-occurrence-callsite",callsiteLine:u.sourceLine})}return{definitions:Xg(o),relations:In(s)}}function UL(e){return[...new Map(e.map(t=>[t.definition.symbol,t])).values()]}function Xg(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function Gr(e){return e.owner.symbol??e.id}function Vs(e){return e.owner.name??`${e.source.file}:${e.source.startLine+1}`}function zL(e,t,n,i,r){return{kind:"runtime-boundary",fromSymbol:Gr(e),fromLabel:Vs(e),fromFile:e.source.file,toSymbol:Gr(t),toLabel:Vs(t),toFile:t.source.file,depth:1,strength:r,evidence:`runtime-boundary:${n}`,callsiteLine:e.source.startLine,runtimeBoundaryKey:i.map(o=>`${o.name}=${o.value}`).join(" ")}}function GL(e,t,n){let i=new Map;for(let s of n){let a=i.get(s.fromSymbol)??[];a.push(s),i.set(s.fromSymbol,a)}let r=[{symbol:e,path:[]}],o=new Set([e]);for(;r.length>0;){let s=r.shift();if(s.path.length>0&&t.has(s.symbol))return s.path;for(let a of(i.get(s.symbol)??[]).sort(on))o.has(a.toSymbol)||(o.add(a.toSymbol),r.push({symbol:a.toSymbol,path:[...s.path,a]}))}return[]}function KL(e,t,n,i){let r=In(e),o=new Set([n,...i].flatMap(s=>[...qr(s),...s.keyAnchors.map(a=>a.symbol)]));for(let s of t){if(r.length>=yi)break;!o.has(s.fromSymbol)&&!o.has(s.toSymbol)||r.some(a=>a.fromSymbol===s.fromSymbol&&a.toSymbol===s.toSymbol)||r.push(s)}return r.slice(0,yi)}function qL(e,t,n,i,r,o,s,a){let l=n.filter(u=>!u.root.symbol.startsWith(Lc)).map(u=>({root:u.root,relations:u.relations.filter(d=>d.depth===1&&d.fromSymbol===u.root.symbol)}));return WL(l).flatMap((u,d)=>{let m=new Set(u.map(A=>A.root.symbol)),f=new Map;for(let A of u)for(let W of new Set(A.relations.map(le=>le.toSymbol)))f.set(W,(f.get(W)??0)+1);let p=[...f].filter(([,A])=>A>=2).sort(([A,W],[le,q])=>q-W||VL(A,le,i,r,s)).map(([A])=>s.get(A)).filter(A=>A?.isFunctionLike===!0).slice(0,mL);if(p.length===0)return[];let g=t.callerFileMap(p,{semantic:a,sourceFallback:!0}),h=new Set;for(let A of p){h.add(A.relativePath);for(let W of g.get(A.symbolId)??[])h.add(W)}let S=o.filter(A=>A.isFunctionLike&&h.has(A.relativePath)).sort(JL).slice(0,fL),v=t.calleeMap(S,{additive:!1,semantic:a}),y=new Set(p.map(A=>A.symbol)),E=In(S.flatMap(A=>Ws(e,A,v.get(A.symbolId)??[],s,1,y).filter(W=>y.has(W.toSymbol)))),w=new Map;for(let A of E){let W=w.get(A.fromSymbol)??new Set;W.add(A.toSymbol),w.set(A.fromSymbol,W)}let b=new Set([...w].filter(([A,W])=>W.size>=2||m.has(A)).map(([A])=>A)),R=E.filter(A=>b.has(A.fromSymbol));if(b.size<2||R.length===0)return[];let L=[...new Set(R.map(A=>A.toSymbol))].map(A=>Js(A,i,r,s)).filter(A=>A!==null).sort(Xe),I=[...b].map(A=>Js(A,i,r,s)).filter(A=>A!==null),x=YL(I,R),P=x.slice(0,xc),_=x.slice(xc);if(L.length===0||P.length===0)return[];let D=[...new Set([...L.flatMap(A=>A.matchedTerms),...u.flatMap(A=>A.root.matchedTerms)])].sort(),T=XL(R,P);return[{id:`effect-owner-set:${d+1}:${Kr(L[0])}`,kind:"shared-callee-owners",roots:L,keyAnchors:P,candidateOwnerCount:x.length,omittedCandidateOwners:_,ownerRecoveryCommands:hD(_,xc),upstreamEntries:[],matchedTerms:D,relations:T,relationCount:R.length,omittedRelations:Math.max(0,R.length-T.length),systemMapCommand:Wr(P,R,D)}]})}function WL(e){let t=e.map((s,a)=>a),n=s=>{for(;t[s]!==s;)t[s]=t[t[s]],s=t[s];return s},i=(s,a)=>{let l=n(s),c=n(a);l!==c&&(t[c]=l)},r=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 l=0;for(let c of r[s]??[])if((r[a]??new Set).has(c)&&(l+=1),l>=2)break;l>=2&&i(s,a)}let o=new Map;for(let s=0;s<e.length;s+=1){let a=n(s),l=o.get(a)??[];l.push(e[s]),o.set(a,l)}return[...o.values()].filter(s=>s.length>=2)}function VL(e,t,n,i,r){let o=Js(e,n,i,r),s=Js(t,n,i,r);return o?s?Xe(o,s):-1:s?1:e.localeCompare(t)}function JL(e,t){return zt(V(e.relativePath))-zt(V(t.relativePath))||e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine}function Js(e,t,n,i){let r=t.get(e);if(r)return qs(r,n);let o=i.get(e);return o?Zg(o):null}function YL(e,t){let n=new Map;for(let r of t){let o=n.get(r.toSymbol)??new Set;o.add(r.fromSymbol),n.set(r.toSymbol,o)}let i=new Map;for(let r of t){let o=n.get(r.toSymbol)?.size??1;i.set(r.fromSymbol,(i.get(r.fromSymbol)??0)+o*o)}return[...e].sort((r,o)=>Number(r.leaf.startsWith("#"))-Number(o.leaf.startsWith("#"))||o.identityMatchedTerms.length-r.identityMatchedTerms.length||(i.get(o.symbol)??0)-(i.get(r.symbol)??0)||Xe(r,o))}function XL(e,t){let n=new Map(t.map((s,a)=>[s.symbol,a])),i=t.map(s=>e.filter(a=>a.fromSymbol===s.symbol).sort(on)),r=[],o=0;for(;r.length<yi&&i.some(s=>o<s.length);){for(let s of i){let a=s[o];if(a&&r.push(a),r.length>=yi)break}o+=1}return r.sort((s,a)=>n.get(s.fromSymbol)-n.get(a.fromSymbol)||on(s,a))}function ZL(e,t,n,i){let r=new Map(t.map((a,l)=>[a.symbol,l])),o=new Map;for(let a of e)o.set(a.fromSymbol,(o.get(a.fromSymbol)??0)+1);return[...e].sort((a,l)=>{let c=u=>{let d=0;return r.has(u.fromSymbol)&&(d+=100),n.has(u.toSymbol)&&(d+=60),d+=Math.min(40,(o.get(u.toSymbol)??0)*8),(i.get(u.toSymbol)?.matchedTerms.length??0)>0&&(d+=25),u.fromFile!==u.toFile&&(d+=15),u.strength==="exact"&&(d+=5),d};return c(l)-c(a)||on(a,l)}).slice(0,yi).sort((a,l)=>(r.get(a.fromSymbol)??gi)-(r.get(l.fromSymbol)??gi)||a.depth-l.depth||(a.callsiteLine??Number.MAX_SAFE_INTEGER)-(l.callsiteLine??Number.MAX_SAFE_INTEGER)||on(a,l))}function Zg(e){return{symbol:e.symbol,label:zn(e),leaf:e.leaf,file:e.relativePath,line:e.startLine,endLine:e.endLine,kind:e.isFunctionLike?"callable":e.isTypeLike?"type":"symbol",fileKind:V(e.relativePath),matches:[],focusLocations:[],matchedTerms:[],symbolMatchedTerms:[],symbolPhraseLength:0,identityMatchedTerms:[],rarity:0,symbolRarity:0}}function QL(e,t,n){let i=[...e].sort(Xe),r=[],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,l=u=>{if(!(!u||r.some(d=>d.symbol===u.symbol))){r.push(u);for(let d of u.matchedTerms)s.add(d);for(let d of u.symbolMatchedTerms)a.add(d)}},c=i.filter(u=>u.symbolPhraseLength>=2&&(o.get(u.symbol)??0)>=2);for(;r.length<Math.min(2,gi);){let u=c.filter(d=>!r.some(m=>m.symbol===d.symbol)).sort((d,m)=>m.symbolMatchedTerms.filter(f=>!a.has(f)).length-d.symbolMatchedTerms.filter(f=>!a.has(f)).length||m.symbolPhraseLength-d.symbolPhraseLength||(o.get(m.symbol)??0)-(o.get(d.symbol)??0)||Ec(d,m))[0];if(!u||r.length>0&&u.symbolMatchedTerms.every(d=>a.has(d)))break;l(u)}if(l(i[0]),r.length>=2){let u=eD(r[0].symbol,r[1].symbol,t,n);for(let d of u?.slice(1,-1)??[]){if(r.length>=gi)break;l(n.get(d))}if(r.length<gi){let d=new Set(r.map(p=>p.symbol)),m=new Set(t.filter(p=>p.depth===1&&d.has(p.fromSymbol)&&d.has(p.toSymbol)).map(p=>p.fromSymbol)),f=t.filter(p=>p.depth===1&&m.has(p.fromSymbol)&&!d.has(p.toSymbol)).map(p=>({relation:p,candidate:n.get(p.toSymbol)})).filter(p=>p.candidate!==void 0&&p.candidate.symbolPhraseLength>=2&&p.candidate.symbolMatchedTerms.length>=2).sort((p,g)=>(o.get(p.relation.fromSymbol)??0)-(o.get(g.relation.fromSymbol)??0)||Ec(p.candidate,g.candidate))[0]?.candidate;l(f)}}else for(;r.length<Math.min(3,gi);){let u=i.filter(d=>!r.some(m=>m.symbol===d.symbol)).sort((d,m)=>m.matchedTerms.filter(f=>!s.has(f)).length-d.matchedTerms.filter(f=>!s.has(f)).length||Xe(d,m))[0];if(!u||u.matchedTerms.every(d=>s.has(d)))break;l(u)}for(;r.length>=2&&r.length<gi;){let u=new Set(r.map(m=>m.symbol)),d=[...n.values()].filter(m=>!u.has(m.symbol)&&(o.get(m.symbol)??0)>0&&t.some(f=>u.has(f.fromSymbol)&&f.toSymbol===m.symbol)).sort((m,f)=>f.identityMatchedTerms.length-m.identityMatchedTerms.length||f.symbolMatchedTerms.length-m.symbolMatchedTerms.length||f.matchedTerms.length-m.matchedTerms.length||(o.get(f.symbol)??0)-(o.get(m.symbol)??0)||Xe(m,f))[0];if(!d)break;l(d)}if(r.length<2){let u=r[0],d=u?i.filter(m=>m.symbol!==u.symbol).map(m=>({root:m,path:tD(m.symbol,u.symbol,t)})).filter(m=>m.path!==null).sort((m,f)=>+(f.root.file!==u.file)-+(m.root.file!==u.file)||m.path.length-f.path.length||Xe(m.root,f.root))[0]?.root:void 0;l(d)}return r}function eD(e,t,n,i){let r=new Map;for(let a of n){let l=r.get(a.fromSymbol)??new Set;l.add(a.toSymbol),r.set(a.fromSymbol,l);let c=r.get(a.toSymbol)??new Set;c.add(a.fromSymbol),r.set(a.toSymbol,c)}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:l}=o.shift(),c=a.at(-1);if(c===t)return a;for(let u of r.get(c)??[]){let d=i.get(u),m=u===t?1:!d||d.matchedTerms.length===0?9:d.symbolPhraseLength>=2?1:d.identityMatchedTerms.length>=2?2:4,f=l+m;f>=(s.get(u)??Number.POSITIVE_INFINITY)||(s.set(u,f),o.push({path:[...a,u],cost:f}))}}return null}function tD(e,t,n){let i=new Map;for(let s of n){let a=i.get(s.fromSymbol)??[];a.push(s.toSymbol),i.set(s.fromSymbol,a)}let r=[[e]],o=new Set([e]);for(;r.length>0;){let s=r.shift(),a=s.at(-1);if(a===t)return s;for(let l of i.get(a)??[])o.has(l)||(o.add(l),r.push([...s,l]))}return null}function Xe(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||Ji(e.kind)-Ji(t.kind)||zt(e.fileKind)-zt(t.fileKind)||e.file.localeCompare(t.file)||e.line-t.line}function Ec(e,t){return t.symbolPhraseLength-e.symbolPhraseLength||t.symbolMatchedTerms.length-e.symbolMatchedTerms.length||Ji(e.kind)-Ji(t.kind)||t.symbolRarity-e.symbolRarity||Xe(e,t)}function nD(e,t){return t.flatMap(n=>{let i=e.filter(s=>s.matchedTerms.includes(n)).sort((s,a)=>rD(s,a,n)),r=[],o=new Set;for(let s of i)if(!o.has(s.file)&&(r.push(s),o.add(s.file),r.length>=_g))return r;for(let s of i)if(!r.some(a=>a.symbol===s.symbol)&&(r.push(s),r.length>=_g))break;return r})}function iD(e,t,n){let i=new Set(t),r=new Map;for(let o of e){if(o.kind!=="callable")continue;let s=o.file.slice(o.file.lastIndexOf("/")+1).replace(/\.[^.]+$/u,"");if(![...ct(s)].some(l=>i.has(l)))continue;let a=r.get(o.file)??[];a.push(o),r.set(o.file,a)}return[...r.entries()].map(([o,s])=>{let a=o.slice(o.lastIndexOf("/")+1).replace(/\.[^.]+$/u,""),l=[...ct(a)].filter(c=>i.has(c));return{file:o,fileCandidates:s,sharedFrequency:Math.min(...l.map(c=>n.get(c)??Number.MAX_SAFE_INTEGER))}}).sort((o,s)=>zt(o.fileCandidates[0].fileKind)-zt(s.fileCandidates[0].fileKind)||o.sharedFrequency-s.sharedFrequency||o.file.localeCompare(s.file)).flatMap(({fileCandidates:o})=>[...o].sort(Xe).slice(0,xL)).slice(0,CL)}function rD(e,t,n){return Gg(e,n)-Gg(t,n)||zt(e.fileKind)-zt(t.fileKind)||t.symbolPhraseLength-e.symbolPhraseLength||Ji(e.kind)-Ji(t.kind)||Xe(e,t)}function Gg(e,t){let n=e.matches.find(i=>i.term===t)?.sources??[];return Math.min(...n.map(wc),Number.MAX_SAFE_INTEGER)}function Vi(e){return[...new Map(e.map(t=>[t.symbol,t])).values()]}function hi(e,t,n){let i=new Set(e.roots.flatMap(o=>o.symbolMatchedTerms)),r=new Set(t.roots.flatMap(o=>o.symbolMatchedTerms));return(t.queryPathMatches?.length??0)-(e.queryPathMatches?.length??0)||Vg(e.kind)-Vg(t.kind)||qg(e)-qg(t)||Wg(e)-Wg(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)||Kg(t,n)-Kg(e,n)||t.matchedTerms.length-e.matchedTerms.length||Math.max(...t.roots.map(o=>o.symbolPhraseLength))-Math.max(...e.roots.map(o=>o.symbolPhraseLength))||r.size-i.size||Xe(e.roots[0],t.roots[0])||t.roots.length-e.roots.length||e.relationCount-t.relationCount||e.id.localeCompare(t.id)}function Kg(e,t){return e.matchedTerms.reduce((n,i)=>n+1/Math.max(1,t.get(i)??1),0)}function oD(e){return[...new Set(e.roots.flatMap(t=>t.queryPathMatches??[]))].sort()}function qg(e){let t=e.keyAnchors.length>0?e.keyAnchors:e.roots;return Math.max(...t.map(n=>zt(n.fileKind)))}function Wg(e){return e.kind==="parallel-paths"?2-(e.parallelConnectedSides??0):e.kind!=="connected-flow"||e.relationCount>0?0:1}function sD(e,t,n){let i=e.slice(0,t);if(t<2||i.some(o=>o.kind==="shared-callee-owners"))return i;let r=e.filter(o=>o.kind==="shared-callee-owners");for(let o of i){if(o.kind==="shared-callee-owners"||o.kind==="parallel-paths")continue;let s=new Set(qr(o)),a=r.map(c=>({group:c,overlap:aD(c,s)})).filter(({overlap:c})=>c>0).sort(({group:c,overlap:u},{group:d,overlap:m})=>m-u||hi(c,d,n))[0]?.group;if(!a)continue;let l=i.length-1;for(;l>=0&&i[l]===o;)l-=1;return l<0?i:(i[l]=a,[...i].sort((c,u)=>hi(c,u,n)))}return i}function aD(e,t){return qr(e).filter(n=>t.has(n)).length}function Vg(e){switch(e){case"cross-boundary-flow":return 0;case"parallel-paths":case"connected-flow":return 1;case"shared-callee-owners":return 2}}function on(e,t){return e.depth-t.depth||Gn(t.strength)-Gn(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 lD(e,t){return Gn(Ic(t.source))-Gn(Ic(e.source))||(e.callsiteLine??Number.MAX_SAFE_INTEGER)-(t.callsiteLine??Number.MAX_SAFE_INTEGER)||e.symbol.localeCompare(t.symbol)}function In(e){let t=new Map;for(let n of e){let i=`${n.fromSymbol}\0${n.toSymbol}`,r=t.get(i);(!r||on(n,r)<0)&&t.set(i,n)}return[...t.values()]}function cD(e){let t=e.match(/[\p{L}\d_.-]+(?:\/[\p{L}\d_.-]+)+/gu)??[];return[...new Set(t.map(n=>n.replace(/[.;:!?]+$/gu,"").toLocaleLowerCase()))]}function uD(e,t){let n=e.replace(/\\/gu,"/").toLocaleLowerCase();return t.filter(i=>{let r=n.indexOf(i);if(r<0)return!1;let o=r===0?"/":n[r-1],s=n[r+i.length];return o==="/"&&(s===void 0||s==="/")})}function dD(e,t){let n=jr(e).map(js),i=0;for(let r=0;r<n.length;r+=1)for(let o=0;o<t.length;o+=1){let s=0;for(;r+s<n.length&&o+s<t.length&&n[r+s]===t[o+s];)s+=1;i=Math.max(i,s)}return i}function Jg(e){if(e.length===0)return[];let t=e.split(`
|
|
67
|
+
`);return e.endsWith(`
|
|
68
|
+
`)&&t.pop(),t}function mD(e,t){return wc(e)-wc(t)}function wc(e){switch(e){case"symbol":return 0;case"path":return 1;case"documentation":return 2;case"source":return 3}}function Ji(e){return e==="callable"?0:e==="type"?1:2}function zt(e){switch(e){case"entry":case"source":case"worker":return 0;case"barrel":return 1;case"test":return 2}}function Ic(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function Gn(e){return e==="exact"?2:1}function Qg(e,t){return e.file.localeCompare(t.file)||e.line-t.line}function Kr(e){return`${e.file}:${e.line+1}`}function Wr(e,t=[],n=[]){let i=e.map(s=>`--symbol ${Ys(`${s.file}:${s.line+1}-${s.endLine+1}`)}`),r=new Set(e.map(s=>s.symbol)),o=e.flatMap(s=>(s.sourceCharacters??0)>Cc?fD(s,t,n,r).map(a=>`--focus-at ${Ys(`${a.file}:${a.line+1}`)}`):[]);return`codebaseiq system-map ${[...i,...o,"--relation call","--relation runtime-boundary"].join(" ")}`}function fD(e,t,n,i){let r=new Set(n),o=t.filter(c=>c.fromSymbol===e.symbol&&c.callsiteLine!==null&&c.callsiteLine>=e.line&&c.callsiteLine<=e.endLine).map(c=>({file:e.file,line:c.callsiteLine,connectsAnchor:i.has(c.toSymbol),overlap:new Set(jr(pD(c.toLabel)).flatMap(ac).filter(u=>r.has(u))).size,strength:c.strength})).filter(c=>c.overlap>0).sort((c,u)=>Number(u.connectsAnchor)-Number(c.connectsAnchor)||u.overlap-c.overlap||c.line-u.line||Gn(u.strength)-Gn(c.strength)),s=o.filter(c=>c.connectsAnchor),a=[...s.length>0?s:o,...s.length>0?[]:e.focusLocations.map(c=>({...c,connectsAnchor:!1,overlap:0,strength:"derived"}))],l=[];for(let c of a)if(!l.some(u=>u.file===c.file&&u.line===c.line)&&(l.push({file:c.file,line:c.line}),l.length>=3))break;return l}function pD(e){return e.slice(Math.max(e.lastIndexOf(":"),e.lastIndexOf("."))+1)}function gD(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 l=`${a.file}\0${a.line}`,c=n.get(l)??{...a,matchedTerms:new Set};c.matchedTerms.add(o),n.set(l,c)}let i=[...n.values()].sort((o,s)=>s.matchedTerms.size-o.matchedTerms.size||[...s.matchedTerms].reduce((a,l)=>a+1/Math.max(1,t.get(l)??1),0)-[...o.matchedTerms].reduce((a,l)=>a+1/Math.max(1,t.get(l)??1),0)||Qg(o,s)),r=[];for(let o of i)if(!r.some(s=>s.file===o.file&&Math.abs(s.line-o.line)<8)&&(r.push(o),r.length>=3))break;return r.map(o=>({file:o.file,line:o.line,matchedTerms:[...o.matchedTerms].sort()}))}function hD(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(Wr(e.slice(i,i+t)));return n}function Ys(e){return`'${e.replaceAll("'",`'"'"'`)}'`}import{createHash as Rh}from"crypto";function Xs(e,t){return de(e)-de(t)||e.relativePath.localeCompare(t.relativePath)}function Ae(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function Yi(e){let t=new Set,n=[];for(let i of e){let r=`${i.symbol}|${i.file}`;t.has(r)||(t.add(r),n.push(i))}return n}function Vr(e,t,n={}){let i=fe(e,t);if(!i)return null;let r=n.semantic!==!1,o=El(e,i,{semantic:r,semanticEvidence:pe}),s=o.rows.filter(d=>ke(d.symbol)).slice(0,50),a=ai(e,i,{limit:50,additive:!0,callableOnly:!0,semantic:r,semanticEvidence:pe}),l=Yi(a.rows),c=s.map(d=>({symbol:d.symbol,shortName:k(d.symbol),file:d.file,relationship:d.source!=="caller-map-inversion"?"reference-candidate":d.callEvidence==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:d.source==="caller-map-inversion"&&d.callEvidence!=="scip-chunk"?"exact":"candidate",evidenceSource:d.callEvidence??d.source})),u=l.map(d=>({symbol:d.symbol,shortName:k(d.symbol),file:d.file,relationship:d.source==="scip-chunk"?"chunk-candidate":"resolved-call",evidenceStrength:d.source==="scip-chunk"?"candidate":"exact",evidenceSource:d.source}));return{symbol:i.symbol,shortName:k(i.symbol),callers:c.map(({symbol:d,shortName:m,file:f})=>({symbol:d,shortName:m,file:f})),callees:u.map(({symbol:d,shortName:m,file:f})=>({symbol:d,shortName:m,file:f})),callerEvidence:c,calleeEvidence:u,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",...o.semanticIncomplete?["compiler-resolved incoming evidence was incomplete; known callers are retained"]:[],...o.semanticUnavailable?["compiler-resolved incoming evidence was unavailable; known callers are retained"]:[],...a.semanticIncomplete?["compiler-resolved outgoing evidence was incomplete; known callees are retained"]:[],...a.semanticUnavailable?["compiler-resolved outgoing evidence was unavailable; known callees are retained"]:[]],semanticEvidence:{enabled:r,incoming:eh(r,o),outgoing:eh(r,a)}}}}function eh(e,t){return e?t.semanticIncomplete&&t.semanticUnavailable?"incomplete-and-unavailable":t.semanticIncomplete?"incomplete":t.semanticUnavailable?"unavailable":"complete":"disabled"}function Xi(e,t,n){if(n.length===0)return[];let i=new Set(n),r=Be(e),o=new Set;if(t==="forward")for(let s of i)for(let a of r.get(s)??[])i.has(a)||o.add(a);else for(let[s,a]of r)if(!i.has(s))for(let l of i)a.has(l)&&o.add(s);return[...o].sort()}function Jr(e,t){let n=lt(e,t);return n?Xi(e,"forward",[n]).filter(r=>!e.isIgnored(r)).map(r=>({relativePath:r,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):[]}function Yr(e,t){let n=lt(e,t);return n?Xi(e,"reverse",[n]).filter(r=>!e.isIgnored(r)).map(r=>({relativePath:r,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):[]}function Dc(e,t,n={}){let i=Zs(e,t,n);return{definitions:i.definitions,referencedBy:i.referencedBy}}function Zs(e,t,n={}){let i=fe(e,t);if(!i)return{definitions:[],referencedBy:[],referenceEvidence:[],claimSupport:null};let r=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",i.symbolId),o=Bi(r?.documentation??null),s=e.isIgnored(i.relativePath)?[]:[{relativePath:i.relativePath,startLine:i.startLine,endLine:i.endLine,signature:xD(o,r?.display_name??null,i.symbol),source:CD(e,i.relativePath,i.startLine,i.endLine)}],a=n.referenceContext??2,l=Am(e,i,{semantic:n.semantic,semanticEvidence:pe}).map(u=>{let d=Ff(e,u.file,u.line,a,re(i.symbol));return{relativePath:u.file,line:u.line,enclosingSymbol:u.enclosingSymbol,enclosingShort:u.enclosingSymbol?k(u.enclosingSymbol):"(top-level)",provenance:u.provenance,sourceStartLine:d?.startLine??null,sourceEndLine:d?.endLine??null,source:d?.source??null,sourceKind:d?.kind??"unavailable"}}),c=l.map(yD);return{definitions:s,referencedBy:c,referenceEvidence:l.map(u=>({relativePath:u.relativePath,line:u.line,provenance:u.provenance,sourceKind:u.sourceKind})),claimSupport:bD(l)}}function yD(e){return{relativePath:e.relativePath,line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort,sourceStartLine:e.sourceStartLine,sourceEndLine:e.sourceEndLine,source:e.source}}function bD(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."],i=e.filter(o=>o.sourceKind!=="complete-call-expression"&&o.sourceKind!=="non-call-reference"),r="direct, statically visible call expressions among the resolved reference sites";return{referenceAbsence:{status:"eligible",scope:t,limitations:n},callsitePredicates:i.length===0?{status:"eligible",scope:r,limitations:n}:{status:"ineligible",scope:r,reason:`${i.length} reference site(s) lack one unambiguous complete call expression.`,followup:SD(i)}}}function SD(e){let t=[...new Set(e.map(n=>`${n.relativePath}:${n.line+1}`))];return t.length===0||t.length>24?null:`codebaseiq inspect ${t.map(n=>`--at ${vD(n)}`).join(" ")} --view behavior`}function vD(e){return`'${e.replaceAll("'","'\\''")}'`}function CD(e,t,n,i){let r=se(e,t);if(!r)return null;let s=r.split(`
|
|
69
|
+
`).slice(n,i+1).join(`
|
|
70
|
+
`).trimEnd();return s.length>0?s:null}function xD(e,t,n){let i=_i(e);if(i&&!RD(i))return i;let r=(t??"").trim();return r?ke(n)&&!r.endsWith("()")?`${r}()`:r:k(n)}function RD(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function Pc(e,t,n={}){let i=ih(e,t,n);if(i.kind!=="matched")return i;let{referenceEvidence:r,claimSupport:o,...s}=i;return s}function ih(e,t,n={}){let i=rt(e,t);if(!i.match)return{kind:"missing",query:t};if(i.total>1)return{kind:"ambiguous",query:t,total:i.total,candidates:[{symbol:i.match.symbol,shortName:k(i.match.symbol),relativePath:i.match.relativePath,startLine:i.match.startLine},...i.candidates]};let r=i.match,o=wD(n.parts),s=o.includes("definition")||o.includes("references")?Zs(e,r.symbol,{semantic:n.semantic,referenceContext:n.referenceContext}):{definitions:[],referencedBy:[],referenceEvidence:[],claimSupport:null},a=o.includes("callers")||o.includes("callees")?Vr(e,r.symbol,{semantic:n.semantic}):null,l=n.relatedSourceLines??80;return{kind:"matched",query:t,symbol:r.symbol,shortName:k(r.symbol),file:r.relativePath,parts:o,definition:o.includes("definition")?$l(e,r.symbol):null,referenceWindows:o.includes("references")?ED(e,s.referencedBy):[],callers:o.includes("callers")?nh(e,a?.callers??[],l):[],callees:o.includes("callees")?nh(e,a?.callees??[],l):[],dependencies:o.includes("dependencies")?Jr(e,r.relativePath):[],consumers:o.includes("consumers")?Yr(e,r.relativePath):[],referenceEvidence:s.referenceEvidence,claimSupport:s.claimSupport}}function ED(e,t){let n=t.filter(r=>r.sourceStartLine!==null&&r.sourceEndLine!==null&&r.source!==null).sort((r,o)=>r.relativePath.localeCompare(o.relativePath)||r.sourceStartLine-o.sourceStartLine||r.line-o.line),i=[];for(let r of n){let o=i[i.length-1];if(o&&o.relativePath===r.relativePath&&r.sourceStartLine<=o.endLine+1){o.endLine=Math.max(o.endLine,r.sourceEndLine),o.references.push(th(r)),o.source=ie(e,o.relativePath).slice(o.startLine,o.endLine+1).join(`
|
|
71
|
+
`);continue}i.push({relativePath:r.relativePath,startLine:r.sourceStartLine,endLine:r.sourceEndLine,source:r.source,references:[th(r)]})}return i}function th(e){return{line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort}}function wD(e){let t=e&&e.length>0?e:["definition","references"];return[...new Set(t)]}function nh(e,t,n){let i=[],r=new Set;for(let o of t){if(r.has(o.symbol))continue;r.add(o.symbol);let s=(o.file?J(e,o.file).find(l=>l.symbol===o.symbol):void 0)??rt(e,o.symbol).match;if(!s)continue;let a=Mf(e,s.relativePath,s.startLine,s.endLine,n);a&&i.push({...a,symbol:o.symbol,shortName:o.shortName,omittedLines:Math.max(0,s.endLine-a.endLine)})}return i}var lh=6;function rh(e,t,n){return`${e}\0${t}\0${n??t}`}function ch(e,t,n,i={}){let r=i.limit??lh;if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`next-anchor limit must be a positive safe integer; received ${r}`);let o=i.sourceAllowed??(()=>!0),s=new Map(t.nodes.map(C=>[C.id,C])),a=new Set(n.steps.map(C=>C.nodeId)),l=new Set(n.steps.flatMap(C=>{let L=Mc(s.get(C.nodeId));return L?[L]:[]})),c=new Set;for(let C of n.steps)for(let L of C.behavior?.supportingDeclarations??[])l.add(L.symbol),c.add(rh(L.file,L.line,L.endLine));let u=C=>C.symbol!==null&&l.has(C.symbol)||c.has(rh(C.file,C.line,C.endLine)),d=new Map(n.steps.flatMap(C=>{if(!C.location)return[];let L=Mc(s.get(C.nodeId));if(!L)return[];let I=J(e,C.location.file).find(x=>x.symbol===L);return I?[[C.id,I]]:[]})),m=new U(e).calleeMap([...d.values()],{additive:!1,semantic:!0}),f=[],p=new Set,g=new Set,h=0,S=0,v=0,y=0,E=0,w=0,b=0,R=0;for(let C of n.steps){if(!C.location||!C.behavior)continue;let L=t.edges.filter(N=>["call","runtime-boundary"].includes(N.kind)&&(N.fromNodeId===C.nodeId||N.toNodeId===C.nodeId)&&N.disposition!=="excluded"&&N.disposition!=="unsupported");for(let N of L){let K=N.toNodeId===C.nodeId,te=K?N.fromNodeId:N.toNodeId;if(a.has(te))continue;let me=s.get(te);if(!me?.location||!o(me.location.file))continue;let ge=N.kind==="call"?Nc(e,me):Ac(me);if(!ge||u(ge))continue;let ce=kc(N,me.location.file)??me.location,be=ie(e,ce.file)[ce.line]?.trim(),F=K?"upstream":"downstream",Z=N.kind==="runtime-boundary"?K?"runtime-producer":"runtime-consumer":K?"caller":"callee",X=["call"],Se=Tc(N.evidence),tt=Xr(me);f.push({anchor:{id:Kn(C.id,ce.line,me.id),status:Se,source:"graph-relation",direction:F,causalRole:Z,relationKind:N.kind,fromStepId:C.id,fromLabel:C.label,callsite:{file:ce.file,line:ce.line,endLine:ce.endLine??ce.line,text:be||`${me.label} \u2192 ${C.label}`,signals:X,calleeLeaf:tt},alternatives:[ge],alternativeCount:1,evidence:N.evidence}}),K&&(w+=1),N.kind==="runtime-boundary"&&(R+=1)}let I=t.edges.filter(N=>N.kind==="reference"&&N.fromNodeId===C.nodeId&&N.disposition!=="excluded"&&N.disposition!=="unsupported"&&!a.has(N.toNodeId));for(let N of I){let K=s.get(N.toNodeId);if(!K?.location||!o(K.location.file))continue;let te=Nc(e,K);if(!te||u(te))continue;let me=Xr(K),ge=kc(N,C.location.file)?.line,ce=C.behavior.lines.find(X=>(ge===void 0||ge>=X.line&&ge<=X.endLine)&&X.text.includes(me));if(!ce)continue;let be=dh(ce.signals),F=be==="result-callback",Z=Tc(N.evidence);f.push({anchor:{id:Kn(C.id,ce.line,K.id),status:Z,source:"graph-relation",direction:"downstream",causalRole:be,relationKind:"reference",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:ce.line,endLine:ce.endLine,text:ce.text,signals:ce.signals,calleeLeaf:me},alternatives:[te],alternativeCount:1,evidence:N.evidence}}),F&&(b+=1)}let x=xn(e,C.location.file,C.location.line,C.location.endLine??C.location.line),P=ie(e,C.location.file),_=Sn(e,C.location.file,C.location.line,C.location.endLine??C.location.line);for(let N of x.targets){if(!o(N.definition.relativePath))continue;let K=bi(C.location.file,N.sourceLine,N.calleeLeaf);if(p.has(K))continue;p.add(K);let te=Fc(_.get(N.sourceLine)),me={symbol:N.definition.symbol,label:N.definition.leaf,file:N.definition.relativePath,line:N.definition.startLine,endLine:N.definition.endLine};u(me)||f.push({anchor:{id:Kn(C.id,N.sourceLine,N.definition.symbol),status:"exact",source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:N.sourceLine,endLine:N.sourceLine,text:P[N.sourceLine]?.trim()||`${N.calleeLeaf}()`,signals:te,calleeLeaf:N.calleeLeaf},alternatives:[me],alternativeCount:1,evidence:[{method:"scip-occurrence-callsite",strength:"exact",identity:N.definition.symbol,location:{file:C.location.file,line:N.sourceLine}}]}})}let D=C.behavior.lines.filter(N=>N.signals.includes("call"));if(D.length===0)continue;h+=1;let T=(ee(e,C.location.file)?.callSites??[]).filter(N=>D.some(K=>N.line>=K.line&&N.line<=K.endLine));S+=T.length;let A=t.edges.filter(N=>N.kind==="call"&&N.fromNodeId===C.nodeId&&N.disposition!=="excluded"&&N.disposition!=="unsupported"),W=new Map;for(let N of A){let K=s.get(N.toNodeId);if(!K)continue;let te=Xr(K);W.set(te,(W.get(te)??0)+1)}let le=d.get(C.id),q=LD(e,le?m.get(le.symbolId)??[]:[]),Y=DD(q);for(let N of q){if(!o(N.alternative.file)||u(N.alternative))continue;let K=Qs(N.alternative.label),te=sh(T,D,K,N.row.callsiteLine,Y.get(K)===1);if(!te)continue;let me=Zr(D,te.line,K);if(!me)continue;let ge=bi(C.location.file,te.line,K);if(p.has(ge))continue;p.add(ge);let ce=gh(N.row.source);f.push({anchor:{id:Kn(C.id,te.line,N.alternative.symbol??N.alternative.file),status:ce,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:me.line,endLine:me.endLine,text:me.text,signals:me.signals,calleeLeaf:K},alternatives:[N.alternative],alternativeCount:1,evidence:[{method:N.row.source,strength:ce,identity:N.row.symbol,location:{file:C.location.file,line:te.line}}]}})}for(let N of A){if(a.has(N.toNodeId))continue;let K=s.get(N.toNodeId);if(!K?.location||!o(K.location.file))continue;let te=Xr(K),me=N.evidence.find(X=>{let Se=X.location;return Se!==null&&Se.file===C.location?.file&&Se.line>=0})?.location?.line,ge=sh(T,D,te,me,W.get(te)===1);if(!ge)continue;let ce=Zr(D,ge.line,te);if(!ce)continue;let be=bi(C.location.file,ge.line,te);if(p.has(be))continue;p.add(be);let F=Ac(K);if(!F||u(F))continue;let Z=Tc(N.evidence);f.push({anchor:{id:Kn(C.id,ge.line,K.id),status:Z,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:ce.line,endLine:ce.endLine,text:ce.text,signals:ce.signals,calleeLeaf:te},alternatives:[F],alternativeCount:1,evidence:N.evidence}})}for(let N of T){let K=bi(C.location.file,N.line,N.calleeLeaf);if(p.has(K))continue;let te=Zr(D,N.line,N.calleeLeaf);if(!te)continue;let me=Yt(C.location.file,Xt(e).get(N.calleeLeaf)??[]).flatMap(F=>J(e,F.file).filter(Z=>Z.symbol===F.symbol&&Z.isFunctionLike)).filter(F=>o(F.relativePath)&&!u({symbol:F.symbol,label:F.leaf,file:F.relativePath,line:F.startLine,endLine:F.endLine})),ge=ta(me.map(F=>({symbol:F.symbol,label:F.leaf??N.calleeLeaf,file:F.relativePath,line:F.startLine,endLine:F.endLine})));if(ge.length===0){E+=1;continue}let ce=`${C.id}\0${N.line}\0${N.calleeLeaf}`;if(g.has(ce))continue;g.add(ce);let be=ge.length>1;be?y+=1:v+=1,f.push({anchor:{id:Kn(C.id,N.line,N.calleeLeaf),status:be?"ambiguous":"candidate",source:"leaf-identity-candidate",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:C.id,fromLabel:C.label,callsite:{file:C.location.file,line:te.line,endLine:te.endLine,text:te.text,signals:te.signals,calleeLeaf:N.calleeLeaf},alternatives:ge.slice(0,3),alternativeCount:ge.length,evidence:[]}})}}return fh(e,f,n.steps,r,{scannedBehaviorSteps:h,visibleCallsites:S,graphEvidencedCallsites:p.size,identityCandidateCallsites:v,ambiguousCallsites:y,unresolvedCallsites:E,upstreamCandidates:w,resultCandidates:b,runtimeCandidates:R},i.selectionTerms)}function uh(e,t,n){let i=new Map(t.nodes.map(r=>[r.id,r]));for(let r of n.steps)if(!(!r.behavior||!r.location))for(let o of t.edges){if(o.kind!=="reference"||o.fromNodeId!==r.nodeId||o.disposition==="excluded"||o.disposition==="unsupported")continue;let s=i.get(o.toNodeId);if(!s?.location||!Nc(e,s))continue;let a=Xr(s),l=kc(o,r.location.file)?.line,c=r.behavior.lines.find(u=>(l===void 0||l>=u.line&&l<=u.endLine)&&u.text.includes(a));!c||dh(c.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 dh(e){return e.includes("call")&&e.some(t=>["return","mutation","shape","spread","binding"].includes(t))?"result-callback":"callable-reference"}function mh(e,t,n={}){let i=n.limit??lh;if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`next-anchor limit must be a positive safe integer; received ${i}`);let r=n.sourceAllowed??(()=>!0),o=[],s=t.map((f,p)=>({id:f.id,nodeId:f.id,order:p,role:"anchor",kind:"source-construct",label:f.label,location:{file:f.file,line:f.startLine,endLine:f.endLine},behavior:null})),a=t.map(f=>({file:f.file,startLine:f.startLine,endLine:f.endLine})),l=0,c=0,u=0,d=0,m=0;for(let f of t){let p=ie(e,f.file),h=(ee(e,f.file)?.callSites??[]).filter(b=>b.line>=f.startLine&&b.line<=f.endLine);l+=h.length;let S=Sn(e,f.file,f.startLine,f.endLine),v=xn(e,f.file,f.startLine,f.endLine),y=new Set;for(let b of v.targets){if(!r(b.definition.relativePath)||a.some(I=>I.file===b.definition.relativePath&&I.startLine<=b.definition.startLine&&I.endLine>=b.definition.endLine))continue;let R=bi(f.file,b.sourceLine,b.calleeLeaf);y.add(R);let C=Fc(S.get(b.sourceLine)),L={symbol:b.definition.symbol,label:b.definition.leaf,file:b.definition.relativePath,line:b.definition.startLine,endLine:b.definition.endLine};o.push({anchor:{id:Kn(f.id,b.sourceLine,b.definition.symbol),status:"exact",source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:f.id,fromLabel:f.label,callsite:{file:f.file,line:b.sourceLine,endLine:b.sourceLine,text:p[b.sourceLine]?.trim()||`${b.calleeLeaf}()`,signals:C,calleeLeaf:b.calleeLeaf},alternatives:[L],alternativeCount:1,evidence:[{method:"scip-occurrence-callsite",strength:"exact",identity:b.definition.symbol,location:{file:f.file,line:b.sourceLine}}]}})}c+=v.resolvedCallsites;let E=Un(e,f.file,{ranges:[{startLine:f.startLine,endLine:f.endLine}]}),w=new Map;for(let b of E.targets){let R=h.find(I=>I.line===b.line)?.calleeLeaf??b.calleeLeaf,C=bi(f.file,b.line,R),L=w.get(C)??[];L.push(b),w.set(C,L)}for(let[b,R]of w){if(y.has(b))continue;y.add(b);let C=R.filter(D=>r(D.targetFile)&&!a.some(T=>T.file===D.targetFile&&T.startLine<=D.targetStartLine&&T.endLine>=D.targetEndLine));if(C.length===0)continue;let L=C[0],I=h.find(D=>D.line===L.line)?.calleeLeaf??L.calleeLeaf,x=Fc(S.get(L.line)),P=ta(C.map(D=>({symbol:D.targetSymbol??null,label:D.calleeLeaf,file:D.targetFile,line:D.targetStartLine,endLine:D.targetEndLine}))),_=C.some(D=>(D.resolutionAlternativeCount??0)>1)?"candidate":C.every(D=>D.strength==="exact")?"exact":"derived";o.push({anchor:{id:Kn(f.id,L.line,P.map(D=>`${D.file}:${D.line}`).join("|")),status:P.length>1?"ambiguous":_,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:f.id,fromLabel:f.label,callsite:{file:f.file,line:L.line,endLine:L.line,text:p[L.line]?.trim()||`${L.calleeLeaf}()`,signals:x,calleeLeaf:I},alternatives:P.slice(0,3),alternativeCount:P.length,evidence:C.map(D=>({method:D.resolution==="constructed-member-receiver"?"ast-constructed-member-callsite":D.resolution==="factory-callback-member"?"ast-factory-callback-callsite":D.resolution==="imported-service-object-member"?"ast-service-member-callsite":"ast-import-member-callsite",strength:_,identity:D.targetSymbol??`${D.targetFile}:${D.targetStartLine}-${D.targetEndLine}`,location:{file:f.file,line:L.line}}))}})}c+=w.size;for(let b of h){let R=bi(f.file,b.line,b.calleeLeaf);y.has(R)||(m+=1)}}return fh(e,o,s,i,{scannedBehaviorSteps:t.length,visibleCallsites:l,graphEvidencedCallsites:c,identityCandidateCallsites:u,ambiguousCallsites:d,unresolvedCallsites:m,upstreamCandidates:0,resultCandidates:0,runtimeCandidates:0})}function fh(e,t,n,i,r,o=[]){let s=PD(t).sort(ph),a=s.filter(p=>ID(e,p)).slice(0,i),l=new Set(a.map(p=>p.anchor.id)),c=s.filter(p=>!l.has(p.anchor.id)),u=a.map(p=>p.anchor),d=c.map(p=>p.anchor),m=ta(u.flatMap(p=>p.alternativeCount===1?p.alternatives:[])),f=ta(d.flatMap(p=>p.alternativeCount===1?p.alternatives:[]));return{anchors:u,withheldAnchors:d,candidateAnchors:s.length,omittedAnchors:Math.max(0,s.length-u.length),...r,inspectCommand:m.length===0?null:`codebaseiq inspect ${m.map(ah).join(" ")} --view behavior`,remainingInspectCommands:FD(f,8).map(p=>`codebaseiq inspect ${p.map(ah).join(" ")} --view behavior`)}}function ph(e,t){let n=e.anchor.alternatives[0],i=t.anchor.alternatives[0];return ea(e.anchor.status)-ea(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(i?.file??"")||(n?.line??0)-(i?.line??0)||e.anchor.id.localeCompare(t.anchor.id)}function ID(e,t){if(t.anchor.alternativeCount!==1)return!0;let n=t.anchor.alternatives[0],i=n.endLine??n.line;return ie(e,n.file).slice(n.line,i+1).join(`
|
|
72
|
+
`).length<=2e4}function Fc(e){return e?.includes("call")?[...e]:["call",...e??[]]}function LD(e,t){let n=new Map;for(let i of t){let r=J(e,i.file).find(a=>a.symbol===i.symbol&&a.isFunctionLike);if(!r)continue;let o={symbol:r.symbol,label:r.leaf,file:r.relativePath,line:r.startLine,endLine:r.endLine},s=n.get(r.symbol);!s||oh(i.source)>oh(s.row.source)?n.set(r.symbol,{row:{...i,...i.callsiteLine===void 0&&s?.row.callsiteLine!==void 0?{callsiteLine:s.row.callsiteLine}:{}},alternative:o}):s.row.callsiteLine===void 0&&i.callsiteLine!==void 0&&n.set(r.symbol,{...s,row:{...s.row,callsiteLine:i.callsiteLine}})}return[...n.values()]}function DD(e){let t=new Map;for(let n of e){let i=Qs(n.alternative.label);t.set(i,(t.get(i)??0)+1)}return t}function gh(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function oh(e){return gh(e)==="exact"?2:1}function Zr(e,t,n){return e.find(i=>t>=i.line&&t<=i.endLine&&i.text.includes(n))??e.find(i=>t>=i.line&&t<=i.endLine)??null}function sh(e,t,n,i,r){if(i!==void 0)return e.find(s=>s.line===i&&s.calleeLeaf===n&&Zr(t,s.line,n)!==null)??null;let o=e.filter(s=>s.calleeLeaf===n&&Zr(t,s.line,s.calleeLeaf)!==null);return r&&o.length===1?o[0]:null}function Xr(e){let t=e.attributes.leaf;if(typeof t=="string"&&t.length>0)return Qs(t);let n=e.label.slice(e.label.lastIndexOf(":")+1);return Qs(n)}function Qs(e){return e.replace(/\(\)$/u,"").replace(/^#/u,"")}function Mc(e){if(e?.kind!=="symbol"||!e.id.startsWith("symbol:"))return null;try{return decodeURIComponent(e.id.slice(7))}catch{return null}}function Ac(e){return e.location?{symbol:Mc(e),label:e.label,file:e.location.file,line:e.location.line,endLine:e.location.endLine??null}:null}function Nc(e,t){let n=Ac(t);return n?.symbol&&J(e,n.file).some(r=>r.symbol===n.symbol&&r.isFunctionLike)?n:null}function kc(e,t){return e.evidence.find(n=>n.location?.file===t)?.location??e.evidence.find(n=>n.location!==null)?.location??null}function Tc(e){let t={exact:5,derived:4,mixed:3,candidate:2,unknown:1};return e.reduce((n,i)=>t[i.strength]>t[n]?i.strength:n,"unknown")}function PD(e){let t=new Map;for(let n of e){let r=n.anchor.alternatives[0]?.symbol??`${n.anchor.callsite.file}:${n.anchor.callsite.line}:${n.anchor.callsite.calleeLeaf}`,o=t.get(r);(!o||TD(n,o)<0)&&t.set(r,n)}return[...t.values()]}function TD(e,t){return ea(e.anchor.status)-ea(t.anchor.status)||e.anchor.alternativeCount-t.anchor.alternativeCount||ph(e,t)}function ea(e){return{exact:0,derived:1,mixed:2,candidate:3,unknown:4,ambiguous:5}[e]}function ta(e){let t=new Map;for(let n of e)t.set(n.symbol??`${n.file}:${n.line}`,n);return[...t.values()].sort((n,i)=>n.file.localeCompare(i.file)||n.line-i.line||n.label.localeCompare(i.label))}function ah(e){return`--at ${MD(`${e.file}:${e.line+1}`)}`}function FD(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}function MD(e){return`'${e.replaceAll("'","'\\''")}'`}function bi(e,t,n){return`${e}\0${t}\0${n}`}function Kn(e,t,n){return["next-anchor",e,String(t),n].map(encodeURIComponent).join(":")}var Eh=6,AD=12,ND=48,kD=2e4,hh=12,Si=Number.MAX_SAFE_INTEGER,_D=["definition","callers","callees"],jc={search:12,"exact-source":24,definition:24,caller:8,callee:8,"production-reference":6,"test-reference":2,dependency:6,consumer:6};function BD(e,t){if(t.cursor)throw new Error("Inspect no longer accepts semantic packet cursors. Run the original inspect selectors again.");let n=$D(t),i=UD(e,n),r=i.candidates.sort((P,_)=>_c(P,_));n.view==="behavior"&&KD(e,r),qD(e,r),n.view==="behavior"&&zD(e,r);let o=Tp(r.map(P=>Oc(P,n.view)),n.evidenceBudgets,(P,_)=>_c(P.candidate,_.candidate)),{selected:s,omitted:a}=Os(o.selected,n.maxUnits,n.maxCharacters,(P,_)=>_c(P.candidate,_.candidate),n.view==="source"),l=s.map(P=>P.candidate),c=[...o.omitted,...a].map(P=>P.candidate),u=l.map(tP),d=gs(l.map(P=>P.kind==="source"?P.bindingClosure:void 0),l.filter(P=>P.kind==="source").map(P=>({relativePath:P.relativePath,startLine:P.startLine,endLine:P.endLine}))),m=u.reduce((P,_)=>P+(_.kind==="source"?rP(_.source):0),0),f=u.reduce((P,_)=>P+(_.kind==="source"?_.source.length:0),0),p=u.reduce((P,_)=>P+Lh(_,n.view),0),g=u.filter(P=>P.kind==="source"&&(P.roles.includes("search")||P.roles.includes("location"))).map(nP),h=r.filter(P=>P.kind==="source"&&(P.roles.includes("search")||P.roles.includes("location"))).length,S=u.filter(P=>P.kind==="source"&&(P.roles.includes("search")||P.roles.includes("location"))).length,v=i.searches.map(P=>JD(P,r,l)),y=YD(c),E=i.locations.every(P=>P.matched)&&i.evidence.every(P=>P.kind==="matched")&&i.searches.every(P=>ZD(P.textCoverage))&&c.every(P=>!P.roles.some(_=>_==="location"||_==="definition")),w=v.reduce((P,_)=>P+_.omittedMatches,0),b=c.length===0&&w===0,R=b?void 0:Ih(n,!0),C=WD(n,c),L=OD(b,E,c.length+w,C,v,R),I=r.filter(P=>n.view==="behavior"&&P.kind==="source"&&P.roles.some(_=>_==="location"||_==="definition"||_==="search")).map(P=>({id:`inspect:${P.relativePath}:${P.startLine}-${P.endLine}`,label:P.ownerShort??`${P.relativePath}:${P.startLine+1}`,file:P.relativePath,startLine:P.startLine,endLine:P.endLine})),x=I.length>0?mh(e,I):void 0;return{searches:v,evidence:i.evidence,locations:i.locations,slices:g,candidateSlices:h,omittedSlices:h-S,maxSlices:h,maxTotalLines:m,units:u,candidateUnits:r.length,omittedUnits:c.length,maxUnits:n.maxUnits,maxCharacters:n.maxCharacters,returnedLines:m,returnedCharacters:f,returnedViewCharacters:p,view:n.view,omissionGroups:C,packetCoverage:{mode:b?"complete":"bounded",candidateUnits:r.length,returnedUnits:u.length,omittedUnits:c.length,omittedByRole:y,exactSelectorsComplete:E,maxUnits:n.maxUnits,maxCharacters:n.maxCharacters,channels:XD(r,l,n.evidenceBudgets,n.view),...R?{expansionCommand:R}:{}},stoppingSummary:L,...x&&x.candidateAnchors>0?{causalFrontier:x}:{},bindingClosure:d,continuation:null}}function OD(e,t,n,i,r,o){let s=ut([...i.map(a=>a.drillCommand),...r.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 $D(e){let t=Bc(e.searches),n=Bc(e.symbols),i=Bc(e.locations),r=t.length+n.length+i.length;if(r===0)throw new Error("inspect requires at least one --search, --symbol, or --at selector.");if(r>24)throw new RangeError(`inspect accepts at most ${24} selectors; received ${r}.`);let o=e.evidence??{};if(e.unitLines!==void 0&&qn(e.unitLines,"unitLines"),e.totalLines!==void 0&&qn(e.totalLines,"totalLines"),e.sliceLimit!==void 0&&qn(e.sliceLimit,"sliceLimit"),e.maxCharacters!==void 0&&qn(e.maxCharacters,"maxCharacters"),e.maxUnits!==void 0&&qn(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:i,...e.scope?.trim()?{scope:e.scope.trim()}:{},context:xh(e.context??Eh,"context"),searchLimit:qn(e.searchLimit??(s?Si:AD),"searchLimit"),maxUnits:qn(s?Si:e.maxUnits??ND,"maxUnits"),maxCharacters:qn(s?Si:e.maxCharacters??kD,"maxCharacters"),evidenceBudgets:s?HD():jD(e.evidenceBudgets??jc),view:e.view??"source",evidence:{...o.parts?{parts:[...o.parts]}:n.length>0?{parts:[..._D]}:{},...o.referenceContext!==void 0?{referenceContext:xh(o.referenceContext,"referenceContext")}:{},relatedSourceLines:o.relatedSourceLines??60,...o.semantic!==void 0?{semantic:o.semantic}:{}}}}function jD(e){let t={...jc};for(let[n,i]of Object.entries(e)){if(!(n in t))throw new Error(`Unknown inspect evidence channel: ${n}.`);if(!Number.isSafeInteger(i)||(i??-1)<0)throw new RangeError(`Evidence budget ${n} must be a non-negative safe integer; received ${i}.`);t[n]=i}return t}function HD(){return Object.fromEntries(Object.keys(jc).map(e=>[e,Si]))}function UD(e,t){let n=[],i=0,r=t.searches.map(c=>{let u=oc(e,c,{scope:t.scope,context:0,limit:t.searchLimit,ranking:"structural"});return{pattern:c,result:u,matches:u.matches}}),o=Math.max(0,...r.map(c=>c.matches.length));for(let c=0;c<o;c+=1)for(let u of r){let d=u.matches[c];if(!d)continue;let m=jn(e,d.relativePath,d.focusLine,Si,t.context);m&&Zi(e,n,m,"search",`search:${u.pattern}`,d.ownerSymbol,d.ownerShort,1,i++)}let s=r.map(({pattern:c,result:u})=>{let d=u.omittedMatches>0?wh(c,t.scope):void 0,m=u.fileCoverage??[],f=QD(c,m,t.scope);return{pattern:c,matchingLines:u.matchingLines,returnedMatches:u.matches.length,omittedMatches:u.omittedMatches,matchingFiles:m.length,returnedFiles:m.filter(p=>p.returnedMatches>0).length,omittedFiles:m.filter(p=>p.returnedMatches===0).length,candidateUnits:0,selectedUnits:0,omittedUnits:0,scopeHints:f.slice(0,hh),omittedScopeHints:Math.max(0,f.length-hh),textCoverage:u.textCoverage,...d?{exactFollowup:d}:{}}}),a=t.locations.map(c=>{let u=iP(c),d=u?lt(e,u.path):null,m=d?jn(e,d,u.line-1,Si,t.context):null;return m&&Zi(e,n,m,"location",`at:${c}`,null,null,0,i++),{target:c,matched:m!==null}}),l=t.symbols.map(c=>Pc(e,c,t.evidence));for(let c of l)if(c.kind==="matched"){if(c.definition){let u=jn(e,c.definition.relativePath,c.definition.startLine,Si,t.context);u&&Zi(e,n,u,"definition",`definition:${c.shortName}`,c.symbol,c.shortName,0,i++)}for(let u of c.referenceWindows){let d=u.references[0];Zi(e,n,{...u,focusLine:d?.line??u.startLine,unitType:null,unitStartLine:u.startLine,unitEndLine:u.endLine,omittedLines:0},"reference",`reference:${c.shortName}`,d?.enclosingSymbol??null,d?.enclosingShort??null,V(u.relativePath)==="test"?5:4,i++,u.references.map(m=>m.line),c.symbol)}for(let u of c.callers)bh(e,n,u,"caller",c,2,i++);for(let u of c.callees)bh(e,n,u,"callee",c,3,i++);for(let u of c.dependencies)Sh(e,n,"dependency",c.file,u.relativePath,c.symbol,t.context,6,i++);for(let u of c.consumers)Sh(e,n,"consumer",u.relativePath,c.file,c.symbol,t.context,7,i++)}return{searches:s,evidence:l,locations:a,candidates:n}}function _c(e,t){return e.priority-t.priority||t.roles.length-e.roles.length||t.reasons.length-e.reasons.length||yh(V(e.relativePath))-yh(V(t.relativePath))||e.sequence-t.sequence}function yh(e){switch(e){case"entry":case"source":case"worker":return 0;case"barrel":return 1;case"test":return 2}}function Oc(e,t){return{candidate:e,priority:e.priority,sequence:e.sequence,relativePath:e.relativePath,fileKind:V(e.relativePath),evidenceCharacters:Lh(e,t),roles:e.roles,reasons:e.reasons,symbols:e.symbols,behaviorSignals:e.kind==="source"?e.behavior?.signals??[]:[],channel:$c(e)}}function $c(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")?V(e.relativePath)==="test"?"test-reference":"production-reference":t.includes("dependency")?"dependency":t.includes("consumer")?"consumer":"search"}function zD(e,t){let n=t.filter(r=>r.kind==="source"),i=xr(e,{files:ut(n.map(r=>r.relativePath))});for(let r of n){r.behavior=ji(e,r.relativePath,r.startLine,r.endLine,r.focusLines)??void 0;let o=i.filter(a=>a.source.file===r.relativePath&&a.source.startLine<=r.endLine&&a.source.endLine>=r.startLine),s=o.filter(a=>!GD(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(l=>({name:l.name,value:l.value,evidence:l.evidence})),derivation:{kind:a.derivation.kind,rule:a.derivation.rule,sourceSpans:a.derivation.sourceSpans.length}}));r.runtimeFacts=s.length>0?s:void 0}}function GD(e,t){if(e.strength!=="candidate"||e.protocol!=="http")return!1;let n=e.keyParts.find(r=>r.name==="path")?.value,i=e.keyParts.find(r=>r.name==="method")?.value;return n?t.some(r=>{if(r===e||r.action!==e.action||r.role!==e.role||r.source.startLine!==e.source.startLine||r.derivation.rule!=="http.mount-prefix")return!1;let o=r.keyParts.find(a=>a.name==="path")?.value,s=r.keyParts.find(a=>a.name==="method")?.value;return!!(o&&o!==n&&o.endsWith(n)&&(!i||i===s))}):!1}function KD(e,t){for(let n of t){if(n.kind!=="source")continue;let i=gt(e,n.relativePath,n.startLine,n.endLine,n.focusLines);i.startLine===n.startLine&&i.endLine===n.endLine||(n.startLine=i.startLine,n.endLine=i.endLine,n.source=ie(e,n.relativePath).slice(i.startLine,i.endLine+1).join(`
|
|
73
|
+
`),n.unitStartLine=i.startLine,n.unitEndLine=i.endLine,n.omittedLines=0)}}function qD(e,t){for(let n of t)n.kind==="source"&&(n.bindingClosure=$i(e,n.relativePath,n.startLine,n.endLine))}function WD(e,t){let n=new Map;for(let i of t){let r=na(i.relativePath),o=$c(i),s=[...i.roles].sort().join(","),a=i.kind==="path"?i.relationship:"",l=`${r}|${o}|${s}|${a}`,c=n.get(l)??[];c.push(i),n.set(l,c)}return[...n.entries()].map(([i,r])=>{let o=r[0],s=ut(r.flatMap(l=>[...l.roles])).sort(),a=ut(r.flatMap(l=>l.kind==="source"?l.behavior?.signals??[]:[])).sort();return{id:`g-${Rh("sha256").update(i).digest("hex").slice(0,8)}`,scope:na(o.relativePath),channel:$c(o),roles:s,behaviorSignals:a,candidateUnits:r.length,sourceCharacters:r.reduce((l,c)=>l+(c.kind==="source"?c.source.length:0),0),anchors:r.map(l=>({relativePath:l.relativePath,line:l.kind==="source"?l.focusLine:0,ownerShort:l.kind==="source"?l.ownerShort:null,roles:[...l.roles],behaviorSignals:l.kind==="source"?[...l.behavior?.signals??[]]:[]})),drillCommand:VD(e,r)}}).sort((i,r)=>r.candidateUnits-i.candidateUnits||r.sourceCharacters-i.sourceCharacters||i.scope.localeCompare(r.scope)||i.id.localeCompare(r.id))}function VD(e,t){let n=ut(t.flatMap(o=>o.reasons.filter(s=>s.startsWith("search:")).map(s=>s.slice(7)))),i=na(t[0].relativePath);if(n.length>0&&t.every(o=>o.kind==="source"&&o.roles.includes("search"))){let o=["codebaseiq inspect"];for(let s of n)o.push(`--search ${_t(s)}`);return o.push(`--scope ${_t(i)}`,"--full"),e.view==="behavior"&&o.push("--view behavior"),o.join(" ")}let r=t.filter(o=>o.kind==="source");if(r.length>0&&r.length<=24){let o=["codebaseiq inspect"];for(let s of r)o.push(`--at ${_t(`${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:Ih(e,!0)}function JD(e,t,n){let i=`search:${e.pattern}`,r=t.filter(a=>a.reasons.includes(i)).length,o=new Set(n),s=t.filter(a=>a.reasons.includes(i)&&o.has(a)).length;return{...e,candidateUnits:r,selectedUnits:s,omittedUnits:r-s}}function YD(e){let t={};for(let n of e)for(let i of n.roles)t[i]=(t[i]??0)+1;return t}function XD(e,t,n,i){let r=e.map(s=>Oc(s,i).channel),o=t.map(s=>Oc(s,i).channel);return Object.fromEntries(Object.keys(n).map(s=>{let a=r.filter(c=>c===s).length,l=o.filter(c=>c===s).length;return[s,{candidateUnits:a,returnedUnits:l,omittedUnits:a-l,maxUnits:n[s]}]}))}function ZD(e){return!!(e&&e.skippedUnreadablePaths.length===0&&e.skippedOversizedPaths.length===0)}function QD(e,t,n){let i=new Map;for(let r of t){let o=na(r.relativePath),s=i.get(o)??{matchingLines:0,returnedMatches:0};s.matchingLines+=r.matchingLines,s.returnedMatches+=r.returnedMatches,i.set(o,s)}return[...i.entries()].map(([r,o])=>({scope:r,...o,exactFollowup:wh(e,r||n)})).sort((r,o)=>o.matchingLines-r.matchingLines||o.returnedMatches-r.returnedMatches||r.scope.localeCompare(o.scope))}function na(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function wh(e,t){return`codebaseiq inspect --search ${_t(e)}${t?` --scope ${_t(t)}`:""} --full`}function Ih(e,t){let n=["codebaseiq inspect"];for(let i of e.searches)n.push(`--search ${_t(i)}`);for(let i of e.symbols)n.push(`--symbol ${_t(i)}`);for(let i of e.locations)n.push(`--at ${_t(i)}`);return e.scope&&n.push(`--scope ${_t(e.scope)}`),e.context!==Eh&&n.push(`--context ${e.context}`),e.evidence.parts&&n.push(`--include ${_t(e.evidence.parts.join(","))}`),t&&n.push("--full"),e.view==="behavior"&&n.push("--view behavior"),n.join(" ")}function bh(e,t,n,i,r,o,s){Zi(e,t,{...n,unitType:null,unitStartLine:n.startLine,unitEndLine:n.endLine+n.omittedLines},i,`${i}:${r.shortName}`,n.symbol,n.shortName,o,s,[n.focusLine],r.symbol)}function Sh(e,t,n,i,r,o,s,a,l){let c=`${i} -> ${r}`,u=Ce(e,i).filter(h=>h.sourcePath===r),d=ie(e,i),m=eP(d,u,r),f=m===null?null:ws(e,i,m,Math.min(s,4));if(f){Zi(e,t,{...f,unitType:null,unitStartLine:f.startLine,unitEndLine:f.endLine,omittedLines:0},n,`${n}:${c}`,null,null,a,l,[f.focusLine],o);return}let p=`codebaseiq inspect --search ${_t(Dh(r))} --scope ${_t(i)}`,g=t.find(h=>h.kind==="path"&&h.relativePath===i&&h.relationship===c);if(g){g.roles=ut([...g.roles,n]),g.reasons=ut([...g.reasons,`${n}:${c}`]),g.symbols=ut([...g.symbols,o]),g.priority=Math.min(g.priority,a);return}t.push({kind:"path",roles:[n],relativePath:i,relationship:c,reasons:[`${n}:${c}`],symbols:[o],exactFollowup:p,priority:a,sequence:l})}function eP(e,t,n){let i=ut(t.flatMap(l=>[l.importedName,l.localName??""]).filter(l=>l.length>1)),r=Dh(n).replace(/\.[^.]+$/u,""),o=ut([...i,r]).filter(Boolean),s=/\b(?:from|import|include|require|use)\b/u,a=e.findIndex(l=>s.test(l)&&o.some(c=>l.includes(c)));return a>=0?a:null}function Zi(e,t,n,i,r,o,s,a,l,c=[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),f=Math.max(d.endLine,n.endLine);d.startLine=m,d.endLine=f,d.source=ie(e,n.relativePath).slice(m,f+1).join(`
|
|
74
|
+
`),d.focusLine=Math.min(d.focusLine,n.focusLine),d.focusLines=Ch([...d.focusLines,...c]),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=ut([...d.reasons,r]),d.roles=ut([...d.roles,i]),d.symbols=ut([...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:[r],focusLines:Ch(c),ownerSymbol:o,ownerShort:s,roles:[i],symbols:u?[u]:[],priority:a,sequence:l})}function tP(e){if(e.kind==="path"){let{priority:o,sequence:s,...a}=e;return{...a,id:vh(a)}}let{priority:t,sequence:n,bindingClosure:i,...r}=e;return{...r,id:vh(r),omittedCharacters:0}}function nP(e){let{kind:t,id:n,roles:i,symbols:r,omittedCharacters:o,behavior:s,runtimeFacts:a,...l}=e;return l}function vh(e){return Rh("sha256").update(JSON.stringify(e)).digest("hex").slice(0,16)}function iP(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 Bc(e){return ut((e??[]).map(t=>t.trim()).filter(Boolean))}function ut(e){return[...new Set(e)]}function Ch(e){return ut(e).sort((t,n)=>t-n)}function rP(e){return e.length===0?0:e.split(`
|
|
75
|
+
`).length}function Lh(e,t){if(e.kind==="path")return e.relationship.length+e.exactFollowup.length;let n="bindingClosure"in e?ff(e.bindingClosure):0,i=(e.runtimeFacts??[]).reduce((r,o)=>r+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((r,o)=>r+o.text.length+o.signals.join(",").length+12,0)+e.behavior.testCases.reduce((r,o)=>r+o.length+2,0)+i+n:e.source.length+n+i}function Dh(e){return e.split("/").at(-1)??e}function _t(e){return`'${e.replaceAll("'","'\\''")}'`}function qn(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new RangeError(`${t} must be a positive safe integer; received ${e}`);return e}function xh(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 oP}from"path";function sP(e,t){let n=t.className,i=rt(e,n);return i.match?i.total>1?{kind:"ambiguous",query:n,total:i.total,candidates:[Ph(i.match),...i.candidates]}:{kind:"matched",query:n,owner:lP(i.match),methods:aP(e,i.match)}:{kind:"missing",query:n,suggestions:es(e,n,5)}}function aP(e,t){let n=re(t.symbol),r=new U(e).definitionsForFile(t.relativePath).filter(l=>it(l.symbol)),o=r.filter(l=>l.parentTypeName===n||l.symbol.includes(n)),a=(o.length>0?o:cP(oP(t.relativePath))===n?r.filter(l=>l.symbol.includes("<invalid-global-code>")):[]).map(l=>({startLine:l.startLine,endLine:l.endLine,name:re(l.symbol)}));return ye(t.relativePath)!=="clojure"?a:dP(a,uP(e,t))}function Ph(e){return{symbol:e.symbol,shortName:k(e.symbol),relativePath:e.relativePath,startLine:e.startLine}}function lP(e){return{...Ph(e),endLine:e.endLine}}function cP(e){return e.replace(/\.[^.]+$/,"")}function uP(e,t){let n=re(t.symbol);return n?(ee(e,t.relativePath)?.clojureMembers??[]).filter(i=>i.ownerName===n).map(i=>({startLine:i.startLine,endLine:i.endLine,name:i.memberName})):[]}function dP(e,t){let n=new Map;for(let i of[...e,...t])n.set(`${i.name}:${i.startLine}:${i.endLine}`,i);return[...n.values()].sort((i,r)=>i.startLine-r.startLine||i.endLine-r.endLine)}import{createHash as lM}from"crypto";var KY={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."},mP=[{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 fP(e){let t=new Set(e);return mP.filter(n=>n.families.some(i=>t.has(i)))}function Th(e){return fP(e).map(t=>`[${t.id}] ${t.capability} ${t.consequence} Recover selected paths with: ${t.recoverWith.map(n=>`codebaseiq ${n}`).join(", ")}.`)}var pP=["incoming","outgoing","both"];function Me(e,t,n,i={}){return{family:e,subtype:t,...i.match?{match:i.match}:{},directions:pP,evidenceStrengths:i.strengths??["exact","derived","mixed"],supportCeiling:i.supportCeiling??"partial",establishes:n,nonClaims:i.nonClaims??[],recoverWith:i.recoverWith??["inspect","code"]}}var gP=["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"],hP=["captured-value-to-state","constant-to-state","expression-to-state","property-to-state","return-to-state","value-to-state"],yP=["await-completion-before","awaits-completion","inside-lock-scope","lexical-successor"],bP=[{id:"indexed-program-identity",label:"SCIP/compiler identity and source ownership",requirements:["indexed-graph"],relations:[Me("execution","call","The source construct may call the resolved target.",{nonClaims:["Static may-call reachability does not prove that an invocation occurred at runtime."],recoverWith:["call-graph","inspect","code"]}),Me("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"]}),Me("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"]}),Me("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"]}),Me("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"]}),Me("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"]}),Me("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"]}),Me("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"]}),Me("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:[Me("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"]}),Me("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"]}),Me("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"]}),Me("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:[...gP.map(e=>Me("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"]})),Me("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"]}),Me("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=>Me("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:[Me("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"]}),Me("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"]}),Me("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"]}),Me("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"]}),Me("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:[...hP.map(e=>Me("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=>Me("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"]})),...yP.map(e=>Me("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 Fh(e,t){let n=bP.flatMap(i=>i.relations.filter(r=>r.family===e&&(r.match==="prefix"?t.startsWith(r.subtype):t===r.subtype)).map(r=>({provider:i,relation:r})));if(n.length>1)throw new Error(`Ambiguous graph relation provider for ${e}/${t}: ${n.map(i=>i.provider.id).join(", ")}`);return n[0]??null}var Gt=["execution","runtime","dataflow","state","temporal","contract","identity","ownership","dependencies"];var Mh=["call","contract-symbol","import","reference","runtime-boundary"],SP={call:[{family:"control",subtype:"call"}],"contract-symbol":[{family:"contract",subtype:"uses-contract-symbol"}],import:[{family:"identity",subtype:"imports"}],reference:[{family:"identity",subtype:"references"}]},vP={"structural-membership":[{family:"identity",subtype:"contains"}],"boundary-observation":[{family:"identity",subtype:"owns-runtime-observation"}],"external-import":[{family:"identity",subtype:"imports-external"}]};function Ah(e){if(e.kind!=="runtime-boundary")return Nh(SP[e.kind]);let t=e.fromBoundaryParticipant?.protocol??e.toBoundaryParticipant?.protocol,n={crossesRuntimeBoundary:!0,...t?{protocol:t}:{},...e.runtimeBoundaryKey?{runtimeKey:e.runtimeBoundaryKey}:{}},i=[{family:"control",subtype:"runtime-handoff",context:n}];return e.evidence==="runtime-boundary:carrier.discriminator"&&(i.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}:{}}}),i.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"&&i.push({family:"temporal",subtype:"enqueue-before-consume",context:{...n},attributes:{producerAction:e.fromBoundaryParticipant.action,consumerAction:e.toBoundaryParticipant.action,retryPolicy:"unknown"}}),i}function ia(e){return Nh(vP[e])}function Nh(e){return e.map(t=>({...t,...t.context?{context:{...t.context}}:{},...t.attributes?{attributes:{...t.attributes}}:{}}))}import{join as qP}from"path";import{createRequire as CP}from"module";import{resolve as eo}from"path";var xP=CP(import.meta.url),Qr;function _h(e,t,n){let i=RP();if(!i)return Hc("The TypeScript compiler runtime is unavailable.");let r=EP(i,e,t),o=r.getSourceFile(eo(t))??r.getSourceFile(t);if(!o)return Hc(`The TypeScript compiler did not materialize ${t}.`);let s={ts:i,sourceFile:o,checker:r.getTypeChecker(),points:new Map,edges:new Map,unsupported:new Set,nextCfgId:0},a=IP(i,o,n);if(a.length===0)return Hc("No function-like construct intersects the selected source range.");let l=new Map(a.map(d=>[d,LP(o,d)])),c=a.map(d=>PP(s,d,DP(i,d,l),l.get(d)));for(let d of c)TP(s,d),NP(s,d),BP(s,d);$P(s,c);let u=[...s.unsupported].sort();return{points:[...s.points.values()].map(({node:d,...m})=>m).sort(KP),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 RP(){if(Qr!==void 0)return Qr;try{Qr=xP("typescript")}catch{Qr=pm()?.ts??null}return Qr}function EP(e,t,n){let i=eo(n),r={target:e.ScriptTarget.ESNext,module:e.ModuleKind.NodeNext,moduleResolution:e.ModuleResolutionKind.NodeNext,skipLibCheck:!0,noResolve:!0},o=e.createSourceFile(i,t,r.target,!0,wP(e,i)),s=e.createCompilerHost(r,!0),a=s.getSourceFile.bind(s),l=s.readFile.bind(s),c=s.fileExists.bind(s);return s.getSourceFile=(u,d,m,f)=>eo(u)===i?o:a(u,d,m,f),s.readFile=u=>eo(u)===i?t:l(u),s.fileExists=u=>eo(u)===i||c(u),e.createProgram([i],r,s)}function wP(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 IP(e,t,n){let i=[],r=o=>{if(Bh(e,o)){let s=t.getLineAndCharacterOfPosition(o.getStart(t)).line,a=t.getLineAndCharacterOfPosition(o.getEnd()).line;(!n||s<=n.endLine&&a>=n.startLine)&&i.push(o)}o.forEachChild(r)};return t.forEachChild(r),i.sort((o,s)=>o.getStart(t)-s.getStart(t))}function Bh(e,t){return e.isFunctionLike(t)&&"body"in t&&t.body!==void 0}function LP(e,t){return`callable:${encodeURIComponent(e.fileName)}:${t.getStart(e)}:${t.getEnd()}`}function DP(e,t,n){for(let i=t.parent;i;i=i.parent)if(Bh(e,i)&&n.has(i))return n.get(i);return null}function PP(e,t,n,i){let r=new Map,o=Ze(e,r,"exit",null),s=t.body,a=o.id;if(s&&e.ts.isBlock(s))a=Uc(e,r,[...s.statements],o.id,{breakTarget:null,continueTarget:null});else if(s){let c=Ze(e,r,"statement",s);_e(r,c.id,o.id),a=c.id}let l=Ze(e,r,"entry",t);return _e(r,l.id,a),{id:i,node:t,parentId:n,cfg:r,entryId:l.id,exitId:o.id}}function Uc(e,t,n,i,r){let o=i;for(let s=n.length-1;s>=0;s-=1)o=vi(e,t,n[s],o,r);return o}function vi(e,t,n,i,r){let o=e.ts;if(o.isBlock(n))return Uc(e,t,[...n.statements],i,r);if(o.isIfStatement(n)){let a=Ze(e,t,"predicate",n.expression),l=vi(e,t,n.thenStatement,i,r),c=n.elseStatement?vi(e,t,n.elseStatement,i,r):i;return _e(t,a.id,l),_e(t,a.id,c),a.id}if(o.isWhileStatement(n)){let a=Ze(e,t,"predicate",n.expression),l=vi(e,t,n.statement,a.id,{breakTarget:i,continueTarget:a.id});return _e(t,a.id,l),_e(t,a.id,i),a.id}if(o.isDoStatement(n)){let a=Ze(e,t,"predicate",n.expression),l=vi(e,t,n.statement,a.id,{breakTarget:i,continueTarget:a.id});return _e(t,a.id,l),_e(t,a.id,i),l}if(o.isForStatement(n)){let a=Ze(e,t,"predicate",n.condition??n),l=n.incrementor?Ze(e,t,"statement",n.incrementor):null;l&&_e(t,l.id,a.id);let c=l?.id??a.id,u=vi(e,t,n.statement,c,{breakTarget:i,continueTarget:c});if(_e(t,a.id,u),n.condition&&_e(t,a.id,i),!n.initializer)return a.id;let d=Ze(e,t,"statement",n.initializer);return _e(t,d.id,a.id),d.id}if(o.isForInStatement(n)||o.isForOfStatement(n)){e.unsupported.add("for-in/for-of iterator assignment is conservatively represented without iterable element flow.");let a=Ze(e,t,"predicate",n.expression),l=Ze(e,t,"statement",n.initializer),c=vi(e,t,n.statement,a.id,{breakTarget:i,continueTarget:a.id});return _e(t,a.id,l.id),_e(t,a.id,i),_e(t,l.id,c),a.id}if(o.isSwitchStatement(n)){e.unsupported.add("switch fallthrough is represented conservatively; discriminant-to-case value refinement is unsupported.");let a=Ze(e,t,"predicate",n.expression),l=i,c=[];for(let u=n.caseBlock.clauses.length-1;u>=0;u-=1){let d=n.caseBlock.clauses[u];l=Uc(e,t,[...d.statements],l,{...r,breakTarget:i}),c.push(l)}for(let u of c)_e(t,a.id,u);return _e(t,a.id,i),a.id}if(o.isReturnStatement(n)||o.isThrowStatement(n)){let a=Ze(e,t,"statement",n),l=[...t.values()].find(c=>c.kind==="exit");return _e(t,a.id,l.id),a.id}if(o.isBreakStatement(n)){let a=Ze(e,t,"statement",n);return r.breakTarget||e.unsupported.add("A break statement could not be attached to a structured target."),_e(t,a.id,r.breakTarget??i),a.id}if(o.isContinueStatement(n)){let a=Ze(e,t,"statement",n);return r.continueTarget||e.unsupported.add("A continue statement could not be attached to a structured target."),_e(t,a.id,r.continueTarget??i),a.id}if(o.isTryStatement(n)){e.unsupported.add("Exceptional control-flow and finally completion are not included in the local compiler CFG.");let a=Ze(e,t,"statement",n);return a.invalidatesAllDefinitions=!0,_e(t,a.id,i),a.id}let s=Ze(e,t,"statement",n);return _e(t,s.id,i),s.id}function Ze(e,t,n,i){let r={id:`cfg:${e.nextCfgId++}`,kind:n,ast:i,successors:new Set,predecessors:new Set,definitions:[],uses:[],displayPoint:null,invalidatesAllDefinitions:!1};return t.set(r.id,r),r}function _e(e,t,n){e.get(t).successors.add(n),e.get(n).predecessors.add(t)}function TP(e,t){let n=t.cfg.get(t.entryId);for(let i of t.node.parameters){let r=Ci(e,i.name);if(!r){e.unsupported.add("Destructured parameter definition-use is not implemented.");continue}n.definitions.push({point:xi(e,r.node,"parameter-definition",r.symbolKey,r.name,t.id),rhsUseIds:[]})}for(let i of t.cfg.values())!i.ast||i.kind==="entry"||i.kind==="exit"||(i.kind==="predicate"&&(i.displayPoint=xi(e,i.ast,"predicate",null,"predicate",t.id)),FP(e,t,i,i.ast),!i.displayPoint&&i.definitions.length===0&&i.uses.length===0&&(i.displayPoint=xi(e,i.ast,"statement",null,HP(e,i.ast),t.id)))}function FP(e,t,n,i){let r=e.ts;if(r.isTryStatement(i))return;let o=s=>{if(!(s!==i&&r.isFunctionLike(s))){if(r.isVariableDeclaration(s)){let a=s.initializer?ra(e,t.id,s.initializer,n):[];n.uses.push(...a);let l=Ci(e,s.name);l?n.definitions.push({point:xi(e,l.node,"definition",l.symbolKey,l.name,t.id),rhsUseIds:a.map(c=>c.point.id)}):(n.invalidatesAllDefinitions=!0,e.unsupported.add("Destructured variable reaching definitions are not implemented."));return}if(r.isBinaryExpression(s)&&jh(r,s.operatorToken.kind)){let a=ra(e,t.id,s.right,n);s.operatorToken.kind!==r.SyntaxKind.EqualsToken&&a.push(...ra(e,t.id,s.left,n)),n.uses.push(...a);let l=Ci(e,s.left);l?n.definitions.push({point:xi(e,l.node,"definition",l.symbolKey,l.name,t.id),rhsUseIds:a.map(c=>c.point.id)}):(n.invalidatesAllDefinitions=!0,e.unsupported.add("Dynamic or destructured assignment targets are not included in reaching definitions."));return}if((r.isPrefixUnaryExpression(s)||r.isPostfixUnaryExpression(s))&&(s.operator===r.SyntaxKind.PlusPlusToken||s.operator===r.SyntaxKind.MinusMinusToken)){let a=ra(e,t.id,s.operand,n);n.uses.push(...a);let l=Ci(e,s.operand);l&&n.definitions.push({point:xi(e,l.node,"definition",l.symbolKey,l.name,t.id),rhsUseIds:a.map(c=>c.point.id)});return}if(!(r.isFunctionDeclaration(s)||r.isClassDeclaration(s)||r.isInterfaceDeclaration(s))){if(Oh(e,s)){let a=$h(e,t.id,s);a&&n.uses.push(a),r.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}}};o(i),n.uses=Hh(n.uses)}function ra(e,t,n,i){let r=[],o=s=>{if(!e.ts.isFunctionLike(s)){if(e.ts.isBinaryExpression(s)&&jh(e.ts,s.operatorToken.kind)){i.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(Oh(e,s)){let a=$h(e,t,s);a&&r.push(a),e.ts.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}};return o(n),Hh(r)}function Oh(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&&MP(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)||AP(e.ts,t))}function MP(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 AP(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 $h(e,t,n){let i=Ci(e,n);return i?{point:xi(e,i.node,"use",i.symbolKey,i.name,t),property:e.ts.isPropertyAccessExpression(n)}:null}function Ci(e,t){let n=e.ts;if(n.isIdentifier(t)){let i=kh(e,t);return i?{node:t,symbolKey:i,name:t.text}:null}if(n.isPropertyAccessExpression(t)){let i=kh(e,t.name);return i?{node:t,symbolKey:i,name:t.getText(e.sourceFile)}:null}return n.isParenthesizedExpression(t)||n.isAsExpression(t)||n.isTypeAssertionExpression(t)||n.isNonNullExpression(t)?Ci(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 kh(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 i=n.valueDeclaration??n.declarations?.[0];return i?`symbol:${encodeURIComponent(i.getSourceFile().fileName)}:${i.getStart()}:${n.getName()}`:`symbol:${n.getName()}`}function xi(e,t,n,i,r,o){let s=t.getStart(e.sourceFile),a=t.getEnd(),l=e.sourceFile.getLineAndCharacterOfPosition(s),c=`flow-point:${encodeURIComponent(e.sourceFile.fileName)}:${s}:${a}:${n}:${encodeURIComponent(i??r)}`,u=e.points.get(c);if(u)return u;let d={id:c,kind:n,name:r,symbolKey:i,callableId:o,start:s,end:a,line:l.line,column:l.character,node:t};return e.points.set(c,d),d}function NP(e,t){let n=[...t.cfg.values()].flatMap(l=>l.definitions),i=new Map(n.map(l=>[l.point.id,l])),r=kP(n),o=new Map,s=new Map;for(let l of t.cfg.values())o.set(l.id,new Set),s.set(l.id,new Set);let a=!0;for(;a;){a=!1;for(let l of t.cfg.values()){let c=zP([...l.predecessors].map(m=>s.get(m))),u=new Set(c);l.invalidatesAllDefinitions&&u.clear();let d=_P(l.definitions);for(let m of d){for(let f of r.get(m.point.symbolKey)??[])u.delete(f.point.id);u.add(m.point.id)}zc(o.get(l.id),c)||(o.set(l.id,c),a=!0),zc(s.get(l.id),u)||(s.set(l.id,u),a=!0)}}for(let l of t.cfg.values()){let c=o.get(l.id);for(let u of l.uses){let d=l.definitions.filter(f=>f.point.symbolKey===u.point.symbolKey&&f.point.start<u.point.start&&!f.rhsUseIds.includes(u.point.id)).sort((f,p)=>p.point.start-f.point.start)[0],m=d?[d.point.id]:c;for(let f of m){let p=i.get(f);p.point.symbolKey===u.point.symbolKey&&to(e,"reaching-definition",p.point.id,u.point.id,"exact","A CFG path reaches this use without an intervening definition.")}}for(let u of l.definitions)for(let d of u.rhsUseIds)to(e,"value-source",d,u.point.id,"exact","This right-hand-side use supplies the new definition.")}}function kP(e){let t=new Map;for(let n of e){if(!n.point.symbolKey)continue;let i=t.get(n.point.symbolKey)??[];i.push(n),t.set(n.point.symbolKey,i)}return t}function _P(e){let t=new Map;for(let n of e)n.point.symbolKey&&t.set(n.point.symbolKey,n);return[...t.values()]}function BP(e,t){let n=OP(t);for(let i of t.cfg.values()){if(i.successors.size<2||!i.displayPoint)continue;let r=n.get(i.id);for(let o of i.successors)for(let s of n.get(o)??[]){if(r.has(s)||s===t.exitId)continue;let a=t.cfg.get(s),l=[...a.definitions.map(c=>c.point),...a.uses.map(c=>c.point),...a.displayPoint?[a.displayPoint]:[]];for(let c of UP(l))to(e,"control-dependence",i.displayPoint.id,c.id,"exact","The target postdominates a branch successor but does not postdominate the predicate.")}}}function OP(e){let t=[...e.cfg.keys()],n=new Set(t),i=new Map;for(let o of t)i.set(o,o===e.exitId?new Set([o]):new Set(n));let r=!0;for(;r;){r=!1;for(let o of e.cfg.values()){if(o.id===e.exitId)continue;let s=[...o.successors].map(l=>i.get(l)),a=new Set([o.id,...GP(s)]);zc(i.get(o.id),a)||(i.set(o.id,a),r=!0)}}return i}function $P(e,t){let n=new Map(t.map(s=>[s.id,s.parentId])),i=t.flatMap(s=>[...s.cfg.values()].flatMap(a=>a.definitions.map(l=>l.point))),r=new Map;for(let s of i){if(!s.symbolKey)continue;let a=r.get(s.symbolKey)??[];a.push(s),r.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(l=>l.uses)){if(!a.point.symbolKey||o.has(a.point.id))continue;let l=r.get(a.point.symbolKey)??[];for(let c of l)jP(c.callableId,a.point.callableId,n)?to(e,"closure-capture",c.id,a.point.id,"candidate","Compiler identity proves the captured binding, but invocation order can select among outer definitions."):a.property&&to(e,"field-definition-to-use",c.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 jP(e,t,n){for(let i=n.get(t)??null;i;i=n.get(i)??null)if(i===e)return!0;return!1}function to(e,t,n,i,r,o){let s=`local-flow-edge:${t}:${encodeURIComponent(n)}:${encodeURIComponent(i)}`;e.edges.set(s,{id:s,kind:t,fromPointId:n,toPointId:i,strength:r,reason:o})}function jh(e,t){return t>=e.SyntaxKind.FirstAssignment&&t<=e.SyntaxKind.LastAssignment}function HP(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 Hh(e){return[...new Map(e.map(t=>[t.point.id,t])).values()]}function UP(e){return[...new Map(e.map(t=>[t.id,t])).values()]}function zP(e){return new Set(e.flatMap(t=>[...t]))}function GP(e){return e.length===0?new Set:new Set([...e[0]].filter(t=>e.slice(1).every(n=>n.has(t))))}function zc(e,t){return e.size===t.size&&[...e].every(n=>t.has(n))}function KP(e,t){return e.start-t.start||e.kind.localeCompare(t.kind)||e.id.localeCompare(t.id)}function Hc(e){return{points:[],edges:[],coverage:{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:[e]}}}var WP=Fi("typescript-local-flow",{clearGroups:["whole-project","source-file","semantic-provider"]});function Gc(e,t,n,i){if(!Xo(t))return null;let r=`${t}\0${n}\0${i}`;return WP.get(e,r,()=>{let o=se(e,t);return o?_h(o,qP(e.config.projectRoot,t),{startLine:n,endLine:i}):{points:[],edges:[],coverage:{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:[`Current source is unavailable for ${t}.`]}}})}function VP(e,t=new Map){let n=new Map,i=new Map,r=[];for(let o of e.transfers){if(!e.caller)continue;let s=oa(e.caller,o.callerPosition),a=oa(e.callee,o.calleePosition);no(n,s),no(n,a),qc(i,e.caller,s),qc(i,e.callee,a);let l=dt("edge","data-transfer",o.proof.file,String(o.proof.startLine),String(o.callerPosition),String(o.calleePosition));i.set(l,{id:l,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=oa(e.callee,o.calleePosition);no(n,a),qc(i,e.callee,a);let l=t.get(o.calleePosition);if(l&&oT(l)){rT(i,n,e,o.calleePosition,o.argumentText,l);return}let c=nT(e,o.calleePosition,o.argumentText);no(n,c);let u=dt("edge","data-transfer-unsupported",o.proof.file,String(o.proof.startLine),String(o.calleePosition),String(s));i.set(u,{id:u,kind:"data-transfer",fromNodeId:c.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}}]}),r.push({id:dt("frontier","data-transfer",u),kind:"data-transfer",direction:"unresolved",fromNodeIds:[c.id],edgeIds:[u],memberNodeIds:[a.id],memberCount:1,disposition:"unsupported",reason:l?.derivation.rule??o.reason,expansion:null})}),{nodes:[...n.values()],edges:[...i.values()],frontiers:r,blindSpots:[]}}function zh(e,t,n=[]){let i=Gh(),r=new Map,o=new Set;for(let s of t){if(s.kind!=="call"||!s.fromSymbol||!s.toSymbol||s.line===null)continue;let a=tT(r,e,s.toFile,s.toSymbol);if(!a)continue;let l=Nm(e,a),c=l.sites.filter(g=>g.file===s.fromFile&&g.startLine<=s.line&&g.endLine>=s.line&&g.caller?.symbol===s.fromSymbol);if(c.length!==1){let g=l.unresolved.find(h=>h.file===s.fromFile&&h.line===s.line);g&&i.blindSpots.push(`Parameter flow unresolved at ${s.fromFile}:${s.line+1}: ${g.reason}.`);continue}let u=c[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=km(e,u),f=ae(e,u.file)?.rootNode,p=new Map;if(f)for(let g of m.unknown){let h=xm({db:e,file:u.file,root:f},u.arguments[g.calleePosition]);h&&p.set(g.calleePosition,h)}Uh(i,VP(m,p)),m.caller&&QP(u.callNode)&&eT(i,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,l=Gc(e,s.location.file,s.location.line,a);if(l){Uh(i,JP(s,l.points,l.edges));for(let c of l.coverage.unsupported)i.blindSpots.push(`TypeScript local flow is partial for ${s.location.file}:${s.location.line+1}-${a+1}: ${c} Recover with: codebaseiq inspect --at '${s.location.file}:${s.location.line+1}-${a+1}' --view behavior.`)}}return i.blindSpots=[...new Set(i.blindSpots)].sort(),i}function JP(e,t,n){let i=Gh(),r=new Map,o=new Map,s=new Map,a=e.location.file;for(let l of t){let c=YP(e,a,l);s.set(l.id,c.id),r.set(c.id,c),XP(o,e,c)}for(let l of n){let c=s.get(l.fromPointId),u=s.get(l.toPointId);if(!c||!u)continue;let d=ZP(l),m=dt("edge","typescript-local-flow",a,l.id);o.set(m,{id:m,kind:l.kind==="control-dependence"?"control-dependence":"data-transfer",fromNodeId:c,toNodeId:u,directed:!0,disposition:"folded",semantics:[d],evidence:[{method:"typescript-compiler-cfg-reaching-definitions",strength:l.strength,identity:l.reason,location:r.get(c)?.location??e.location}]})}return i.nodes=[...r.values()],i.edges=[...o.values()],i}function YP(e,t,n){return{id:dt("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 XP(e,t,n){let i=dt("edge","local-flow-owner",t.id,n.id);e.has(i)||e.set(i,{id:i,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 ZP(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 QP(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 eT(e,t,n){if(!t.caller)return;let i={id:dt("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}},r=dt("edge","return-to-call-result",t.callee.symbol,i.id),o=dt("edge","call-result-owner",t.caller.symbol,i.id);e.nodes.push(i),e.edges.push({id:r,kind:"data-transfer",fromNodeId:Wc(t.callee.symbol),toNodeId:i.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:i.location}]},{id:o,kind:"call-result-owner",fromNodeId:Wc(t.caller.symbol),toNodeId:i.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:i.location}]})}function Gh(){return{nodes:[],edges:[],frontiers:[],blindSpots:[]}}function Uh(e,t){Kc(e.nodes,t.nodes),Kc(e.edges,t.edges),Kc(e.frontiers,t.frontiers),e.blindSpots.push(...t.blindSpots)}function Kc(e,t){let n=new Set(e.map(i=>i.id));for(let i of t)n.has(i.id)||(n.add(i.id),e.push(i))}function tT(e,t,n,i){let r=`${n}\0${i}`,o=e.get(r);if(o!==void 0)return o;let s=J(t,n).find(a=>a.symbol===i)??null;return e.set(r,s),s}function oa(e,t){return{id:lT(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 nT(e,t,n){return{id:dt("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 iT(e,t,n){return{id:dt("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 rT(e,t,n,i,r,o){let s=iT(n,i,o),a=oa(n.callee,i);no(t,s);let l=dt("edge","static-value-transfer",n.call.file,String(n.call.startLine),String(i));e.set(l,{id:l,kind:"data-transfer",fromNodeId:s.id,toNodeId:a.id,directed:!0,disposition:"folded",semantics:[{family:"data",subtype:sT(o),attributes:{argumentText:r,calleePosition:i,value:o.value,precision:o.precision,derivationRule:o.derivation.rule}}],evidence:aT(o,n)})}function oT(e){return e.derivation.kind!=="heuristic"&&e.precision!=="symbolic"&&e.precision!=="unknown"}function sT(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 aT(e,t){return(e.derivation.sourceSpans.length>0?e.derivation.sourceSpans:[t.call]).map(i=>({method:`static-value:${e.derivation.rule}`,strength:e.derivation.kind==="direct"?"exact":"derived",identity:e.derivation.inputFactIds.join(",")||e.value,location:{file:i.file,line:i.startLine,endLine:i.endLine}}))}function no(e,t){e.has(t.id)||e.set(t.id,t)}function qc(e,t,n){let i=dt("edge","parameter-owner",t.symbol,n.id);e.has(i)||e.set(i,{id:i,kind:"parameter-owner",fromNodeId:Wc(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 lT(e,t){return dt("parameter",e,String(t))}function Wc(e){return dt("symbol",e)}function dt(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function Kh(e,t){let n=new Map,i=new Map,r=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,l=vf(e,s.location.file,s.location.line,a);if(!l){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 c of l.facts){let u=Vc(s,c.controller),d=Vc(s,c.outcome);n.set(u.id,u),n.set(d.id,d),cT(i,s,u);let m=Ri("edge","control-dependence",u.id,d.id,c.subtype);i.set(m,{id:m,kind:"control-dependence",fromNodeId:u.id,toNodeId:d.id,directed:!0,disposition:"folded",semantics:[{family:"control",subtype:c.subtype,attributes:{...c.attributes}}],evidence:[{method:"parser-control-dependence",strength:"exact",identity:`${s.location.file}:${c.controller.startLine+1}-${c.outcome.startLine+1}`,location:{file:s.location.file,line:c.controller.startLine,endLine:c.controller.endLine}}]})}for(let c of l.terminals){let u=Vc(s,c);n.set(u.id,u);let d=c.label.startsWith("throw")||c.label.startsWith("raise")?"throw":"return",m=Ri("edge","control-terminal",s.id,u.id,d);i.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:c.label,location:{file:s.location.file,line:c.startLine,endLine:c.endLine}}]})}for(let c of l.unsupported){let u=Ri("control-unsupported",s.location.file,String(c.startLine),String(c.endLine),c.reason);n.set(u,{id:u,kind:"control-unsupported",label:c.reason,disposition:"unsupported",location:{file:s.location.file,line:c.startLine,endLine:c.endLine},anchorIds:[],attributes:{ownerNodeId:s.id}});let d=Ri("edge","control-unsupported",s.id,u);i.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:c.reason,location:{file:s.location.file,line:c.startLine,endLine:c.endLine}}]});let m=Ri("frontier","control-dependence",u);r.set(m,{id:m,kind:"control-dependence",direction:"unresolved",fromNodeIds:[s.id],edgeIds:[d],memberNodeIds:[u],memberCount:1,disposition:"unsupported",reason:c.reason,expansion:null})}}return{nodes:[...n.values()],edges:[...i.values()],frontiers:[...r.values()],blindSpots:[...o].sort()}}function Vc(e,t){let n=e.location.file;return{id:Ri(`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 cT(e,t,n){let i=Ri("edge","control-owner",t.id,n.id);e.has(i)||e.set(i,{id:i,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 Ri(...e){return e.map(t=>encodeURIComponent(t)).join(":")}var sa=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"]),ro=new Set(["block","body","compound_statement","declaration_list","statement_block"]),uT=new Set(["assignment","assignment_expression","augmented_assignment_expression"]),Yc=new Set(["update_expression"]),Jh=new Set(["array_access","element_access_expression","subscript_expression"]),Yh=new Set(["attribute","field_access","field_expression","member_access_expression","member_expression","selector_expression"]),dT=new Set(["false","null","null_literal","number","number_literal","string","string_literal","template_string","true"]),mT=new Set(["call_expression","method_invocation","object_creation_expression"]),fT=new Set(["comment","else_clause","formal_parameters","parameters","type_parameters"]);function Xh(e,t,n,i){let r=ae(e,t);if(!r)return null;let o=CT(r.rootNode,n,i);if(!o)return null;let s=[],a=[],l=[];return Ei(o,c=>{if(uT.has(c.type)||Yc.has(c.type)||Qh(c)){let u=pT(c);u?s.push(u):l.push({family:"state",startLine:c.startPosition.row,endLine:c.endPosition.row,reason:`Mutation target ${sn(c.text)} could not be resolved to an exact source resource.`})}}),Ei(o,c=>{if(!ro.has(c.type))return;let u=ST(c);for(let d=0;d<u.length-1;d+=1)a.push({from:io(u[d]),to:io(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],f=RT(m).filter(p=>p.type==="await_expression");for(let p of f){let g=oo("event",`await ${sn(p.text.replace(/^await\s+/u,""))}`,p);a.push({from:io(m),to:g,subtype:"awaits-completion",synchronizationScope:null,attributes:{completionRequired:!0}});let h=u[d+1];h&&a.push({from:g,to:io(h),subtype:"await-completion-before",synchronizationScope:null,attributes:{continuationOnly:!0}})}}}),Ei(o,c=>{if(c.type!=="synchronized_statement")return;let u=c.childForFieldName("object")??c.childForFieldName("condition")??c.namedChildren.find(g=>!ro.has(g.type)),d=c.childForFieldName("body")??c.namedChildren.find(g=>ro.has(g.type));if(!u||!d){l.push({family:"temporal",startLine:c.startPosition.row,endLine:c.endPosition.row,reason:"Synchronized scope has no structurally resolved monitor or body."});return}let m=sn(u.text).replace(/^\(|\)$/gu,""),f=oo("lock",m,u),p=xT(d).filter(g=>g.parent!==null&&ey(g));for(let g of vT(p))a.push({from:f,to:io(g),subtype:"inside-lock-scope",synchronizationScope:m,attributes:{syntaxNative:!0}})}),{mutations:s,temporal:a,unsupported:l}}function pT(e){let t=Qh(e),n=e.childForFieldName("left")??e.childForFieldName("argument")??(t?e.namedChildren.at(-1)??null:e.namedChildren[0]??null);if(!n)return null;let i=gT(n);if(!i)return null;let r=t?"delete":Yc.has(e.type)||!bT(e,n).startsWith("=")?"update":"assign",o=t||Yc.has(e.type)?null:e.childForFieldName("right");return{event:oo("event",sn(e.text),e),resource:{kind:"resource",label:i.name,startLine:n.startPosition.row,endLine:n.endPosition.row},operation:r,durabilityClass:"in-memory",recordIdentity:i.recordIdentity,value:o?oo("value",sn(o.text),o):null,dataSubtype:o?hT(o,e):null}}function gT(e){if(Jh.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:`${sn(t.text)}[]`,recordIdentity:sn(n.text)}}return Yh.has(e.type)?{name:sn(e.text),recordIdentity:null}:/^(?:identifier|property_identifier|field_identifier)$/u.test(e.type)?{name:sn(e.text),recordIdentity:null}:null}function hT(e,t){return dT.has(e.type)||/(?:integer|float|decimal|boolean|character)_literal$/u.test(e.type)?"constant-to-state":mT.has(e.type)?"return-to-state":Yh.has(e.type)||Jh.has(e.type)?"property-to-state":/identifier$/u.test(e.type)?yT(e.text,t)?"captured-value-to-state":"value-to-state":"expression-to-state"}function yT(e,t){let n=Jc(t.parent);if(!n||qh(n,e))return!1;let i=Jc(n.parent);for(;i;){if(qh(i,e))return!0;i=Jc(i.parent)}return!1}function Jc(e){let t=e;for(;t;){if(sa.has(t.type))return t;t=t.parent}return null}function qh(e,t){let n=e.childForFieldName("parameters")??e.namedChildren.find(o=>["formal_parameters","parameters"].includes(o.type));if(n&&Wh(n,t))return!0;let i=e.childForFieldName("body")??e.namedChildren.find(o=>ro.has(o.type));if(!i)return!1;let r=!1;return Zh(i,e,o=>{if(r||!/(?:declarator|declaration|parameter)$/u.test(o.type))return;let s=o.childForFieldName("name")??o.childForFieldName("pattern")??o.namedChildren[0];s&&Wh(s,t)&&(r=!0)}),r}function Wh(e,t){let n=!1;return Ei(e,i=>{/identifier$/u.test(i.type)&&i.text===t&&(n=!0)}),n}function Zh(e,t,n){n(e);for(let i of e.namedChildren)i!==t&&sa.has(i.type)||Zh(i,t,n)}function bT(e,t){let n=e.childForFieldName("right"),i=Math.max(0,t.endIndex-e.startIndex),r=n?Math.max(i,n.startIndex-e.startIndex):e.text.length;return e.text.slice(i,r).trim()}function Qh(e){return(e.type==="delete_expression"||e.type==="unary_expression")&&/^delete\b/u.test(e.text.trim())}function ST(e){return e.namedChildren.filter(t=>ey(t))}function ey(e){return fT.has(e.type)||ro.has(e.type)?!1:/(?:statement|declaration)$/u.test(e.type)||e.type==="expression_statement"||e.type==="local_variable_declaration"}function vT(e){let t=new Set(e);return e.filter(n=>{let i=n.parent;for(;i;){if(t.has(i))return!1;i=i.parent}return!0})}function io(e){return oo("event",sn(e.text),e)}function oo(e,t,n){return{kind:e,label:t,startLine:n.startPosition.row,endLine:n.endPosition.row}}function CT(e,t,n){let i=[];return Ei(e,o=>{o.startPosition.row<=t&&o.endPosition.row>=n&&i.push(o)}),i.filter(o=>sa.has(o.type)).sort(Vh)[0]??i.sort(Vh)[0]??null}function Vh(e,t){return e.endIndex-e.startIndex-(t.endIndex-t.startIndex)||e.startIndex-t.startIndex}function xT(e){let t=[];return Ei(e,n=>t.push(n)),t}function RT(e){let t=[],n=i=>{t.push(i);for(let r of i.namedChildren)r!==e&&sa.has(r.type)||n(r)};return n(e),t}function Ei(e,t){t(e);for(let n of e.namedChildren)Ei(n,t)}function sn(e){return e.trim().replace(/\s+/gu," ")}function iy(e,t,n=[]){let i=new Map,r=new Map,o=new Map,s=new Set;for(let a of t){if(!a.location||!["source-construct","symbol"].includes(a.kind))continue;let l=a.location.endLine??a.location.line,c=Xh(e,a.location.file,a.location.line,l);if(!c){s.add(`State and temporal analysis unavailable for ${a.location.file}:${a.location.line+1}-${l+1}: no supported syntax tree or covering construct.`);continue}for(let u of c.mutations){let d=la(a,u.event),m=PT(a,u.resource,u.durabilityClass);if(i.set(d.id,d),i.set(m.id,m),ca(r,a,d,"contains-state-effect"),ua(r,{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 f=la(a,u.value);i.set(f.id,f),ua(r,{kind:"data-to-state",from:f,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 c.temporal){let d=la(a,u.from),m=la(a,u.to);i.set(d.id,d),i.set(m.id,m),ca(r,a,d,u.from.kind==="lock"?"contains-lock-scope":"contains-event"),ca(r,a,m,"contains-event"),ua(r,{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 c.unsupported){let d=Ln(`${u.family}-unsupported`,a.location.file,String(u.startLine),String(u.endLine),u.reason);i.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=Ln("edge",`${u.family}-unsupported`,a.id,d);r.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 f=Ln("frontier",u.family,d);o.set(f,{id:f,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(l=>l.kind==="runtime-boundary-participant")){let l=aa(a,"protocol"),c=aa(a,"action"),u=aa(a,"address")??a.label;!l||!c||!ny(l,c)||ty(i,r,a,{observationId:a.id,action:c,strength:"exact",file:a.location?.file??"",line:a.location?.line??0,address:u,protocol:l,role:aa(a,"role")??void 0,resolution:"locally-linked"})}for(let a of n){if(!a.protocol||!ny(a.protocol,a.action))continue;let l=LT(t,a.file,a.line,a.ownerShortName??null);if(!l){s.add(`State observation ${a.observationId} at ${a.file}:${a.line+1} has no materialized owner node.`);continue}ty(i,r,l,a)}return{nodes:[...i.values()],edges:[...r.values()],frontiers:[...o.values()],blindSpots:[...s].sort()}}function ty(e,t,n,i){let r=wT(i),s={id:Ln("runtime-state-event",i.observationId),kind:"runtime-state-event",label:`${i.action} ${r}`,disposition:"folded",location:{file:i.file,line:i.line},anchorIds:[],attributes:{action:i.action,protocol:i.protocol??null,modality:i.modality??null,resolution:i.resolution??null}},a=i.protocol==="database"?"external-durable-intent":"external",l={id:Ln("runtime-state-resource",i.protocol??"unknown",r),kind:"runtime-state-resource",label:r,disposition:"folded",location:{file:i.file,line:i.line},anchorIds:[],attributes:{protocol:i.protocol??null,durabilityClass:a}};e.set(s.id,s),e.set(l.id,l),ca(t,n,s,"contains-runtime-state-effect");let c=ET(i.action);ua(t,{kind:"runtime-state-resource",from:s,to:l,semantics:[{family:"state",subtype:c,context:{crossesRuntimeBoundary:!0,protocol:i.protocol},attributes:{operation:i.action,durabilityClass:a,resource:r,recordIdentity:IT(i),modality:i.modality??null,resolution:i.resolution??null,transactionMembership:"unknown",commitState:i.protocol==="database"?"unknown":null}}],method:`runtime-boundary-${i.strength}`,identity:i.observationId})}function ET(e){return e==="database.read"?"reads-resource":e==="queue.send"?"enqueues-resource":e==="queue.consume"?"consumes-resource":"writes-resource"}function wT(e){return(e.keyParts?.find(n=>["address","resource"].includes(n.name))?.value??e.address)||e.observationId}function IT(e){return e.keyParts?.find(n=>/^(?:id|key|record)$/u.test(n.name))?.value??null}function ny(e,t){return e==="database"&&["database.read","database.write"].includes(t)||e==="queue"&&["queue.consume","queue.send"].includes(t)}function aa(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function LT(e,t,n,i){let r=e.filter(s=>s.location?.file===t&&["source-construct","symbol"].includes(s.kind)),o=r.filter(s=>s.location.line<=n&&(s.location.endLine??s.location.line)>=n).sort(DT)[0];if(o)return o;if(i){let s=r.find(a=>a.label===i||a.label.endsWith(`.${i}`)||a.label.includes(i));if(s)return s}return r.length===1?r[0]:null}function DT(e,t){let n=(e.location?.endLine??e.location?.line??0)-(e.location?.line??0),i=(t.location?.endLine??t.location?.line??0)-(t.location?.line??0);return n-i}function la(e,t){let n=e.location.file;return{id:Ln(`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 PT(e,t,n){let i=e.location.file;return{id:Ln("program-resource",i,e.id,t.label,n),kind:"program-resource",label:t.label,disposition:"folded",location:{file:i,line:t.startLine,endLine:t.endLine},anchorIds:[],attributes:{ownerNodeId:e.id,durabilityClass:n}}}function ca(e,t,n,i){let r=Ln("edge","program-owner",t.id,n.id,i);e.has(r)||e.set(r,{id:r,kind:"program-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:i}],evidence:[{method:"parser-program-owner",strength:"exact",identity:t.id,location:n.location}]})}function ua(e,t){let n=Ln("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 Ln(...e){return e.map(t=>encodeURIComponent(t)).join(":")}var TT=new Set(["control","data","state","temporal"]),da=new Set(["contains-control","contains-event","contains-lock-scope","contains-state-effect","contains-runtime-state-effect","contains","owns-parameter","owns-runtime-observation"]),ay=new Set(["discriminator-dispatch","result-callback","returns","runtime-handoff","throws"]);function ly(e,t={}){let n=new Map(e.nodes.map(C=>[C.id,C])),i=BT(e.nodes,t.focusLocations),r=OT(e.edges,t.focusLocations),o=$T(e.edges,r),s=new Set(e.paths.flatMap(C=>C.edgeIds)),a=Dn(e.anchors.filter(C=>C.status==="matched").flatMap(C=>C.nodeIds)),c=e.edges.filter(sy).filter(C=>FT(C,i,r,s)),u=c.filter(C=>kT(C,i,r,o,n,s)),d=ry(a,u,"forward"),m=NT(d,u),f=ry(m,u,"backward"),p=new Set([...d].filter(C=>f.has(C)));for(let C of a)p.add(C);let g=new Set(u.filter(C=>p.has(C.fromNodeId)&&p.has(C.toNodeId)).map(C=>C.id)),h=new Set(p),S=new Set(g);MT(c,h,S,i,r);let v=e.frontiers.filter(C=>HT(C,h)),y=Dn(v.filter(C=>C.disposition==="unsupported").map(C=>C.id)),E=Dn(e.edges.filter(C=>!sy(C)&&uy(C)&&jT(C,h)).map(C=>C.id)),w=Dn(v.map(C=>C.id)),b=[];a.length===0&&b.push("No matched anchor node starts the corridor."),m.length===0&&b.push("No proved mechanical outcome is reachable from a matched anchor."),y.length>0&&b.push(`${y.length} unsupported frontier(s) touch the protected corridor.`),E.length>0&&b.push(`${E.length} candidate or unknown edge(s) touch the protected corridor.`);let R=b.length===0?"complete":"incomplete";return{schemaVersion:1,status:R,startNodeIds:a,outcomeNodeIds:m,baseNodeIds:Dn([...p]),baseEdgeIds:Dn([...g]),nodeIds:Dn([...h]),edgeIds:Dn([...S]),accountedFrontierIds:w,unresolvedFrontierIds:y,unresolvedEdgeIds:E,coverage:{protectedNodes:h.size,protectedEdges:S.size,baseNodes:p.size,baseEdges:g.size,accountedFrontiers:w.length,unresolvedFrontiers:y.length,unresolvedEdges:E.length},explanation:R==="complete"?"Every proved anchor-to-outcome path is closed over its material causal facts within reported coverage.":b.join(" ")}}function FT(e,t,n,i){return t===null||e.disposition==="emitted"||i.has(e.id)||n?.has(e.id)===!0?!0:(e.semantics??[]).some(r=>{if(r.family==="identity"&&da.has(r.subtype))return t.has(e.toNodeId);if(r.family==="contract")return t.has(e.fromNodeId)&&t.has(e.toNodeId);if(r.family==="state")return t.has(e.fromNodeId);if(r.family==="data"||r.family==="temporal")return t.has(e.fromNodeId)||t.has(e.toNodeId);if(r.family==="control"){if(dy(r))return t.has(e.fromNodeId);if(["returns","throws"].includes(r.subtype))return t.has(e.toNodeId);if(r.subtype==="completion-callback")return t.has(e.fromNodeId)||t.has(e.toNodeId)}return!1})}function MT(e,t,n,i,r){let o=!0;for(;o;){o=!1;for(let s of e)AT(s,t,i,r)&&(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 AT(e,t,n,i){let r=t.has(e.fromNodeId),o=t.has(e.toNodeId);return!r&&!o?!1:(e.semantics??[]).some(s=>s.family==="identity"?da.has(s.subtype)&&(o||n===null||n.has(e.toNodeId)):s.family==="contract"?!0:s.family==="state"?r&&(n===null||n.has(e.fromNodeId)):s.family==="temporal"?s.subtype==="lexical-successor"?r&&o:!0:s.family==="data"?o&&(r||n===null||n.has(e.fromNodeId)||i?.has(e.id)===!0):s.family==="control"?cy(s)||["returns","throws"].includes(s.subtype)&&!o&&n!==null&&!n.has(e.toNodeId)?!1:ay.has(s.subtype)||dy(s)||s.subtype==="completion-callback":!1)}function NT(e,t){let n=new Set,i=new Map,r=new Map;for(let o of t)!e.has(o.fromNodeId)||!e.has(o.toNodeId)||(i.set(o.fromNodeId,(i.get(o.fromNodeId)??0)+1),r.set(o.toNodeId,(r.get(o.toNodeId)??0)+1),(o.semantics??[]).some(s=>s.family==="state"||s.family==="control"&&ay.has(s.subtype))&&n.add(o.toNodeId));for(let o of e)(r.get(o)??0)>0&&(i.get(o)??0)===0&&n.add(o);return Dn([...n])}function ry(e,t,n){let i=new Map;for(let s of t){let a=n==="forward"?s.fromNodeId:s.toNodeId,l=n==="forward"?s.toNodeId:s.fromNodeId,c=i.get(a)??[];c.push(l),i.set(a,c)}let r=new Set(e),o=[...e];for(;o.length>0;){let s=o.shift();for(let a of i.get(s)??[])r.has(a)||(r.add(a),o.push(a))}return r}function kT(e,t,n,i,r,o){return(e.semantics??[]).some(s=>e.disposition==="emitted"||o.has(e.id)?!0:s.family==="identity"&&da.has(s.subtype)?t===null||t.has(e.toNodeId)||i?.has(e.toNodeId)===!0:!TT.has(s.family)||cy(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"?_T(e,r)&&(t.has(e.fromNodeId)||t.has(e.toNodeId)):!1)}function cy(e){return e.family==="control"&&["call","discriminator-dispatch","result-callback","runtime-handoff"].includes(e.subtype)}function _T(e,t){let n=t.get(e.fromNodeId),i=t.get(e.toNodeId);if(!n||!i)return!1;let r=oy(n,"ownerNodeId")??(n.kind==="symbol"?n.id:null),o=oy(i,"ownerNodeId")??(i.kind==="symbol"?i.id:null);return r!==null&&r===o}function BT(e,t){if(!t)return null;let n=new Map;for(let i of t){let r=n.get(i.file)??[];r.push(i.line),n.set(i.file,r)}return new Set(e.filter(i=>{if(!i.location||i.kind==="parameter")return!1;let r=n.get(i.location.file)??[],o=i.location.endLine??i.location.line;return r.some(s=>s>=i.location.line&&s<=o)}).map(i=>i.id))}function OT(e,t){if(!t)return null;let n=new Map;for(let i of t){let r=n.get(i.file)??[];r.push(i.line),n.set(i.file,r)}return new Set(e.filter(i=>i.evidence.some(r=>{if(!r.location)return!1;let o=n.get(r.location.file)??[],s=r.location.endLine??r.location.line;return o.some(a=>a>=r.location.line&&a<=s)})).map(i=>i.id))}function $T(e,t){return t===null?null:new Set(e.filter(n=>t.has(n.id)).flatMap(n=>[n.fromNodeId,n.toNodeId]))}function oy(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function sy(e){return e.disposition==="excluded"||e.disposition==="unsupported"||!uy(e)?!1:e.evidence.some(t=>t.strength==="exact"||t.strength==="derived")}function uy(e){return(e.semantics??[]).some(t=>t.family!=="identity"||da.has(t.subtype))}function dy(e){return e.subtype.startsWith("predicate-")||e.subtype.startsWith("loop-")||e.subtype.startsWith("exception-")||e.subtype.startsWith("finally-")||e.subtype.startsWith("handler-")}function jT(e,t){return t.has(e.fromNodeId)||t.has(e.toNodeId)}function HT(e,t){return[...e.fromNodeIds,...e.memberNodeIds].some(n=>t.has(n))}function Dn(e){return[...new Set(e)].sort()}import{createHash as UT}from"crypto";var ma=["identity","contract","control","data","state","temporal"],zT=new Set(ma);function pa(e){let t=er(e.anchors,"anchor"),n=er(e.nodes,"node"),i=er(e.edges,"edge"),r=er(e.paths??[],"path"),o=er(e.frontiers??[],"frontier"),s=new Set(t.map(f=>f.id)),a=new Set(n.map(f=>f.id)),l=new Set(i.map(f=>f.id)),c=e.routeCatalog?{...e.routeCatalog,routes:er(e.routeCatalog.routes,"route"),selectedRouteIds:ht(e.routeCatalog.selectedRouteIds)}:void 0;for(let f of t)Rt(`anchor ${f.id}`,[...f.nodeIds,...f.candidateNodeIds],a,"node");for(let f of n)Rt(`node ${f.id}`,f.anchorIds,s,"anchor");for(let f of i){if(Rt(`edge ${f.id}`,[f.fromNodeId,f.toNodeId],a,"node"),f.evidence.length===0)throw new Error(`Exploration edge ${f.id} has no evidence source.`);qT(f)}for(let f of r)Rt(`path ${f.id}`,[f.fromAnchorId,f.toAnchorId],s,"anchor"),Rt(`path ${f.id}`,f.nodeIds,a,"node"),Rt(`path ${f.id}`,f.edgeIds,l,"edge");for(let f of o)if(Rt(`frontier ${f.id}`,f.fromNodeIds,a,"node"),Rt(`frontier ${f.id}`,f.edgeIds,l,"edge"),Rt(`frontier ${f.id}`,f.memberNodeIds,a,"node"),f.memberCount!==f.memberNodeIds.length)throw new Error(`Exploration frontier ${f.id} reports ${f.memberCount} member(s) but identifies ${f.memberNodeIds.length}.`);for(let f of c?.routes??[])Rt(`route ${f.id}`,f.nodeIds,a,"node"),Rt(`route ${f.id}`,f.edgeIds,l,"edge"),Rt(`route ${f.id}`,[f.anchorNodeId,f.endpointNodeId],a,"node");c&&Rt("route catalog selection",c.selectedRouteIds,new Set(c.routes.map(f=>f.id)),"route");let u=ht(e.incompleteReasons??[]),d=u.length===0?"accounted":"incomplete",m=t.reduce((f,p)=>f+p.omittedCandidates,0);return{schemaVersion:1,anchors:t,nodes:n,edges:i,paths:r,frontiers:o,coverage:{status:d,scope:e.scope,nodes:vy(n),edges:vy(i),matchedAnchors:t.filter(f=>f.status==="matched").length,ambiguousAnchors:t.filter(f=>f.status==="ambiguous").length,missingAnchors:t.filter(f=>f.status==="missing").length,omittedCandidates:m,frontierGroups:o.length,programEdges:KT(i),blindSpots:ht(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:JT(d,r,e.scope),...c?{routeCatalog:c}:{}}}function GT(e){return e.flatMap(t=>WT(t.semantics??[]).map(n=>({id:VT(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 KT(e){let t=GT(e),n=new Set(t.map(s=>s.sourceEdgeId)),i=new Map(ma.map(s=>[s,new Set])),r=new Map(ma.map(s=>[s,new Set])),o=new Map(ma.map(s=>[s,0]));for(let s of t)i.get(s.family).add(s.sourceEdgeId),r.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:ht(e.filter(s=>!n.has(s.id)).map(s=>s.kind)),families:{identity:Qi("identity",i,o,r),contract:Qi("contract",i,o,r),control:Qi("control",i,o,r),data:Qi("data",i,o,r),state:Qi("state",i,o,r),temporal:Qi("temporal",i,o,r)}}}function Qi(e,t,n,i){return{sourceEdges:t.get(e)?.size??0,projectedEdges:n.get(e)??0,subtypes:[...i.get(e)??[]].sort()}}function qT(e){let t=new Set;for(let n of e.semantics??[]){if(!zT.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 i=Xc(n);if(t.has(i))throw new Error(`Exploration edge ${e.id} repeats program edge semantic ${i}.`);t.add(i)}}function WT(e){return[...e].sort((t,n)=>Xc(t).localeCompare(Xc(n)))}function Xc(e){return`${e.family}:${e.subtype}`}function VT(e,t){return`program:${encodeURIComponent(e)}:${t.family}:${encodeURIComponent(t.subtype)}`}function JT(e,t,n){return e==="incomplete"||t.some(i=>i.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 Cy(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 i=new Set(e.anchors.flatMap(I=>[...I.nodeIds,...I.candidateNodeIds])),r=[],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 x=I+1;x<o.length;x+=1){let P=o[I],_=o[x],D=hy(e,P,_,!1),A=D??hy(e,P,_,!0);A?(A.nodeIds.forEach(W=>i.add(W)),r.push({id:fa("path",P.id,_.id),fromAnchorId:P.id,toAnchorId:_.id,status:!D||P.status==="ambiguous"||_.status==="ambiguous"?"candidate":"connected",nodeIds:A.nodeIds,edgeIds:A.edgeIds})):r.push({id:fa("path",P.id,_.id),fromAnchorId:P.id,toAnchorId:_.id,status:"partial",nodeIds:[],edgeIds:[]})}let s=ht(t.routeIds??[]),a=YT(e,s),l=new Set(a.routes.map(I=>I.id)),c=s.filter(I=>!l.has(I));if(c.length>0)throw new Error(`Unknown exploration route id(s): ${c.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(x=>i.add(x));let m=r.length===0||r.some(I=>I.edgeIds.length>0);m&&by(e,i,n);let f=Sy(e,i),p=new Set(t.expandedFrontierIds??[]),g=new Set(f.map(I=>I.id)),h=[...p].filter(I=>!g.has(I)).sort();if(h.length>0)throw new Error(`Unknown exploration frontier id(s): ${h.join(", ")}`);for(let I of f)p.has(I.id)&&I.memberNodeIds.forEach(x=>i.add(x));m&&by(e,i,n);let S=new Map(d.map(I=>[I.endpointNodeId,I.endpointKind])),v=new Set(d.flatMap(I=>I.nodeIds)),y=new Map;for(let I of d)for(let x=0;x<I.nodeIds.length;x+=1){let P=I.nodeIds[x],_=x;y.set(P,Math.max(y.get(P)??0,_))}let E=e.nodes.map(I=>{let x=S.get(I.id),P=v.has(I.id)?{upstreamCausalPath:!0,upstreamCausalDistance:y.get(I.id)??0,...x?{upstreamCausalEndpoint:x}:{}}:{};return{...I,attributes:{...I.attributes,...P},disposition:I.disposition==="excluded"||I.disposition==="unsupported"?I.disposition:i.has(I.id)?"emitted":"folded"}}),w=new Set([...r.flatMap(I=>I.edgeIds),...d.flatMap(I=>I.edgeIds)]),b=e.edges.map(I=>({...I,disposition:I.disposition==="excluded"||I.disposition==="unsupported"?I.disposition:w.has(I.id)||i.has(I.fromNodeId)&&i.has(I.toNodeId)?"emitted":"folded"})),R=pa({anchors:e.anchors,nodes:E,edges:b,paths:r,frontiers:[...e.frontiers.filter(I=>I.disposition!=="folded"),...Sy({...e,nodes:E,edges:b},i)],scope:e.coverage.scope,blindSpots:e.coverage.blindSpots,incompleteReasons:e.coverage.status==="incomplete"?[e.coverage.explanation]:[],routeCatalog:a}),C=new Set(R.frontiers.flatMap(I=>I.edgeIds)),L=R.edges.filter(I=>I.disposition==="folded"&&!C.has(I.id)).map(I=>I.id);if(L.length>0)throw new Error(`Folded exploration edge(s) are not frontier-accounted: ${L.sort().join(", ")}`);return R}var my=10;function YT(e,t=[]){let n=new Map(e.nodes.map(h=>[h.id,h])),i=new Map(e.edges.map(h=>[h.id,h])),r=new Map;for(let h of e.edges){if(!XT(h))continue;let S=r.get(h.toNodeId)??[];S.push(h),r.set(h.toNodeId,S)}for(let h of r.values())h.sort((S,v)=>Number(so(v))-Number(so(S))||gy(v)-gy(S)||S.fromNodeId.localeCompare(v.fromNodeId)||S.id.localeCompare(v.id));let o=ht(e.anchors.filter(h=>h.status==="matched").flatMap(h=>h.nodeIds)),s=new Map,a=new Set,l=(h,S,v)=>{let y=S.nodeIds[S.nodeIds.length-1],E=n.get(y),w=n.get(h);if(!E?.location||!w)return;let b=[...S.nodeIds].reverse(),R=[...S.edgeIds].reverse(),C=new Set(b),L=R.flatMap(D=>{let T=i.get(D);return T?[T]:[]}),I=e.edges.filter(D=>D.disposition!=="excluded"&&D.disposition!=="unsupported"&&(C.has(D.fromNodeId)||C.has(D.toNodeId))),x={id:fa("route",h,y,v,...R),status:"proved",anchorNodeId:h,anchorLabel:w.label,endpointNodeId:y,endpointLabel:E.label,endpointLocation:{...E.location},endpointKind:v,nodeIds:b,edgeIds:R,evidenceStrengths:ht(L.flatMap(D=>D.evidence.map(T=>T.strength))),spineEdgeFamilies:fy(L,!0),relatedEdgeFamilies:fy(I,!1),crossesRuntimeBoundary:L.some(so)},P=`${h}\0${y}\0${v}`,_=s.get(P);(!_||py(x,_)<0)&&s.set(P,x)};for(let h of o){n.get(h)?.attributes.publicEntry===!0&&l(h,{nodeIds:[h],edgeIds:[]},"public-entry");let S=[{nodeIds:[h],edgeIds:[]}],v=new Map([[h,0]]);for(let y=0;y<S.length;y+=1){let E=S[y],w=E.nodeIds[E.nodeIds.length-1];E.edgeIds.length>0&&n.get(w)?.location&&n.get(w)?.attributes.publicEntry===!0&&l(h,E,"public-entry");let b=r.get(w)??[];if(E.edgeIds.length>=my){b.some(R=>!E.nodeIds.includes(R.fromNodeId))&&a.add(h);continue}for(let R of b){if(E.nodeIds.includes(R.fromNodeId))continue;let C=E.edgeIds.length+1,L=v.get(R.fromNodeId);if(L!==void 0&&L<=C)continue;let I={nodeIds:[...E.nodeIds,R.fromNodeId],edgeIds:[...E.edgeIds,R.id]};if(v.set(R.fromNodeId,C),so(R)&&n.get(R.fromNodeId)?.location){l(h,I,"runtime-boundary");continue}S.push(I)}}}let c=[...s.values()].sort(py),u=new Set(c.map(h=>h.id)),d=ht(t.filter(h=>u.has(h))),m=ht(c.map(h=>h.anchorNodeId)),f=o.filter(h=>!m.includes(h)),p=[...a].sort(),g=e.coverage.status==="accounted"&&p.length===0?"accounted":"incomplete";return{schemaVersion:1,routes:c,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:my,anchorNodeIds:o,anchorsWithRoutes:m,anchorsWithoutRoutes:f,depthLimitedAnchorNodeIds:p,routeCount:c.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 fy(e,t){let n=e.flatMap(i=>i.semantics?.map(r=>r.family)??[]);return t&&e.length>0&&n.length===0&&n.push("control"),ht(n)}function py(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 XT(e){return e.disposition!=="excluded"&&e.disposition!=="unsupported"&&ZT(e)&&e.evidence.some(t=>["exact","derived","mixed"].includes(t.strength))}function ZT(e){return so(e)||e.kind==="boundary-observation"||e.kind==="call"||e.kind==="compiler:call"}function so(e){return e.kind==="runtime-boundary"||e.kind.startsWith("runtime:")}function gy(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 hy(e,t,n,i){return yy(e,t,n,i)??yy(e,n,t,i)}function yy(e,t,n,i){let r=[...t.nodeIds,...t.candidateNodeIds].sort(),o=new Set([...n.nodeIds,...n.candidateNodeIds]);if(r.some(u=>o.has(u)))return{nodeIds:[r.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))&&!i||QT(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 l=r.map(u=>({nodeId:u,nodeIds:[u],edgeIds:[]})),c=new Set(r);for(let u=0;u<l.length;u+=1){let d=l[u];for(let m of a.get(d.nodeId)??[]){if(c.has(m.nodeId))continue;let f={nodeId:m.nodeId,nodeIds:[...d.nodeIds,m.nodeId],edgeIds:[...d.edgeIds,m.edgeId]};if(o.has(m.nodeId))return f;c.add(m.nodeId),l.push(f)}}return null}function QT(e,t,n,i){let r=e.get(t)??[];r.push({nodeId:n,edgeId:i}),e.set(t,r)}function eF(e,t,n){let i=new Map;for(let a of e.edges){let l=i.get(a.fromNodeId)??{incoming:0,outgoing:0},c=i.get(a.toNodeId)??{incoming:0,outgoing:0};l.outgoing+=1,c.incoming+=1,i.set(a.fromNodeId,l),i.set(a.toNodeId,c)}let r=new Set,o=new Map;for(let a of e.edges){let l=t.has(a.fromNodeId),c=t.has(a.toNodeId);if(l===c)continue;let u=l?a.toNodeId:a.fromNodeId,d=l?a.fromNodeId:a.toNodeId,m=e.nodes.find(g=>g.id===u);if(m?.kind==="structural-region")continue;let f=o.get(u)??new Set;f.add(d),o.set(u,f),(/(?:runtime-boundary|external)/u.test(a.kind)||m&&/(?:frontier|external)/u.test(m.kind))&&r.add(u)}let s=[...o].filter(([a,l])=>{if(r.has(a))return!0;let c=i.get(a)??{incoming:0,outgoing:0};return(c.incoming>1||c.outgoing>1)&&l.size>1}).sort(([a,l],[c,u])=>Number(r.has(c))-Number(r.has(a))||u.size-l.size||a.localeCompare(c)).map(([a])=>a);for(let a of s){if(t.size>=n)break;t.add(a)}}function by(e,t,n){let i=-1;for(;t.size!==i&&t.size<n;)i=t.size,eF(e,t,n)}function Sy(e,t){let n=new Set(e.nodes.filter(s=>!t.has(s.id)&&s.disposition!=="excluded"&&s.disposition!=="unsupported").map(s=>s.id)),i=new Map;for(let s of e.edges){if(!n.has(s.fromNodeId)||!n.has(s.toNodeId))continue;let a=i.get(s.fromNodeId)??new Set,l=i.get(s.toNodeId)??new Set;a.add(s.toNodeId),l.add(s.fromNodeId),i.set(s.fromNodeId,a),i.set(s.toNodeId,l)}let r=[],o=new Set;for(let s of[...n].sort()){if(o.has(s))continue;let a=[],l=[s];o.add(s);for(let c=0;c<l.length;c+=1){let u=l[c];a.push(u);for(let d of[...i.get(u)??[]].sort())o.has(d)||(o.add(d),l.push(d))}r.push(a.sort())}return r.map(s=>{let a=new Set(s),l=e.edges.filter(p=>a.has(p.fromNodeId)||a.has(p.toNodeId)),c=l.filter(p=>a.has(p.fromNodeId)!==a.has(p.toNodeId)),u=ht(c.map(p=>a.has(p.fromNodeId)?p.toNodeId:p.fromNodeId)),d=new Set(c.map(p=>a.has(p.toNodeId)?"outgoing":"incoming")),m=ht(l.map(p=>p.id)),f=ht(c.map(p=>p.kind));return{id:fa("frontier",...s,...m),kind:f.join("+")||"disconnected",direction:d.size===1?[...d][0]:"undirected",fromNodeIds:u,edgeIds:m,memberNodeIds:s,memberCount:s.length,disposition:"folded",reason:c.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 fa(e,...t){let n=UT("sha256").update(t.join("\0")).digest("hex").slice(0,16);return`${e}:${n}`}function er(e,t){let n=[...e].sort((i,r)=>i.id.localeCompare(r.id));for(let i=1;i<n.length;i+=1)if(n[i-1].id===n[i].id)throw new Error(`Duplicate exploration ${t} id: ${n[i].id}`);return n}function Rt(e,t,n,i){let r=ht(t.filter(o=>!n.has(o)));if(r.length>0)throw new Error(`Exploration ${e} references missing ${i}(s): ${r.join(", ")}`)}function vy(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 ht(e){return[...new Set(e)].sort()}var tF=5,nF=12,iF=8,rF=3,xy=8,oF=6,sF=12,Ry=12,aF=12,lF=2,cF=new Set(["branch","loop","call","await","return","throw","mutation","catch","finally"]),uF=9e3,Ey=Mh;function dF(e,t){return Ny(e,t,"full")}function Ay(e,t){return Ny(e,t,"topology")}function Ny(e,t,n){let i=ya(t.searches??[]),r=ya(t.symbols??[]),o=ya(t.relations&&t.relations.length>0?t.relations:Ey),s=o.filter(M=>!Ey.includes(M));if(s.length>0)throw new Error(`Unsupported system-map relation kind(s): ${s.join(", ")}`);let a=new Set(o),l=t.evidenceFloor??"derived";if(l!=="exact"&&l!=="derived")throw new Error(`Unsupported system-map evidence floor: ${l}`);let c=ya(t.sourceScopes&&t.sourceScopes.length>0?t.sourceScopes:["production"]),u=["production","test","fixture","example","generated","script","unknown"],d=c.filter(M=>!u.includes(M));if(d.length>0)throw new Error(`Unsupported system-map source scope(s): ${d.join(", ")}`);let m=new Set(c),f=M=>m.has(hl(M));if(i.length===0&&r.length===0)throw new Error("system-map requires at least one --search or --symbol anchor.");let p=t.maxDepth??tF;if(!Number.isSafeInteger(p)||p<0)throw new RangeError(`maxDepth must be a non-negative safe integer; received ${p}`);let g=t.maxTopologyCharacters??uF;if(!Number.isSafeInteger(g)||g<=0)throw new RangeError(`maxTopologyCharacters must be a positive safe integer; received ${g}`);let h=new U(e),S=h.fileDependencyGraph(),v=JF(S),y=YF(h.sourceFiles()),E=ns(e),w=new Map((E?.observations??[]).map(M=>[M.id,M])),b=new Set((E?.observations??[]).map(M=>`${M.source.file}\0${M.source.startLine}`)),R=new Set,C=new Map,L=new Map,I=new Map,x=new Map,P=[],_=new Map,D=new Map,T=[],A=0,W=0,le=0,q=0,Y=0,N=0,K=new Set,te=new Map,me=new Map,ge=M=>{let H=me.get(M);if(H)return H;let Q=Un(e,M,{excludeIndexedTargets:!1});return me.set(M,Q),Q},ce=(M,H,Q,we,j=!1)=>{let B=L.get(M);if(B)return B.depth=Math.min(B.depth,H),B.primary||=we,B.promoteBoundaryImports||=j,B.origins.add(Q),B;let G={file:M,depth:H,primary:we,promoteBoundaryImports:j,origins:new Set([Q]),processed:!1};return L.set(M,G),G},be=(M,H,Q,we,j="none",B=!1)=>{let G=I.get(M.symbol);if(G)return G.depth=Math.min(G.depth,H),G.origins.add(Q),we&&G.anchorQueries.add(we),G.referenceScope=VF(G.referenceScope,j),ce(M.relativePath,H,Q,!0,B),G;let oe={definition:M,depth:H,origins:new Set([Q]),anchorQueries:new Set(we?[we]:[]),referenceScope:j,processed:!1};return I.set(M.symbol,oe),ce(M.relativePath,H,Q,!0,B),oe},F=(M,H,Q,we,j=!1,B=!0)=>{let G=an(M),oe=x.get(G);if(oe)return oe.depth=Math.min(oe.depth,H),oe.origins.add(Q),we&&oe.anchorQueries.add(we),oe.reverseCallExpansion||=j,oe.traversalEligible||=B,ce(M.file,H,Q,oe.traversalEligible,!0),oe;let z={...M,depth:H,origins:new Set([Q]),anchorQueries:new Set(we?[we]:[]),reverseCallExpansion:j,traversalEligible:B};return x.set(G,z),ce(M.file,H,Q,B,!0),z},Z=(M,H,Q)=>{ce(M.source.file,H,Q,!0,!0),M.owner.file!==M.source.file&&ce(M.owner.file,H,`${Q}:owner`,!0,!0);let we=J(e,M.owner.file),j=M.owner.symbol?Wn(e,h,M.owner.symbol).matches.find(oe=>oe.relativePath===M.owner.file):null,B=(j&&!Le(j.symbol)?j:null)??Ge(we,M.source.startLine);if(B&&!Le(B.symbol))return be(B,H,Q,void 0,"none",!0),B.symbol;M.owner.name&&F({file:M.owner.file,name:M.owner.name,startLine:M.owner.startLine,endLine:M.owner.endLine},H,`${Q}:source-owner`,void 0,!0);let G=h.definitionsForFile(M.source.file).filter(oe=>!!oe.leaf&&yn(e,M.source.file,oe.leaf).some(z=>z>=M.source.startLine&&z<=M.source.endLine));if(G.length===1){let oe=G[0];be(oe,H,`${Q}:handler-identifier`,void 0,"none",!0),Et(_,{kind:"runtime-boundary",evidence:"runtime-boundary:handler-identifier",fromFile:M.source.file,fromSymbol:null,toFile:oe.relativePath,toSymbol:oe.symbol,fromBoundaryParticipant:nr(M),line:M.source.startLine,strength:"derived"})}return null};for(let M of i){let H=FF(e,h,M,b),Q=H.filter(G=>_F(G,f)),we=!t.fullLiteralTraversal&&(H.length>nF||Q.length>iF),j=we?[]:H,B=new Set((we?[]:t.fullLiteralTraversal?Q:[...Q].sort(MF).slice(0,rF)).map(Dy));we&&(W+=1,le+=H.length);for(let G of j){let oe=B.has(Dy(G)),z=oe&&!G.ownerSymbol&&G.ownerStartLine!==null&&G.ownerEndLine!==null;if(ce(G.relativePath,0,`${oe?"literal-anchor":"literal-match"}:${M}`,z,z),z&&F({file:G.relativePath,name:G.ownerShortName??`${G.relativePath}:${G.ownerStartLine+1}`,startLine:G.ownerStartLine,endLine:G.ownerEndLine},0,`literal-source-owner:${M}`,M,!0),oe&&G.ownerSymbol){let ue=Wn(e,h,G.ownerSymbol).matches[0];ue&&!Le(ue.symbol)&&be(ue,0,"literal-owner",M,"all",!0)}P.push({query:M,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:oe})}T.push({kind:"literal",query:M,status:H.length>0?"matched":"missing",matchedRegionIds:[],matchingLines:H.length,seedMatchingLines:we?0:B.size,matchOnlyLines:H.length-B.size,eligibleSeedMatchingLines:Q.length,materializedMatchingLines:j.length,withheldMatchingLines:we?H.length:0,literalTraversal:we?"withheld-broad":"materialized",representativeMatches:we?BF(M,H):void 0,narrowingCommands:we?$F(M,H):void 0,exhaustiveTraversalCommand:we||B.size<Q.length?`codebaseiq system-map --search ${Ne(M)} --full-literal-traversal`:void 0,seedRegionIds:[],matchOnlyRegionIds:[]})}for(let M of r){let H=Wn(e,h,M);A+=H.omitted;let Q=AF(e,M),we=H.matches.filter(z=>!Le(z.symbol)),j=Q!==null&&we.length===0;j&&F(Q,0,"source-construct-anchor",M,!0);let B=j?we:H.matches;for(let z of B)be(z,0,"symbol-anchor",M,"all",!0);let G=j?NF(Q):null,oe=j?1:H.total;T.push({kind:"symbol",query:M,status:oe===0?"missing":oe===1?"matched":"ambiguous",matchedRegionIds:[],symbolCandidates:[...G?[G]:[],...B.map(GF)],totalSymbolCandidates:oe,omittedSymbolCandidates:H.omitted})}for(let M=0;M<p;M+=1){if(a.has("call")){let j=[...x.values()].filter(B=>B.traversalEligible&&B.reverseCallExpansion&&B.depth<=M&&!K.has(an(B)));for(let B of j){K.add(an(B));let G=ee(e,B.file);if((G?.callables??[]).filter(ue=>ue.name===B.name&&ue.startLine<=B.endLine&&ue.endLine>=B.startLine).length===1){let ue=(G?.callSites??[]).filter(xe=>xe.calleeLeaf===B.name&&!xe.memberAccess);for(let xe of ue){let Te=M+1,ve=Ge(J(e,B.file),xe.line),Pe=null,We=null;if(ve&&!Le(ve.symbol)){if(ve.relativePath===B.file&&ve.startLine<=B.endLine&&ve.endLine>=B.startLine)continue;be(ve,Te,"reverse-local-call-owner",void 0,"forward-regions",!0),Pe=ve.symbol}else{let O=Zc(e,B.file,xe.line);O&&an(O)!==an(B)&&(We=F(O,Te,"reverse-local-call-source-owner",void 0,!0))}!Pe&&!We||Et(_,{kind:"call",evidence:"ast-callsite",fromFile:B.file,fromSymbol:Pe,toFile:B.file,toSymbol:null,fromSourceConstruct:We?yt(We):void 0,toSourceConstruct:yt(B),line:xe.line,strength:"derived"})}}let z=new Set([...v.get(B.file)??[],...te.get(an(B))??[],...Up(e,B.file).flatMap(ue=>[...v.get(ue)??[]])]);for(let ue of z){if(!f(ue))continue;let Te=ge(ue).targets.filter(ve=>ve.targetFile===B.file&&ve.targetStartLine<=B.endLine&&ve.targetEndLine>=B.startLine);for(let ve of Te){let Pe=M+1,We=Ge(J(e,ue),ve.line),O=null,Ie=null;if(We&&!Le(We.symbol))be(We,Pe,"reverse-member-call-owner",void 0,"cross-workspace-or-forward",!0),O=We.symbol;else{let ne=Zc(e,ue,ve.line);ne&&(Ie=F(ne,Pe,"reverse-member-call-source-owner",void 0,!0))}!O&&!Ie||Et(_,{kind:"call",evidence:"ast-service-member-callsite",fromFile:ue,fromSymbol:O,toFile:B.file,toSymbol:null,fromSourceConstruct:Ie?yt(Ie):void 0,toSourceConstruct:yt(B),line:ve.line,strength:ve.strength==="exact"?"exact":"derived"})}}}}let H=[...I.values()].filter(j=>!j.processed&&j.depth<=M),Q=a.has("call")?h.calleeMap(H.map(j=>j.definition),{additive:!1,semantic:!1}):new Map;for(let j of H){j.processed=!0;let B=j.definition;if(j.referenceScope!=="none"&&(a.has("call")||a.has("reference")||a.has("contract-symbol"))){let G=HF(e,h,B).filter(z=>f(z.file)&&WF(j,z.file,L,y)),oe=new Set(G.flatMap(z=>{if(!(a.has("call")&&ee(e,z.file)?.callSites.some(Te=>Te.line===z.line&&Te.calleeLeaf===B.leaf)===!0)||!z.enclosingSymbol)return[];let xe=Wn(e,h,z.enclosingSymbol).matches[0];return xe&&!Le(xe.symbol)?[{owner:xe,site:z}]:[]}).sort((z,ue)=>{let xe=It(B.relativePath,y).relativeDir,Te=It(z.owner.relativePath,y).relativeDir===xe,ve=It(ue.owner.relativePath,y).relativeDir===xe,Pe=wy(e,z.owner),We=wy(e,ue.owner),O=z.owner.endLine-z.owner.startLine,Ie=ue.owner.endLine-ue.owner.startLine;return Number(ve)-Number(Te)||We-Pe||O-Ie||z.owner.symbol.localeCompare(ue.owner.symbol)}).filter((z,ue,xe)=>xe.findIndex(Te=>Te.owner.symbol===z.owner.symbol)===ue).reduce((z,ue)=>{if(z.length>=lF)return z;let xe=It(ue.owner.relativePath,y).relativeDir;return z.some(Te=>Te.workspace===xe)||z.push({symbol:ue.owner.symbol,workspace:xe}),z},[]).map(z=>z.symbol));for(let z of G){let ue=M+1;ce(z.file,ue,`reference:${k(B.symbol)}`,!0);let xe=a.has("call")&&ee(e,z.file)?.callSites.some(Pe=>Pe.line===z.line&&Pe.calleeLeaf===B.leaf)===!0,Te=null,ve=null;if(z.enclosingSymbol){let Pe=Wn(e,h,z.enclosingSymbol).matches[0];Pe&&!Le(Pe.symbol)&&(be(Pe,ue,"reference-owner",void 0,xe&&oe.has(Pe.symbol)?j.referenceScope:"none"),Te=Pe.symbol)}if(!Te&&z.line!==null){let Pe=Zc(e,z.file,z.line);Pe&&(ve=F(Pe,ue,"reference-source-owner",void 0,xe))}a.has("reference")&&Et(_,{kind:"reference",evidence:"indexed-or-source-reference",fromFile:z.file,fromSymbol:Te,toFile:B.relativePath,toSymbol:B.symbol,fromSourceConstruct:ve?yt(ve):void 0,line:z.line,strength:"mixed"}),xe&&Et(_,{kind:"call",evidence:"ast-callsite",fromFile:z.file,fromSymbol:Te,toFile:B.relativePath,toSymbol:B.symbol,fromSourceConstruct:ve?yt(ve):void 0,line:z.line,strength:"derived"}),a.has("contract-symbol")&&It(z.file,y).relativeDir!==It(B.relativePath,y).relativeDir&&Et(_,{kind:"contract-symbol",evidence:"compiler-cross-workspace-symbol",fromFile:z.file,fromSymbol:Te,toFile:B.relativePath,toSymbol:B.symbol,fromSourceConstruct:ve?yt(ve):void 0,line:z.line,strength:"exact"})}}for(let G of Q.get(B.symbolId)??[]){let oe=Wn(e,h,G.symbol).matches.find(ue=>ue.relativePath===G.file);if(!oe||!f(oe.relativePath))continue;if(!(oe.relativePath===B.relativePath||(S.get(B.relativePath)??new Set).has(oe.relativePath))){q+=1;continue}be(oe,M+1,`call:${k(B.symbol)}`,void 0,"none",!0),Et(_,{kind:"call",evidence:G.source,fromFile:B.relativePath,fromSymbol:B.symbol,toFile:oe.relativePath,toSymbol:oe.symbol,line:null,strength:RF(G.source)})}}let we=[...L.values()].filter(j=>!j.processed&&j.primary&&j.depth<=M);for(let j of we){j.processed=!0;let B=[...x.values()].filter(O=>O.traversalEligible&&O.file===j.file&&O.depth<=M),G=[...I.values()].filter(O=>O.definition.relativePath===j.file&&O.depth<=M).map(O=>{let Ie=Ui(e,j.file,O.definition.startLine);return{startLine:Ie?.startLine??O.definition.startLine,endLine:Ie?.endLine??O.definition.endLine}}),oe=O=>[...I.values()].filter(Ie=>Ie.definition.relativePath===j.file&&Ie.definition.startLine<=O&&Ie.definition.endLine>=O).sort((Ie,ne)=>Ie.definition.endLine-Ie.definition.startLine-(ne.definition.endLine-ne.definition.startLine)||Ie.definition.startLine-ne.definition.startLine)[0],z=[...w.values()].filter(O=>O.source.file===j.file&&C.has(O.id)),ue=[...B.map(O=>({startLine:O.startLine,endLine:O.endLine})),...z.map(O=>({...ha(e,O)}))],xe=[...G,...ue],Te=(ee(e,j.file)?.callSites??[]).filter(O=>xe.some(Ie=>O.line>=Ie.startLine&&O.line<=Ie.endLine)),ve=new Set;if(a.has("call"))for(let O of xe){let Ie=xn(e,j.file,O.startLine,O.endLine);for(let ne of Ie.targets){if(!f(ne.definition.relativePath))continue;let Ve=oe(ne.sourceLine),$t=B.find(Dt=>Dt.startLine<=ne.sourceLine&&Dt.endLine>=ne.sourceLine),bt=z.find(Dt=>{let st=ha(e,Dt);return st.startLine<=ne.sourceLine&&st.endLine>=ne.sourceLine});be(ne.definition,M+1,`scip-occurrence-call:${j.file}:${ne.sourceLine+1}`,void 0,"none",!0),Et(_,{kind:"call",evidence:"scip-occurrence-callsite",fromFile:j.file,fromSymbol:Ve?.definition.symbol??null,toFile:ne.definition.relativePath,toSymbol:ne.definition.symbol,fromBoundaryParticipant:bt?nr(bt):void 0,fromSourceConstruct:$t?yt($t):void 0,line:ne.sourceLine,strength:"exact"}),ve.add(`${ne.sourceLine}\0${ne.calleeLeaf}`)}}if(a.has("reference"))for(let O of xe){let Ie=Yp(e,j.file,O.startLine,O.endLine);for(let ne of Ie.targets){if(!f(ne.definition.relativePath)||ve.has(`${ne.sourceLine}\0${ne.calleeLeaf}`))continue;let Ve=oe(ne.sourceLine);if(Ve?.definition.symbol===ne.definition.symbol)continue;let $t=B.find(Dt=>Dt.startLine<=ne.sourceLine&&Dt.endLine>=ne.sourceLine),bt=z.find(Dt=>{let st=ha(e,Dt);return st.startLine<=ne.sourceLine&&st.endLine>=ne.sourceLine});be(ne.definition,M+1,`scip-occurrence-reference:${j.file}:${ne.sourceLine+1}`,void 0,"none",!0),Et(_,{kind:"reference",evidence:"scip-occurrence-reference",fromFile:j.file,fromSymbol:Ve?.definition.symbol??null,toFile:ne.definition.relativePath,toSymbol:ne.definition.symbol,fromBoundaryParticipant:bt?nr(bt):void 0,fromSourceConstruct:$t?yt($t):void 0,line:ne.sourceLine,strength:"exact"})}}let Pe=a.has("call")?Un(e,j.file,{ranges:xe,excludeIndexedTargets:!1}):{targets:[],unresolvedCallsites:0};N+=Pe.unresolvedCallsites;let We=Pe.targets.filter(O=>!ve.has(`${O.line}\0${O.calleeLeaf}`));Y+=We.filter(O=>O.strength!=="exact"&&(O.resolution!=="imported-service-object-member"||(O.resolutionAlternativeCount??0)>1)).length;for(let O of We){let Ie=(O.resolutionAlternativeCount??1)===1,ne=O.targetSymbol?J(e,O.targetFile).find(st=>st.symbol===O.targetSymbol):void 0,Ve=ne?null:F({file:O.targetFile,name:O.calleeLeaf,startLine:O.targetStartLine,endLine:O.targetEndLine},M+1,`member-call:${j.file}`,void 0,O.resolution==="imported-service-object-member"&&Ie,Ie);if(Ve&&O.serviceFile){let st=an(Ve),pr=te.get(st)??new Set;for(let hx of v.get(O.serviceFile)??[])pr.add(hx);te.set(st,pr)}ne&&be(ne,M+1,`member-call:${j.file}`,void 0,"none",!0);let $t=B.find(st=>st.startLine<=O.line&&st.endLine>=O.line),bt=oe(O.line),Dt=z.find(st=>{let pr=ha(e,st);return pr.startLine<=O.line&&pr.endLine>=O.line});Et(_,{kind:"call",evidence:O.resolution==="constructed-member-receiver"?"ast-constructed-member-callsite":O.resolution==="factory-callback-member"?"ast-factory-callback-callsite":O.resolution==="imported-service-object-member"?"ast-service-member-callsite":"ast-member-import-candidate",fromFile:j.file,fromSymbol:bt?.definition.symbol??null,toFile:O.targetFile,toSymbol:ne?.symbol??null,fromBoundaryParticipant:Dt?nr(Dt):void 0,fromSourceConstruct:$t?yt($t):void 0,toSourceConstruct:Ve?yt(Ve):void 0,line:O.line,strength:O.resolution==="imported-service-object-member"?(O.resolutionAlternativeCount??0)===1?"derived":"candidate":O.strength??"candidate"})}for(let O of a.has("import")||a.has("call")?UF(e,j.file):[]){if(!O.fromFile){if(a.has("import")){let ne=D.get(O.shortName)??{name:O.shortName,fromFiles:new Set};ne.fromFiles.add(j.file),D.set(O.shortName,ne)}continue}if(!f(O.fromFile))continue;if(a.has("import")&&(ce(O.fromFile,M+1,`import:${j.file}`,!1),Et(_,{kind:"import",evidence:"indexed-or-source-import",fromFile:j.file,fromSymbol:null,toFile:O.fromFile,toSymbol:O.symbol,line:null,strength:"mixed"})),a.has("call")&&Te.length>0){let ne=(O.source==="compiler"?Wn(e,h,O.symbol).matches:_n(e,O.fromFile,O.importedName)).filter(Ve=>!Le(Ve.symbol));for(let Ve of ne){let $t=Te.filter(bt=>bt.calleeLeaf===O.localName).map(bt=>bt.line);if($t.length!==0){be(Ve,M+1,`source-call:${j.file}`,void 0,"none",!0);for(let bt of $t)Et(_,{kind:"call",evidence:"ast-callsite",fromFile:j.file,fromSymbol:null,toFile:Ve.relativePath,toSymbol:Ve.symbol,line:bt,strength:"derived"})}}}if(!j.promoteBoundaryImports||!KF(j.file,O.fromFile,y))continue;let Ie=Wn(e,h,O.symbol);for(let ne of Ie.matches)if(qF(ne.relativePath,O.fromFile,y)&&!Le(ne.symbol)){let Ve=It(j.file,y).relativeDir!==It(ne.relativePath,y).relativeDir;be(ne,M+1,`boundary-import:${j.file}`,void 0,Ve?"cross-workspace-or-forward":"forward-regions")}}}for(let j of a.has("runtime-boundary")?E?.links??[]:[]){if(j.strength==="candidate"||l==="exact"&&j.strength!=="exact"||R.has(j.id))continue;let B=w.get(j.from),G=w.get(j.to);if(!B||!G||!f(B.source.file)||!f(G.source.file))continue;let oe=Fy(B,M,C,I,x),z=Fy(G,M,C,I,x);if(oe===null&&z===null)continue;let ue=M+1,xe=Z(B,oe??ue,`runtime-boundary:${j.joinRule}`),Te=Z(G,z??ue,`runtime-boundary:${j.joinRule}`),ve=xe?null:Ty(x,B),Pe=Te?null:Ty(x,G);C.set(B.id,oe??ue),C.set(G.id,z??ue),Et(_,{kind:"runtime-boundary",evidence:`runtime-boundary:${j.joinRule}`,fromFile:B.source.file,fromSymbol:xe,toFile:G.source.file,toSymbol:Te,fromBoundaryParticipant:nr(B),toBoundaryParticipant:nr(G),fromSourceConstruct:ve?yt(ve):void 0,toSourceConstruct:Pe?yt(Pe):void 0,runtimeBoundaryKey:j.matchedKeyParts.map(We=>`${We.name}=${We.value}`).join(" "),line:B.source.startLine,strength:j.strength}),R.add(j.id)}}let X=new Map;for(let M of L.keys())X.set(M,ao(M,y));let Se=[..._.values()].filter(M=>X.has(M.fromFile)&&X.has(M.toFile)).map(M=>({...M,fromRegionId:X.get(M.fromFile).id,toRegionId:X.get(M.toFile).id})).sort(Oy),tt=nM(Se),ni=new Set(t.expand??[]),An=ZF(L,I,P,Se,tt,X,ni),Ti=new Set([...L.values()].filter(M=>[...M.origins].some(H=>H.startsWith("literal-anchor:")||H==="literal-owner"||H==="symbol-anchor")).map(M=>X.get(M.file).id)),Ad=LF(An),ox=new Set(An.map(M=>M.id)),sx=[...ni].filter(M=>!ox.has(M)).sort();for(let M of T)if(M.matchedRegionIds=rM(M,P,I,X),M.kind==="literal"){let H=P.filter(Q=>Q.query===M.query);M.seedRegionIds=De(H.filter(Q=>Q.traversalSeed).map(Q=>X.get(Q.file).id)),M.matchOnlyRegionIds=De(H.filter(Q=>!Q.traversalSeed).map(Q=>X.get(Q.file).id))}let Nd=[...I.values()].filter(M=>!M.processed).length,kd=[...L.values()].filter(M=>M.primary&&!M.processed).length,_d=[...L.values()].filter(M=>!M.primary&&!M.processed).length,Bd=[...I.values()].filter(M=>M.processed),Bo=(E?.frontiers??[]).flatMap(M=>{let H=w.get(M.observationId);return!H&&M.source&&M.action&&M.strength?!a.has("runtime-boundary")||!f(M.source.file)||l==="exact"||!L.has(M.source.file)?[]:[{observationId:M.observationId,action:M.action,strength:M.strength,file:M.source.file,line:M.source.startLine,ownerShortName:M.ownerShortName??null,address:M.address??M.missingKeyParts.join(", "),reason:M.reason}]:!a.has("runtime-boundary")||!H||!f(H.source.file)||l==="exact"&&H.strength!=="exact"||!L.has(H.source.file)?[]:[{observationId:H.id,action:H.action,strength:H.strength,file:H.source.file,line:H.source.startLine,ownerShortName:H.owner.name,address:By(H),reason:M.reason,protocol:H.protocol,role:H.role,modality:H.modality,resolution:H.resolution,sourceScope:H.sourceScope,keyParts:H.keyParts.map(Q=>({name:Q.name,value:Q.value,evidence:Q.evidence}))}]}).sort((M,H)=>M.file.localeCompare(H.file)||M.line-H.line),il=(E?.links??[]).filter(M=>{if(!a.has("runtime-boundary")||l==="exact"&&M.strength!=="exact")return!1;let H=w.get(M.from),Q=w.get(M.to);return!!(H&&Q&&f(H.source.file)&&f(Q.source.file)&&(L.has(H.source.file)||L.has(Q.source.file)))}),ax=il.filter(M=>M.strength==="exact").length,lx=il.filter(M=>M.strength==="derived").length,cx=il.filter(M=>M.strength==="candidate").length,ux=E?.links.filter(M=>M.strength==="exact").length??0,dx=E?.links.filter(M=>M.strength==="derived").length??0,mx=E?.links.filter(M=>M.strength==="candidate").length??0,rl=iM(D,X),ol=A===0?"accounted":"incomplete",Od=[...W>0?[`${W} broad literal anchor(s) withheld ${le} 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 (${c.join(", ")}) remain visible as match-only evidence and do not seed traversal.`,E?"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 codebaseiq 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 ${p}; nonzero frontier counts identify evidence that was discovered but not traversed.`,"Region labels are structural path groupings, not inferred runtime or architectural boundaries."],Lt=hF({db:e,anchors:T,regions:An,symbolStates:I,sourceConstructStates:x,literalHits:P,relations:Se,externalBoundaries:rl,boundaryFrontiers:Bo,regionForFile:X,closureStatus:ol,omittedSymbolCandidates:A,maxDepth:p,requestedRelationKinds:o,evidenceFloor:l,includedSourceScopes:c,blindSpots:Od,topologyFrontiers:t.topologyFrontiers??[],routeIds:t.routeIds??[],expandedRegionIds:[...ni],maxTopologyCharacters:g,fullLiteralTraversal:t.fullLiteralTraversal??!1});if(n==="topology")return Lt;let $d=(t.behaviorFocusLocations?.length??0)>0?new Set([...Lt.anchors.flatMap(M=>M.nodeIds),...Lt.paths.flatMap(M=>M.nodeIds)]).size:void 0,Oo=Ag(e,Lt,{focusLocations:t.behaviorFocusLocations,...$d?{maxSteps:$d}:{}});uh(e,Lt,Oo);let fx=mF(e,Lt,Oo,t.behaviorFocusLocations??[]);Lt.corridor=ly(Lt,{focusLocations:fx});let jd=ch(e,Lt,Oo,{sourceAllowed:f,selectionTerms:t.selectionTerms}),Hd=CF(Lt),px=wF(i,r,p,o,l,c,t.fullLiteralTraversal??!1,g,An,tt,Ti,ni,Hd),gx=EF(i,r,p,An.filter(M=>Hd.has(M.id)),Ti,o,l,c,t.fullLiteralTraversal??!1,g);return{anchors:T,regions:An,regionRelations:tt,externalBoundaries:rl,boundaryFrontiers:Bo,unmatchedExpansions:sx,expansion:gx,drilldown:Ad,presentation:px,topology:Lt,behavior:Oo,nextAnchors:jd,closure:{status:ol,emitted:{regions:An.length,relations:Se.length,runtimeLinks:R.size},withheld:{symbols:Nd,files:kd+_d,regions:Lt.nodes.filter(M=>M.kind==="structural-region"&&M.disposition==="folded").length,drillAnchors:(Ad?.omittedAnchors??0)+jd.omittedAnchors,literalMatches:le},ambiguous:{anchors:T.filter(M=>M.status==="ambiguous").length,omittedSymbolCandidates:A},external:rl.length,unresolved:Bo.length,explanation:ol==="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:T.length,requestedRelationKinds:o,evidenceFloor:l,includedSourceScopes:c,matchedAnchorCount:T.filter(M=>M.status!=="missing").length,literalSearchesComplete:!0,broadLiteralAnchors:W,withheldLiteralMatches:le,symbolCandidateSetsComplete:A===0,omittedSymbolCandidates:A,maxTraversalDepth:p,frontierSymbols:Nd,frontierFiles:kd,supportFilesNotTraversed:_d,filteredUnverifiedCallEdges:q,memberCallCandidateEdges:Y,unresolvedMemberCallsites:N,runtimeBoundaryEvidenceAvailable:E!==null,runtimeBoundaryObservations:E?.observations.length??0,runtimeBoundaryExactLinks:ax,runtimeBoundaryDerivedLinks:lx,runtimeBoundaryCandidateLinks:cx,repositoryRuntimeBoundaryExactLinks:ux,repositoryRuntimeBoundaryDerivedLinks:dx,repositoryRuntimeBoundaryCandidateLinks:mx,runtimeBoundaryTraversedLinks:R.size,runtimeBoundaryFrontiers:Bo.length,referenceExpansionEligibleSymbols:Bd.filter(M=>M.referenceScope!=="none").length,referenceExpansionSkippedSymbols:Bd.filter(M=>M.referenceScope==="none").length,dynamicDispatchRepresented:E?.links.some(M=>M.joinRule==="carrier.discriminator"&&R.has(M.id))??!1,runtimeGeneratedLinksRepresented:E!==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:Od}}}function mF(e,t,n,i){let r=new Map,o=l=>{r.set(`${l.file}\0${l.line}`,l)};for(let l of i)o(l);let s=new Set(t.anchors.filter(l=>l.status==="matched").flatMap(l=>l.nodeIds));for(let l of n.steps)if(!(!l.location||!s.has(l.nodeId)||(l.behavior?.rawCharacters??1/0)>3e3))for(let c of l.behavior?.lines??[])c.signals.some(u=>cF.has(u))&&o({file:l.location.file,line:c.line,endLine:c.endLine});let a=t.edges.filter(l=>l.disposition==="emitted").flatMap(l=>l.evidence.flatMap(c=>c.location?[c.location]:[]));for(let l of a){o(l);let c=t.nodes.filter(d=>d.location?.file===l.file&&["symbol","source-construct","runtime-boundary-participant"].includes(d.kind)&&d.location.line<=l.line&&(d.location.endLine??d.location.line)>=l.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(!c?.location)continue;let u=xs(e,l.file,c.location.line,c.location.endLine??c.location.line,[l.line]);for(let d of u)o({file:l.file,line:d.line,endLine:d.endLine})}return[...r.values()].sort((l,c)=>l.file.localeCompare(c.file)||l.line-c.line)}function fF(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 an(e){return`${e.file}\0${e.startLine}\0${e.endLine}\0${e.name}`}function yt(e){return{file:e.file,name:e.name,startLine:e.startLine,endLine:e.endLine}}function ga(e,t){let n=nu(ee(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 i=_y(e,t.file,t.startLine);return i&&i.endLine>=t.endLine?{file:t.file,name:i.name,startLine:i.startLine,endLine:i.endLine}:yt(t)}function tr(e){return wt("source-construct",e.file,String(e.startLine),String(e.endLine),e.name)}function ba(e,t){let n=qi(e,t.symbol,t.relativePath),i=new Set(["package-surface-file","transitive-package-surface"]),r=n.filter(s=>!i.has(s)||Ct(e,t)),o=r.some(s=>!i.has(s));return{evidence:r,priority:o||hg(e,t.symbol,t.relativePath)?2:1}}function wy(e,t){let n=ba(e,t);return n.evidence.length>0?n.priority:0}function pF(e,t){let n=J(e,t.file),i=n.filter(r=>r.startLine<=t.startLine&&r.endLine>=t.startLine).sort((r,o)=>r.endLine-r.startLine-(o.endLine-o.startLine)||r.startLine-o.startLine);for(let r of i){let o=ba(e,r);if(o.evidence.length>0)return o}for(let r of gF(e,t.file,t.startLine)){let o=n.filter(s=>s.leaf===r.name).sort((s,a)=>Math.abs(s.startLine-r.startLine)-Math.abs(a.startLine-r.startLine)||s.symbol.localeCompare(a.symbol));for(let s of o){let a=ba(e,s);if(a.evidence.length>0)return a}return{evidence:[],priority:0}}return{evidence:[],priority:0}}function gF(e,t,n){let i=ae(e,t)?.rootNode;if(!i||i.startPosition.row>n||i.endPosition.row<n)return[];let r=[],o=iu(i,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")&&r.push({name:s.text,startLine:o.startPosition.row})}o=o.parent}return r}function hF(e){let t=[...new Map([...e.sourceConstructStates.values()].map(x=>ga(e.db,x)).map(x=>[an(x),x])).values()].sort((x,P)=>x.file.localeCompare(P.file)||x.startLine-P.startLine||x.endLine-P.endLine),n=e.anchors.map((x,P)=>{let _=wt("anchor",String(P),x.kind,x.query),D=[...e.symbolStates.values()].filter(q=>q.anchorQueries.has(x.query)).flatMap(q=>{if(!Le(q.definition.symbol))return[Vn(q.definition.symbol)];let Y=t.filter(N=>N.file===q.definition.relativePath).map(N=>tr(N));return Y.length>0?Y:[Vn(q.definition.symbol)]}),T=[...e.sourceConstructStates.values()].filter(q=>q.anchorQueries.has(x.query)).map(q=>tr(ga(e.db,q))),A=e.literalHits.filter(q=>q.query===x.query&&q.traversalSeed===!0&&q.ownerSymbol&&e.symbolStates.has(q.ownerSymbol)).map(q=>Vn(q.ownerSymbol)),W=e.literalHits.filter(q=>q.query===x.query&&q.traversalSeed===!0&&!q.ownerSymbol&&q.ownerStartLine!==null&&q.ownerStartLine!==void 0&&q.ownerEndLine!==null&&q.ownerEndLine!==void 0).map(q=>tr(ga(e.db,fF(q)))),le=De(x.kind==="symbol"?[...D,...T]:A.length+W.length>0?[...A,...W]:x.seedRegionIds??[]);return{id:_,kind:x.kind,query:x.query,status:x.status,nodeIds:x.status==="ambiguous"?[]:le,candidateNodeIds:x.status==="ambiguous"?le:[],omittedCandidates:x.omittedSymbolCandidates??0}}),i=new Map;for(let x of n)for(let P of[...x.nodeIds,...x.candidateNodeIds]){let _=i.get(P)??[];_.push(x.id),i.set(P,_)}let r=e.relations.flatMap(x=>[x.fromBoundaryParticipant,x.toBoundaryParticipant].flatMap(P=>P?.ownerName?[P]:[])),o=e.regions.map(x=>({id:x.id,kind:"structural-region",label:x.label,disposition:"folded",location:null,anchorIds:De(i.get(x.id)??[]),attributes:{workspace:x.workspace,structuralPath:x.structuralPath,minimumDepth:x.minDepth,files:x.fileCount,symbols:x.symbolCount,expanded:x.expanded}}));for(let x of e.symbolStates.values()){let P=e.regionForFile.get(x.definition.relativePath)?.id;if(!P)throw new Error(`System-map symbol ${x.definition.symbol} has no structural region.`);let _=Vn(x.definition.symbol),D=ba(e.db,x.definition);o.push({id:_,kind:"symbol",label:k(x.definition.symbol),disposition:(i.get(_)?.length??0)>0?"emitted":"folded",location:{file:x.definition.relativePath,line:x.definition.startLine,endLine:x.definition.endLine},anchorIds:De(i.get(_)??[]),attributes:{regionId:P,depth:x.depth,leaf:x.definition.leaf??k(x.definition.symbol),referenceScope:x.referenceScope,...D.evidence.length>0?{publicEntry:!0,publicEntryPriority:D.priority,publicEntryEvidence:D.evidence.join(",")}:{}}})}for(let x of t){let P=e.regionForFile.get(x.file)?.id;if(!P)throw new Error(`Source construct ${x.name} has no structural region.`);let _=tr(x),T=r.find(W=>W.file===x.file&&W.line>=x.startLine&&W.line<=x.endLine)?.ownerName??x.name,A=pF(e.db,x);o.push({id:_,kind:"source-construct",label:T,disposition:(i.get(_)?.length??0)>0?"emitted":"folded",location:{file:x.file,line:x.startLine,endLine:x.endLine},anchorIds:De(i.get(_)??[]),attributes:{regionId:P,leaf:T,sourceOwned:!0,...A.evidence.length>0?{publicEntry:!0,publicEntryPriority:A.priority,publicEntryEvidence:A.evidence.join(",")}:{}}})}let s=new Map;for(let x of e.relations)x.fromBoundaryParticipant&&s.set(x.fromBoundaryParticipant.observationId,x.fromBoundaryParticipant),x.toBoundaryParticipant&&s.set(x.toBoundaryParticipant.observationId,x.toBoundaryParticipant);for(let x of[...s.values()].sort((P,_)=>P.observationId.localeCompare(_.observationId))){let P=e.regionForFile.get(x.file)?.id;if(!P)throw new Error(`Runtime-boundary participant ${x.observationId} has no structural region.`);o.push({id:Qc(x.observationId),kind:"runtime-boundary-participant",label:x.address||x.ownerName||`${x.role} ${x.action}`,disposition:"folded",location:{file:x.file,line:x.line,endLine:x.endLine},anchorIds:[],attributes:{regionId:P,action:x.action,protocol:x.protocol,role:x.role,...x.address?{address:x.address}:{},ownerSymbol:x.ownerSymbol}})}let a=new Set(o.map(x=>x.id)),l=Kt(t,x=>x.file),c=(x,P,_,D,T,A,W=!1)=>{let le=x?Vn(x):null;if(le&&a.has(le)&&!Le(x))return le;let q=P?Qc(P.observationId):null;if(W&&q&&a.has(q))return q;let Y=_?tr(ga(e.db,_)):null;if(Y&&a.has(Y))return Y;if(q&&a.has(q))return q;let N=A===null?null:(l.get(T)??[]).filter(K=>K.startLine<=A&&K.endLine>=A).sort((K,te)=>K.endLine-K.startLine-(te.endLine-te.startLine)||K.startLine-te.startLine)[0]??null;return N?tr(N):le&&a.has(le)?le:D},u=[];for(let x of e.symbolStates.values()){let P=e.regionForFile.get(x.definition.relativePath)?.id;if(!P)continue;let _=Vn(x.definition.symbol);u.push({id:wt("edge","structural-membership",P,_),kind:"structural-membership",fromNodeId:P,toNodeId:_,directed:!0,disposition:"folded",semantics:ia("structural-membership"),evidence:[{method:"indexed-definition-file",strength:"exact",identity:x.definition.symbol,location:{file:x.definition.relativePath,line:x.definition.startLine,endLine:x.definition.endLine}}]})}let d=Kt(e.relations,x=>`${c(x.fromSymbol,x.fromBoundaryParticipant,x.fromSourceConstruct,x.fromRegionId,x.fromFile,x.line,x.kind==="runtime-boundary")}\0${c(x.toSymbol,x.toBoundaryParticipant,x.toSourceConstruct,x.toRegionId,x.toFile,null)}\0${x.kind}`),m=new Set;for(let x of d.values()){let P=x[0],_=c(P.fromSymbol,P.fromBoundaryParticipant,P.fromSourceConstruct,P.fromRegionId,P.fromFile,P.line,P.kind==="runtime-boundary"),D=c(P.toSymbol,P.toBoundaryParticipant,P.toSourceConstruct,P.toRegionId,P.toFile,null);if(P.kind==="runtime-boundary"&&P.fromBoundaryParticipant){let A=Qc(P.fromBoundaryParticipant.observationId),W=c(P.fromSymbol,void 0,P.fromSourceConstruct,P.fromRegionId,P.fromFile,P.line);W!==A&&!m.has(A)&&(m.add(A),u.push({id:wt("edge","boundary-observation",W,A),kind:"boundary-observation",fromNodeId:W,toNodeId:A,directed:!0,disposition:"folded",semantics:ia("boundary-observation"),evidence:[{method:"runtime-boundary-observation-owner",strength:P.strength??"unknown",identity:P.fromBoundaryParticipant.observationId,location:{file:P.fromBoundaryParticipant.file,line:P.fromBoundaryParticipant.line,endLine:P.fromBoundaryParticipant.endLine}}]}))}(_===D?o.find(A=>A.id===_):null)?.kind!=="structural-region"&&u.push({id:wt("edge",P.kind,_,D),kind:P.kind,fromNodeId:_,toNodeId:D,directed:!0,disposition:"folded",semantics:Ah(P),evidence:xF(x.map(A=>({method:A.evidence,strength:A.strength??"unknown",identity:A.kind==="runtime-boundary"&&A.runtimeBoundaryKey?A.runtimeBoundaryKey:`${A.fromSymbol??A.fromFile} -> ${A.toSymbol??A.toFile}`,location:A.line===null?null:{file:A.fromFile,line:A.line}})))})}for(let x of e.externalBoundaries){let P=wt("external",x.kind,x.name),_=De(x.fromRegionIds);o.push({id:P,kind:x.kind,label:x.name,disposition:"folded",location:null,anchorIds:[],attributes:{}});for(let D of _)u.push({id:wt("edge",x.kind,D,P),kind:x.kind,fromNodeId:D,toNodeId:P,directed:!0,disposition:"folded",semantics:ia("external-import"),evidence:[{method:"indexed-or-source-import",strength:"mixed",identity:`${D} -> ${x.name}`,location:null}]})}let f=[];e.boundaryFrontiers.forEach((x,P)=>{let _=e.regionForFile.get(x.file)?.id;if(!_)throw new Error(`Runtime-boundary frontier ${x.observationId} has no system-map region.`);let D=wt("unsupported","runtime-boundary",x.observationId,String(P)),T=wt("edge","runtime-boundary-frontier",_,D);o.push({id:D,kind:"runtime-boundary-frontier",label:x.address,disposition:"unsupported",location:{file:x.file,line:x.line},anchorIds:[],attributes:{action:x.action,strength:x.strength,owner:x.ownerShortName}}),u.push({id:T,kind:"runtime-boundary-frontier",fromNodeId:_,toNodeId:D,directed:!0,disposition:"unsupported",evidence:[{method:"runtime-boundary-extractor",strength:x.strength,identity:x.observationId,location:{file:x.file,line:x.line}}]}),f.push({id:wt("frontier","runtime-boundary",x.observationId,String(P)),kind:"runtime-boundary",direction:"unresolved",fromNodeIds:[_],edgeIds:[T],memberNodeIds:[D],memberCount:1,disposition:"unsupported",reason:x.reason,expansion:null})});let p=pa({anchors:n,nodes:o,edges:u,paths:[],frontiers:f,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`]:[]}),g=e.topologyFrontiers.some(x=>x==="frontier:program-facts"),h=Cy(p,{expandedFrontierIds:e.topologyFrontiers.filter(x=>x!=="frontier:program-facts"),routeIds:e.routeIds}),S=h.nodes.filter(x=>x.disposition==="emitted"||h.anchors.some(P=>P.status==="matched"&&P.nodeIds.includes(x.id))),v=e.relations.filter(x=>S.some(P=>yF(x,P))),y=e.boundaryFrontiers.filter(x=>S.some(P=>bF(x,P))),E=zh(e.db,v,S),w=Kh(e.db,S),b=iy(e.db,S,y),R=[...E.nodes,...w.nodes,...b.nodes].map(x=>g&&x.disposition==="folded"?{...x,disposition:"emitted"}:x),C=[...E.edges,...w.edges,...b.edges].map(x=>g&&x.disposition==="folded"?{...x,disposition:"emitted"}:x),L=g?null:SF(S,R,C),I=pa({anchors:h.anchors,nodes:[...h.nodes,...R],edges:[...h.edges,...C],paths:h.paths,frontiers:[...h.frontiers,...E.frontiers,...w.frontiers,...b.frontiers,...L?[L]:[]],scope:h.coverage.scope,blindSpots:[...h.coverage.blindSpots,...E.blindSpots,...w.blindSpots,...b.blindSpots],incompleteReasons:h.coverage.status==="incomplete"?[h.coverage.explanation]:[],...h.routeCatalog?{routeCatalog:h.routeCatalog}:{}});I.completion=h.completion;for(let x of I.frontiers)x.disposition==="folded"&&(x.id.startsWith("frontier:program-facts:")||(x.expansion=vF(e,x.id)));return I}function yF(e,t){if(e.fromSymbol&&t.id===Vn(e.fromSymbol)||e.toSymbol&&t.id===Vn(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 bF(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 SF(e,t,n){let i=De(t.filter(o=>o.disposition==="folded").map(o=>o.id)),r=De(n.filter(o=>o.disposition==="folded").map(o=>o.id));return i.length===0&&r.length===0?null:{id:wt("frontier","program-facts"),kind:"program-facts",direction:"outgoing",fromNodeIds:De(e.map(o=>o.id)),edgeIds:r,memberNodeIds:i,memberCount:i.length,disposition:"folded",reason:"Control, data, state, and temporal facts are folded beneath the selected high-level owners.",expansion:null}}function vF(e,t){return`codebaseiq system-map ${[...e.anchors.flatMap(i=>i.kind==="literal"?[`--search ${Ne(i.query)}`]:[`--symbol ${Ne(i.query)}`]),`--depth ${e.maxDepth}`,...e.requestedRelationKinds.map(i=>`--relation ${Ne(i)}`),`--evidence-floor ${Ne(e.evidenceFloor)}`,...e.includedSourceScopes.map(i=>`--source-scope ${Ne(i)}`),...e.fullLiteralTraversal?["--full-literal-traversal"]:[],`--topology-characters ${e.maxTopologyCharacters}`,...e.expandedRegionIds.map(i=>`--expand ${Ne(i)}`),...e.topologyFrontiers.map(i=>`--frontier ${Ne(i)}`),...e.routeIds.map(i=>`--route ${Ne(i)}`),`--frontier ${Ne(t)}`].join(" ")}`}function CF(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 i=n.attributes.regionId;typeof i=="string"&&t.add(i)}return t}function xF(e){let t=new Map;for(let n of e){let i=n.location?`${n.location.file}:${n.location.line}`:"";t.set(`${n.method}\0${n.strength}\0${n.identity??""}\0${i}`,n)}return[...t.values()].sort((n,i)=>n.method.localeCompare(i.method)||(n.identity??"").localeCompare(i.identity??"")||(n.location?.file??"").localeCompare(i.location?.file??"")||(n.location?.line??0)-(i.location?.line??0))}function wt(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function Vn(e){return wt("symbol",e)}function RF(e){return e==="semantic-callee"||e==="scip-chunk"?"exact":"derived"}function EF(e,t,n,i,r,o,s,a,l,c){let u=[...i].sort((g,h)=>ky(g,h,r)),m=u.slice(0,Ry).map(g=>g.id),f=u.slice(Ry).map(g=>g.id),p=[...e.map(g=>`--search ${Ne(g)}`),...t.map(g=>`--symbol ${Ne(g)}`),`--depth ${n}`,...o.map(g=>`--relation ${Ne(g)}`),`--evidence-floor ${Ne(s)}`,...a.map(g=>`--source-scope ${Ne(g)}`),...l?["--full-literal-traversal"]:[],`--topology-characters ${c}`,...m.map(g=>`--expand ${Ne(g)}`)];return{command:m.length===0?null:`codebaseiq system-map ${p.join(" ")}`,regionCount:m.length,regionIds:m,candidateRegionCount:i.length,omittedRegionIds:f}}function wF(e,t,n,i,r,o,s,a,l,c,u,d,m){let f=[...l].sort((I,x)=>ky(I,x,u)).filter(I=>!m||m.has(I.id)||d.has(I.id)),p=c.length>0?Math.floor(a*.4):0,g=a-p,h=new Set,S=0;for(let I of f){let x=Iy(I);!d.has(I.id)&&h.size>0&&S+x>g||(h.add(I.id),S+=x)}let v=c.filter(I=>h.has(I.fromRegionId)&&h.has(I.toRegionId)).sort(IF),y=[];for(let I of v){let x=Ly(I);y.length>0&&S+x>a||(y.push(Sa(I)),S+=x)}let E=l.filter(I=>!h.has(I.id)).map(I=>I.id).sort(),w=new Set(y),b=c.filter(I=>!w.has(Sa(I))).length,R=l.reduce((I,x)=>I+Iy(x),0)+c.reduce((I,x)=>I+Ly(x),0),C=f.every(I=>h.has(I.id))&&y.length===v.length,L=[...e.map(I=>`--search ${Ne(I)}`),...t.map(I=>`--symbol ${Ne(I)}`),`--depth ${n}`,...i.map(I=>`--relation ${Ne(I)}`),`--evidence-floor ${Ne(r)}`,...o.map(I=>`--source-scope ${Ne(I)}`),...s?["--full-literal-traversal"]:[],`--topology-characters ${Math.max(a,R)}`];return{maxCharacters:a,estimatedCharacters:S,totalEstimatedCharacters:R,regionIds:[...h],omittedRegionIds:E,relationKeys:y,omittedRelations:b,complete:C,expansionCommand:C?null:`codebaseiq system-map ${L.join(" ")}`}}function Iy(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 Ly(e){return 70+e.fromRegionId.length+e.toRegionId.length+e.kinds.join(",").length+e.evidence.join(",").length}function IF(e,t){let n=i=>i.kinds.includes("runtime-boundary")?0:i.kinds.includes("contract-symbol")?1:2;return n(e)-n(t)||t.relationCount-e.relationCount||Sa(e).localeCompare(Sa(t))}function Sa(e){return`${e.fromRegionId}\0${e.toRegionId}`}function ky(e,t,n){let i=a=>n.has(a.id)?0:1,r=a=>a.sourceFileCount===0?1:0,o=a=>a.symbolCount+a.literalHitCount>0?0:1,s=a=>[...a.incomingRegionIds,...a.outgoingRegionIds].filter(l=>n.has(l)).length;return i(e)-i(t)||o(e)-o(t)||r(e)-r(t)||e.minDepth-t.minDepth||s(t)-s(e)||t.literalHitCount-e.literalHitCount||e.testFileCount-t.testFileCount||e.label.localeCompare(t.label)}function LF(e){let t=[],n=new Set;for(let r of e.filter(o=>o.expanded)){for(let l of r.symbols)l.origins.includes("symbol-anchor")&&n.add(l.file);let o=Kt(r.symbols,l=>l.file),s=Kt(r.literalHits,l=>l.file),a=[...r.files].sort((l,c)=>PF(l,c,o,s));for(let l of a){let c=(o.get(l.file)??[]).sort(TF)[0];if(c){t.push({kind:"symbol",regionId:r.id,file:c.file,line:c.startLine,endLine:c.endLine,label:c.shortName});continue}let u=(s.get(l.file)??[]).sort($y)[0];u&&t.push({kind:"literal",regionId:r.id,file:u.file,line:u.line,endLine:null,label:u.ownerShortName??u.query})}}let i=DF(t,n);return{command:i.length===0?null:`codebaseiq inspect ${i.map(r=>`--at ${Ne(`${r.file}:${r.line+1}`)}`).join(" ")} --view behavior`,definitionCommand:null,candidateAnchors:t.length,selectedAnchors:i.length,omittedAnchors:t.length-i.length,anchors:i}}function DF(e,t){let n=[...Kt(e,s=>s.regionId).values()],i=[],r=new Set,o=Math.min(aF,24);for(let s of e)if(!(!t.has(s.file)||r.has(s.file))&&(i.push(s),r.add(s.file),i.length===o))return i;for(let s=0;i.length<o;s+=1){let a=!1;for(let l of n){let c=l[s];if(c&&(a=!0,!r.has(c.file)&&(i.push(c),r.add(c.file),i.length===o)))break}if(!a)break}return i}function PF(e,t,n,i){let r=a=>a.kind==="test"?2:a.kind==="barrel"?1:0,o=a=>(i.get(a.file)??[]).some(l=>l.traversalSeed)?0:1,s=a=>{let l=n.get(a.file)??[];return Math.min(5,...l.map(c=>lo(c.origins)))};return r(e)-r(t)||o(e)-o(t)||s(e)-s(t)||e.depth-t.depth||e.file.localeCompare(t.file)}function TF(e,t){return lo(e.origins)-lo(t.origins)||e.depth-t.depth||e.startLine-t.startLine||e.shortName.localeCompare(t.shortName)}function Ne(e){return`'${e.replaceAll("'","'\\''")}'`}function FF(e,t,n,i){let r=[];for(let o of he(e,{includeIgnored:!1})){let s=ie(e,o);if(s.length===0)continue;let a=t.definitionsForFile(o),l=ee(e,o)?.callables??[];for(let c=0;c<s.length;c+=1){let u=s[c]??"";if(!u.includes(n))continue;let d=Ge(a,c),m=nu(l,c),f=d&&!Le(d.symbol)?d:null,p=f?.startLine??m?.startLine??d?.startLine??c,g=f?.endLine??m?.endLine??d?.endLine??c,h=Ar(e,o,c,p,g),S=i.has(`${o}\0${c}`),v=!!(f?.isFunctionLike||m);r.push({relativePath:o,line:c,sourceLine:u,ownerSymbol:f?.symbol??null,ownerShortName:f?k(f.symbol):m?.name??(d?k(d.symbol):null),ownerStartLine:h.startLine,ownerEndLine:h.endLine,matchKind:kF(u,n),seedPriority:S?0:v?1:2})}}return r}function MF(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 Dy(e){return`${e.relativePath}\0${e.line}`}function nu(e,t){return e.filter(n=>n.startLine<=t&&n.endLine>=t).sort((n,i)=>n.endLine-n.startLine-(i.endLine-i.startLine)||n.startLine-i.startLine)[0]??null}function Zc(e,t,n){let r=nu(ee(e,t)?.callables??[],n)??_y(e,t,n);if(!r)return null;let o=Ar(e,t,n,r.startLine,r.endLine);return{file:t,name:r.name,startLine:o.startLine,endLine:o.endLine}}function _y(e,t,n){let i=ae(e,t)?.rootNode;if(!i||i.startPosition.row>n||i.endPosition.row<n)return null;let r=iu(i,n);for(;r;){if(r.type==="variable_declarator"){let s=r.childForFieldName("name")??r.namedChild(0),a=r.childForFieldName("value")??r.namedChild(1);if(s?.type==="identifier"&&a&&eu(a,n))return{name:s.text,startLine:r.startPosition.row,endLine:r.endPosition.row}}if(r.type==="pair"){let s=r.childForFieldName("key")??r.namedChild(0),a=r.childForFieldName("value")??r.namedChild(1),l=s?.text.replace(/^(?:['"])(.*)(?:['"])$/u,"$1");if(l&&a&&/^[A-Za-z_$][\w$]*$/u.test(l)&&eu(a,n))return{name:l,startLine:r.startPosition.row,endLine:r.endPosition.row}}r=r.parent}let o=Ui(e,t,n);return o?{name:`source@${n+1}`,startLine:o.startLine,endLine:o.endLine}:null}function eu(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&&eu(n,t))}function iu(e,t){let n=e.namedChildren.filter(i=>i.startPosition.row<=t&&i.endPosition.row>=t).sort((i,r)=>i.endIndex-i.startIndex-(r.endIndex-r.startIndex)||i.startPosition.row-r.startPosition.row)[0];return n?iu(n,t):e}function AF(e,t){let n=t.match(/^(.+):(\d+)(?:-(\d+))?$/u);if(!n)return null;let i=Go(e,n[1],{allowMultiple:!1})[0]?.relativePath;if(!i)return null;let r=Math.max(0,Number.parseInt(n[2],10)-1),o=n[3]?Math.max(r,Number.parseInt(n[3],10)-1):r,s=(ee(e,i)?.callables??[]).filter(a=>a.startLine<=r&&a.endLine>=o).sort((a,l)=>a.endLine-a.startLine-(l.endLine-l.startLine)||a.startLine-l.startLine)[0];return s?{file:i,name:s.name,startLine:s.startLine,endLine:s.endLine}:null}function NF(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 kF(e,t){let n=/[\p{L}\p{N}_$]/u,i=e.indexOf(t);for(;i>=0;){let r=e[i-1]??"",o=e[i+t.length]??"";if((r==="'"||r==='"'||r==="`")&&o===r)return"exact-value";if(!n.test(r)&&!n.test(o))return"boundary";i=e.indexOf(t,i+Math.max(1,t.length))}return"embedded"}function tu(e){return V(e)==="test"?!1:!/(?:^|[/._-])(?:fixtures?|mocks?|previews?|demos?|examples?|stories)(?:[/._-]|$)/iu.test(e)}function _F(e,t){return e.matchKind!=="embedded"&&t(e.relativePath)&&(hl(e.relativePath)!=="production"||tu(e.relativePath))}function BF(e,t){let n=[...t].sort(OF),i=[],r=new Set;for(let o of n)if(!r.has(o.relativePath)&&(i.push(o),r.add(o.relativePath),i.length>=xy))break;for(let o of n){if(i.length>=xy)break;i.includes(o)||i.push(o)}return i.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 OF(e,t){let n={"exact-value":0,boundary:1,embedded:2};return n[e.matchKind]-n[t.matchKind]||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||+!tu(e.relativePath)-+!tu(t.relativePath)||e.relativePath.localeCompare(t.relativePath)||e.line-t.line}function $F(e,t){let n=new Map;for(let i of t){let r=jF(i.relativePath);n.set(r,(n.get(r)??0)+1)}return[...n].sort(([i,r],[o,s])=>s-r||i.localeCompare(o)).slice(0,oF).map(([i])=>`codebaseiq search ${Ne(e)} --scope ${Ne(i)}`)}function jF(e){let t=e.split("/").filter(Boolean);if(t.length<=1)return e;let n=t.slice(0,-1),i=n.lastIndexOf("src");return i>=0?n.slice(0,Math.min(n.length,i+3)).join("/"):n.slice(0,Math.min(n.length,3)).join("/")}function HF(e,t,n){let i=t.callerFileMap([n],{semantic:!1}).get(n.symbolId)??new Set,r=[];for(let o of[...i].sort()){let s=n.leaf?yn(e,o,n.leaf):[];if(s.length===0){r.push({file:o,line:null,enclosingSymbol:null});continue}let a=t.definitionsForFile(o);for(let l of s)r.push({file:o,line:l,enclosingSymbol:Ge(a,l)?.symbol??null})}return r}function UF(e,t){let n=e.all(`SELECT DISTINCT gs.symbol, def_d.relative_path AS from_file
|
|
76
|
+
FROM mentions m
|
|
77
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
78
|
+
JOIN documents imp_d ON c.document_id = imp_d.id
|
|
79
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
80
|
+
LEFT JOIN (
|
|
81
|
+
SELECT m2.symbol_id, c2.document_id
|
|
82
|
+
FROM mentions m2
|
|
83
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
84
|
+
WHERE m2.role = 1
|
|
85
|
+
GROUP BY m2.symbol_id
|
|
86
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
87
|
+
LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
88
|
+
WHERE imp_d.relative_path = ? AND m.role = 2
|
|
89
|
+
ORDER BY def_d.relative_path, gs.symbol`,t);return n.length>0?n.map(i=>({symbol:i.symbol,shortName:k(i.symbol),importedName:Py(k(i.symbol)),localName:Py(k(i.symbol)),fromFile:i.from_file,source:"compiler"})):Ce(e,t).map(i=>{let r=zF(i.importedName,i.localName,i.kind),o=i.localName??i.importedName,s=i.importedName==="default"?o:i.importedName;return{symbol:r,shortName:r,importedName:s,localName:o,fromFile:i.sourcePath,source:"parsed-source"}})}function Py(e){return e.slice(e.lastIndexOf(":")+1).replace(/\(\)$/u,"")||e}function zF(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 Wn(e,t,n){let i=rt(e,n);if(!i.match)return{matches:[],total:0,omitted:0};let r=[i.match,...i.candidates.map(s=>rt(e,s.symbol).match)].filter(s=>s!==null),o=new Map;for(let s of r){let a=t.definitionsForFile(s.relativePath).find(l=>l.symbol===s.symbol);a&&o.set(a.symbol,a)}return{matches:[...o.values()],total:i.total,omitted:Math.max(0,i.total-o.size)}}function GF(e){return{symbol:e.symbol,shortName:k(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function Et(e,t){let n=[t.kind,t.fromFile,t.fromSymbol??"",t.toFile,t.toSymbol??"",t.fromBoundaryParticipant?.observationId??"",t.toBoundaryParticipant?.observationId??"",t.fromSourceConstruct?an(t.fromSourceConstruct):"",t.toSourceConstruct?an(t.toSourceConstruct):"",t.runtimeBoundaryKey??"",t.line??""].join("\0");e.set(n,t)}function nr(e){return{observationId:e.id,action:e.action,protocol:e.protocol,role:e.role,address:By(e),file:e.source.file,line:e.source.startLine,endLine:e.source.endLine,ownerName:e.owner.name,ownerSymbol:e.owner.symbol}}function ha(e,t){let n=ie(e,t.source.file);return gt(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine])}function Ty(e,t){let n=[...e.values()];for(let i of[t.owner,t.source]){let r=n.filter(o=>o.file===i.file&&o.startLine<=i.startLine&&o.endLine>=i.startLine).sort((o,s)=>o.endLine-o.startLine-(s.endLine-s.startLine)||o.startLine-s.startLine)[0];if(r)return r}return null}function Fy(e,t,n,i,r){let o=[],s=n.get(e.id);s!==void 0&&s<=t&&o.push(s);for(let a of i.values()){if(a.depth>t)continue;let l=a.definition;My(l,e)&&o.push(a.depth)}for(let a of r.values())a.depth>t||My(a,e)&&o.push(a.depth);return o.length>0?Math.min(...o):null}function My(e,t){let n=e.relativePath??e.file;return[t.owner,t.source].some(i=>n===i.file&&e.startLine<=i.startLine&&e.endLine>=i.startLine)}function Qc(e){return wt("runtime-boundary-participant",e)}function KF(e,t,n){let i=It(e,n),r=It(t,n);return i.relativeDir!==r.relativeDir?!0:/(?:^|\/)(?:contracts?|schemas?|db\/schema)(?:\/|$)/u.test(t)}function qF(e,t,n){return ao(e,n).id===ao(t,n).id}function WF(e,t,n,i){if(e.referenceScope==="all")return!0;let r=ao(t,i).id;return[...n.values()].some(s=>s.promoteBoundaryImports&&ao(s.file,i).id===r)?!0:e.referenceScope!=="cross-workspace-or-forward"?!1:It(t,i).relativeDir!==It(e.definition.relativePath,i).relativeDir}function VF(e,t){let n={none:0,"forward-regions":1,"cross-workspace-or-forward":2,all:3};return n[e]>=n[t]?e:t}function JF(e){let t=new Map;for(let[n,i]of e)for(let r of i){let o=t.get(r)??new Set;o.add(n),t.set(r,o)}return t}function It(e,t){return t.find(n=>e===n.relativeDir||e.startsWith(`${n.relativeDir}/`))??{name:"root",relativeDir:""}}function YF(e){let t=new Set(["apps","packages","services","crates","libs","tools"]),n=new Map;for(let i of e){let r=i.split("/").filter(Boolean);if(r.length<3||!t.has(r[0]))continue;let o=`${r[0]}/${r[1]}`;n.set(o,{name:r[1],relativeDir:o})}return[...n.values()].sort((i,r)=>r.relativeDir.length-i.relativeDir.length)}function ao(e,t){let n=It(e,t),r=(n.relativeDir?e.slice(n.relativeDir.length+1):e).split("/").filter(Boolean);r[0]==="src"&&r.shift();let o=XF(r);return{id:`region:${n.relativeDir||"root"}:${o}`,label:`${n.name}:${o}`,workspace:n.name,structuralPath:o}}function XF(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 ZF(e,t,n,i,r,o,s){let a=Kt([...e.values()],f=>o.get(f.file).id),l=Kt([...t.values()],f=>o.get(f.definition.relativePath).id),c=Kt(n,f=>o.get(f.file).id),u=new Map;for(let f of i)for(let p of new Set([f.fromRegionId,f.toRegionId])){let g=u.get(p)??[];g.push(f),u.set(p,g)}let d=Kt(r,f=>f.toRegionId),m=Kt(r,f=>f.fromRegionId);return[...a.entries()].map(([f,p])=>{let g=o.get(p[0].file),h=l.get(f)??[],S=c.get(f)??[],v=u.get(f)??[],y=s.has(f),E=h.map(tM).sort(oM).slice(0,sF),w=p.filter(b=>V(b.file)==="test").length;return{id:f,label:g.label,workspace:g.workspace,structuralPath:g.structuralPath,minDepth:Math.min(...p.map(b=>b.depth)),fileCount:p.length,sourceFileCount:p.length-w,testFileCount:w,symbolCount:h.length,literalHitCount:S.length,anchorQueries:De([...S.map(b=>b.query),...h.flatMap(b=>[...b.anchorQueries])]),relationKinds:De(v.map(b=>b.kind)),incomingRegionIds:De((d.get(f)??[]).map(b=>b.fromRegionId)),outgoingRegionIds:De((m.get(f)??[]).map(b=>b.toRegionId)),memberCallCandidateRelationCount:v.filter(b=>b.evidence==="ast-member-import-candidate").length,notableSymbols:E,omittedNotableSymbols:Math.max(0,h.length-E.length),expanded:y,files:y?p.map(QF).sort(sM):[],symbols:y?h.map(eM).sort(aM):[],literalHits:y?[...S].sort($y):[],relations:y?[...v].sort(Oy):[]}}).sort((f,p)=>f.minDepth-p.minDepth||f.label.localeCompare(p.label))}function QF(e){return{file:e.file,kind:V(e.file),depth:e.depth,origins:De([...e.origins])}}function eM(e){return{symbol:e.definition.symbol,shortName:k(e.definition.symbol),file:e.definition.relativePath,startLine:e.definition.startLine,endLine:e.definition.endLine,depth:e.depth,origins:De([...e.origins]),anchorQueries:De([...e.anchorQueries]),referenceExpansion:e.referenceScope!=="none",referenceScope:e.referenceScope}}function tM(e){return{shortName:k(e.definition.symbol),file:e.definition.relativePath,origins:De([...e.origins])}}function nM(e){return[...Kt(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:De(n.map(i=>i.kind)),relationCount:n.length,fromFiles:De(n.map(i=>i.fromFile)),toFiles:De(n.map(i=>i.toFile)),fromSymbols:De(n.flatMap(i=>i.fromSymbol?[k(i.fromSymbol)]:[])),toSymbols:De(n.flatMap(i=>i.toSymbol?[k(i.toSymbol)]:[])),evidence:De(n.map(i=>i.evidence)),strengths:De(n.map(i=>i.strength??"unknown"))})).sort((n,i)=>n.fromRegionId.localeCompare(i.fromRegionId)||n.toRegionId.localeCompare(i.toRegionId))}function iM(e,t){return[...e.values()].map(n=>({kind:"external-import",name:n.name,fromRegionIds:De([...n.fromFiles].flatMap(i=>{let r=t.get(i);return r?[r.id]:[]})),fromFiles:De([...n.fromFiles])})).sort((n,i)=>n.name.localeCompare(i.name))}function rM(e,t,n,i){let r=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 De(r.map(o=>i.get(o)?.id).filter(o=>!!o))}function By(e){return e.keyParts.map(t=>`${t.name}=${t.value}`).join(" ")}function ya(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))]}function De(e){return[...new Set(e)].sort()}function Kt(e,t){let n=new Map;for(let i of e){let r=t(i),o=n.get(r)??[];o.push(i),n.set(r,o)}return n}function Oy(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 oM(e,t){return lo(e.origins)-lo(t.origins)||e.shortName.localeCompare(t.shortName)}function lo(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 sM(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)}function aM(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function $y(e,t){return e.file.localeCompare(t.file)||e.line-t.line||e.query.localeCompare(t.query)}var cM=["causal","structure","complete"],uM={causal:["execution","runtime","dataflow","state","temporal"],structure:["contract","identity","ownership","dependencies"],complete:Gt},dM=2,mM=48,jy=64,fM=5e4;function co(e,t,n={}){let i=Pn([...t.symbols??[],...t.locations??[]]),r=Pn(t.searches??[]);if(i.length===0&&r.length===0)throw new Error("evidence requires at least one positional symbol, --symbol, --at, or --search selector.");let o=n.view??"causal",s=pM(n.families,o),a=n.direction??"both",l=Pn(n.subtypes??[]),c=n.connecting??!1,u=n.inventoryOnly??!1,d=Pn(n.foldIds??[]),m=n.maxDepth??dM,f=n.maxEdges??mM;if(!Number.isSafeInteger(m)||m<0)throw new RangeError(`Evidence depth must be a non-negative safe integer; received ${m}.`);if(!Number.isSafeInteger(f)||f<=0)throw new RangeError(`Evidence max edges must be a positive safe integer; received ${f}.`);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 p=Ay(e,{symbols:i,searches:r,maxDepth:m,maxTopologyCharacters:fM,relations:gM(s)}),g=new Map(p.nodes.map(Y=>[Y.id,Y])),h=p.edges.filter(Y=>Y.disposition==="emitted"||Y.disposition==="folded").flatMap(Y=>hM(Y,g)),S=h.filter(Y=>s.includes(Y.family)).filter(Y=>l.length===0||l.includes(Y.subtype)),v=new Set(p.anchors.flatMap(Y=>Y.nodeIds));if(c&&v.size<2)throw new Error("Connecting evidence requires at least two resolved root nodes.");let y=new Set(S.map(Y=>Y.id)),E=ru(h,v,"incoming").filter(Y=>y.has(Y.id)),w=ru(h,v,"outgoing").filter(Y=>y.has(Y.id)),b=ru(h,v,"both").filter(Y=>y.has(Y.id)),R=CM(s,l,E,w,b),C=a==="incoming"?E:a==="outgoing"?w:b,L=c?DM(C,[...v],a):C,I=TM(L,v,a),x=[...L].sort((Y,N)=>FM(Y,N,I)),P=xM(x,f),_=EM(P,d),D=u?[]:d.length>0?x.filter(Y=>_.has(Y.id)):x,T=d.length>0?D:D.slice(0,f),A=d.length>0||u?[]:P,W=Math.max(0,D.length-T.length),le=p.frontiers.filter(Y=>Y.disposition==="unsupported").length,q=p.coverage.status==="incomplete"?"incomplete":W>0?"bounded":"accounted";return{kind:"graph",view:n.families&&n.families.length>0?"custom":o,families:s,selection:{direction:a,subtypes:l,connecting:c,inventoryOnly:u,foldIds:d},targets:p.anchors.map(Y=>({kind:Y.kind,query:Y.query,status:Y.status,nodeIds:[...Y.nodeIds],omittedCandidates:Y.omittedCandidates})),inventory:R,edges:T,folds:A,coverage:{status:q,topologyStatus:p.coverage.status,scope:p.coverage.scope,maxDepth:m,maxEdges:f,matchedEdges:x.length,eligibleEdges:D.length,returnedEdges:T.length,omittedEdges:W,frontierGroups:p.frontiers.length,unsupportedFrontiers:le,blindSpots:Pn([...p.coverage.blindSpots,...Th(s)]),explanation:u?`${x.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.`:q==="accounted"?"Every selected relationship in the bounded topology was emitted.":q==="bounded"?`${W} selected relationship(s) were withheld by the explicit edge budget.`:p.coverage.explanation}}}function pM(e,t){let n=e&&e.length>0?e:uM[t],i=n.filter(r=>!Gt.includes(r));if(i.length>0)throw new Error(`Unsupported graph evidence family: ${i.join(", ")}.`);return Pn(n)}function gM(e){return["call","contract-symbol","import","reference","runtime-boundary"]}function hM(e,t){let n=t.get(e.fromNodeId),i=t.get(e.toNodeId);return!n||!i?[]:(e.semantics??[]).flatMap((r,o)=>{let s=bM(r);if(!s)return[];let a=Fh(s,r.subtype);if(!a)throw new Error(`No graph relation provider contract is registered for ${s}/${r.subtype}.`);let l=vM(e);if(!a.relation.evidenceStrengths.includes(l))throw new Error(`Graph relation provider ${a.provider.id} does not admit ${l} evidence for ${s}/${r.subtype}.`);return[{id:`${e.id}:${o}:${s}`,family:s,semanticFamily:r.family,subtype:r.subtype,from:Hy(n),to:Hy(i),sourceKind:e.kind,providerId:a.provider.id,supportCeiling:a.relation.supportCeiling,establishes:a.relation.establishes,nonClaims:[...a.relation.nonClaims],recoverWith:[...a.relation.recoverWith],evidenceStrength:l,evidenceMethods:Pn(e.evidence.map(c=>c.method)),evidenceConstituents:yM(e.evidence),context:r.context?{...r.context}:null,attributes:r.attributes?{...r.attributes}:null}]})}function yM(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:i})=>({method:n,strength:i}))}function bM(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 Hy(e){let t=SM(e);return{id:e.id,kind:e.kind,label:t?k(t):e.label,symbol:t,location:e.location?{...e.location}:null}}function SM(e){return e.kind!=="symbol"||!e.id.startsWith("symbol:")?null:decodeURIComponent(e.id.slice(7))}function vM(e){let t=Pn(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 ru(e,t,n){let i=ou(e,n),r=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 l=s[a],c=o.get(l);for(let u of i.get(l)??[])r.set(u.edge.id,u.edge),!o.has(u.next)&&(o.set(u.next,c+1),s.push(u.next))}return[...r.values()]}function ou(e,t){let n=new Map,i=(r,o,s)=>{let a=n.get(r)??[];a.push({edge:s,next:o}),n.set(r,a)};for(let r of e)t!=="incoming"&&i(r.from.id,r.to.id,r),t!=="outgoing"&&i(r.to.id,r.from.id,r);for(let r of n.values())r.sort((o,s)=>o.edge.id.localeCompare(s.edge.id)||o.next.localeCompare(s.next));return n}function CM(e,t,n,i,r){let o=new Set;for(let u of[...n,...i,...r])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 f=`${m.family}\0${m.subtype}`;d.set(f,(d.get(f)??0)+1)}return d},a=s(n),l=s(i),c=s(r);return[...o].map(u=>{let[d,m]=u.split("\0");return{family:d,subtype:m,incoming:a.get(u)??0,outgoing:l.get(u)??0,both:c.get(u)??0}}).sort((u,d)=>Gt.indexOf(u.family)-Gt.indexOf(d.family)||u.subtype.localeCompare(d.subtype))}function xM(e,t){let n=e.slice(t),i=new Map;for(let s of n){let a=RM(s),l=`${s.family}\0${a}`,c=i.get(l)??[];c.push(s),i.set(l,c)}let r=new Map(e.map((s,a)=>[s.id,a+1])),o=[];for(let[s,a]of[...i].sort(([l],[c])=>l.localeCompare(c))){let[l,c]=s.split("\0"),u=[...a].sort((d,m)=>d.id.localeCompare(m.id));for(let d=0;d<u.length;d+=jy){let m=u.slice(d,d+jy),f=m.map(S=>S.id),p=Pn(m.map(S=>S.subtype)).sort(),g=p.length===1?p[0]:"mixed",h=[...new Set(m.flatMap(S=>[S.from.id,S.to.id]))].sort();o.push({id:LM(l,p.join("\0"),f),mode:wM(m),family:l,subtype:g,subtypes:p,region:c,edgeCount:f.length,edgeIds:f,nodeIds:h,minimumMaxEdges:Math.max(...f.map(S=>r.get(S)??e.length))})}}return o.sort((s,a)=>Gt.indexOf(s.family)-Gt.indexOf(a.family)||(s.region??"").localeCompare(a.region??"")||s.id.localeCompare(a.id))}function RM(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 EM(e,t){if(t.length===0)return new Set;let n=new Map(e.map(r=>[r.id,r])),i=t.filter(r=>!n.has(r));if(i.length>0){let r=e.map(o=>o.id).sort();throw new Error(`Unknown evidence fold ${i.join(", ")} for this projection. Available folds: ${r.join(", ")||"(none)"}.`)}return new Set(t.flatMap(r=>n.get(r).edgeIds))}function wM(e){let t=new Map,n=new Map,i=new Set;for(let o of e){i.add(o.from.id),i.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 IM(i,t)?"scc":[...i].every(o=>(n.get(o)?.size??0)<=1&&(t.get(o)?.size??0)<=1)?"linear":"topology"}function IM(e,t){let n=new Set,i=new Set,r=o=>{if(n.has(o))return!0;if(i.has(o))return!1;n.add(o);for(let s of t.get(o)??[])if(r(s))return!0;return n.delete(o),i.add(o),!1};return[...e].some(r)}function LM(e,t,n){return`fold:${lM("sha256").update([e,t,...n].join("\0")).digest("hex").slice(0,16)}`}function DM(e,t,n){let i=new Map,r=[...new Set(t)].sort();for(let o=0;o<r.length;o+=1)for(let s=o+1;s<r.length;s+=1)for(let a of PM(e,r[o],r[s],n))i.set(a.id,a);return[...i.values()]}function PM(e,t,n,i){let r=ou(e,i),o=new Map([[t,0]]),s=new Map,a=[t];for(let c=0;c<a.length;c+=1){let u=a[c],d=o.get(u);if(u!==n)for(let m of r.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 l=[];for(let c=n;c!==t;){let u=s.get(c);if(!u)return[];l.push(u.edge),c=u.node}return l.reverse()}function TM(e,t,n){let i=ou(e,n),r=new Map,o=[...t];for(let s of t)r.set(s,0);for(let s=0;s<o.length;s+=1){let a=o[s],l=r.get(a);for(let{next:c}of i.get(a)??[])r.has(c)||(r.set(c,l+1),o.push(c))}return r}function FM(e,t,n){return Uy(e,n)-Uy(t,n)||zy(e)-zy(t)||Gy(e.evidenceStrength)-Gy(t.evidenceStrength)||Gt.indexOf(e.family)-Gt.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 Uy(e,t){return Math.min(t.get(e.from.id)??Number.MAX_SAFE_INTEGER,t.get(e.to.id)??Number.MAX_SAFE_INTEGER)}function zy(e){let t=[e.from,e.to].filter(n=>n.kind==="structural-region").length;return t===2?2:t}function Gy(e){switch(e){case"exact":return 0;case"mixed":return 1;case"derived":return 2;case"candidate":return 3;case"unknown":return 4}}function Pn(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))]}function su(e,t){let n=bn(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let i=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
|
|
90
|
+
WHERE relative_path IN (${i})
|
|
91
|
+
ORDER BY relative_path`,...n).map(c=>c.relative_path).filter(c=>!e.isIgnored(c)),s=Zo(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:c,...u})=>u),a=Xi(e,"forward",n).filter(c=>!e.isIgnored(c)),l=Xi(e,"reverse",n).filter(c=>!e.isIgnored(c));return{files:o,symbols:s,dependsOn:a,dependedOnBy:l}}function au(e,t){let n=bn(e,t);return n.length===0?[]:qy([...Ky(e,n),...AM(e,n)]).filter(i=>!e.isIgnored(i.relative_path)).map(Wy)}function MM(e,t){let n=bn(e,t);return n.length===0?[]:qy(Ky(e,n)).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({...Wy(i),basis:"external-reference"}))}function Ky(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
|
|
92
|
+
FROM mentions m
|
|
93
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
94
|
+
JOIN documents d1 ON c.document_id = d1.id
|
|
95
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
96
|
+
WHERE d1.relative_path NOT IN (${n})
|
|
97
|
+
AND (
|
|
98
|
+
EXISTS (
|
|
99
|
+
SELECT 1
|
|
100
|
+
FROM defn_enclosing_ranges der
|
|
101
|
+
JOIN documents d2 ON der.document_id = d2.id
|
|
102
|
+
WHERE der.symbol_id = gs.id
|
|
103
|
+
AND d2.relative_path IN (${n})
|
|
104
|
+
)
|
|
105
|
+
OR EXISTS (
|
|
106
|
+
SELECT 1
|
|
107
|
+
FROM mentions def_m
|
|
108
|
+
JOIN chunks def_c ON def_m.chunk_id = def_c.id
|
|
109
|
+
JOIN documents d2 ON def_c.document_id = d2.id
|
|
110
|
+
WHERE def_m.symbol_id = gs.id
|
|
111
|
+
AND def_m.role = 1
|
|
112
|
+
AND d2.relative_path IN (${n})
|
|
113
|
+
)
|
|
114
|
+
)
|
|
115
|
+
AND m.role != 1
|
|
116
|
+
AND ${e.localSymbolPredicate}
|
|
117
|
+
${e.pathExclusionsFor("d1")}
|
|
118
|
+
ORDER BY d1.relative_path`,...t,...t,...t)}function AM(e,t){let n=new U(e);return t.flatMap(i=>n.definitionsForFile(i).filter(r=>it(r.symbol)).map(r=>({relative_path:i,symbol:r.symbol})))}function qy(e){let t=new Set;return e.filter(n=>{let i=`${n.relative_path}|${n.symbol}`;return t.has(i)?!1:(t.add(i),!0)})}function Wy(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:k(e.symbol)}}var uo=new WeakMap,Vy=vt({kind:"definition-exclusions",invalidation:Je("definition-exclusions"),serialize:e=>JSON.stringify(e),deserialize:NM});function Yy(e,t){let n=ye(t);if(!(n==="rust"||n==="typescript"||n==="tsx"||n==="javascript"))return[];let r=se(e,t);if(!r)return[];let o=Ft(e,t,r),s=Vy.read(e,t,o);if(s)return s;let a=n==="rust"?UM(e,t):OM(e,t);return Vy.write(e,t,o,a),a}function NM(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=t.map(kM);return n.some(i=>i===null)?null:n}catch{return null}}function kM(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?e0(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 Xy=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),_M=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,BM=/\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 OM(e,t){let n=se(e,t);if(!n||!$M(n))return[];let i=ae(e,t);if(!i)return[];let r=uo.get(i);if(r)return r;let o=!1,s=i.rootNode;for(let l of s.namedChildren){if(l.type!=="expression_statement")continue;let c=l.namedChild(0);if(!c||c.type!=="call_expression")continue;let u=c.namedChild(0);if(!u)continue;let d=u.type==="member_expression"?u.namedChild(u.namedChildCount-1)?.text:u.text;if(d&&Xy.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 l of s.namedChildren){let c=null,u=null;if(l.type==="function_declaration")c=l.namedChild(0)?.text??null,u=l;else if(l.type==="export_statement"){let d=l.namedChild(0);d?.type==="function_declaration"&&(c=d.namedChild(0)?.text??null,u=d)}else if(l.type==="lexical_declaration"){let d=l.namedChild(0);if(d?.type==="variable_declarator"){let m=d.namedChild(0)?.text,f=d.namedChild(1);m&&(f?.type==="arrow_function"||f?.type==="function_expression")&&(c=m,u=d)}}c&&/^use[A-Z]/.test(c)&&u&&a.push({startLine:u.startPosition.row,endLine:u.endPosition.row,reason:"React custom hook (use*)",disposition:"exclude"})}return a.push(...Zy(i,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),uo.set(i,a),a}function $M(e){if(e.includes("codebaseiq"))return!0;let t=!1;for(let n of Xy)if(e.includes(n)){t=!0;break}return t&&_M.test(e)?!0:e.includes("use")&&BM.test(e)}var jM=/codebaseiq[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function HM(e){return jM.test(e)}function Zy(e,t,n){let i=[],r=o=>{if(t.has(o.type)&&o.parent){let a=o.parent.children,l=-1;for(let c=0;c<a.length;c+=1)if(a[c].startIndex===o.startIndex&&a[c].type===o.type){l=c;break}if(l>0)for(let c=l-1;c>=0;c-=1){let u=a[c];if(n.has(u.type)){if(HM(u.text)){i.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"codebaseiq suppression comment",disposition:"exclude"});break}continue}if(!(u.type==="attribute_item"||u.type==="inner_attribute_item"))break}}for(let s of o.namedChildren)r(s)};return r(e.rootNode),i}function UM(e,t){let n=ae(e,t);if(!n)return[];let i=uo.get(n);if(i)return i;let r=[],o=zM(n);return o?(uo.set(n,o),o):(Qy(n.rootNode,r,!1,!1),r.push(...Zy(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"]))),r.push(...ZM(n.rootNode)),uo.set(n,r),r)}function zM(e){return t0(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)",disposition:"exclude"}]:null}function Qy(e,t,n,i){let r=n,o=i;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"?GM(e,t,n,i):i&&XM(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"?KM(e,t,n):e.type==="mod_item"&&lu(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(r=!0);for(let s of e.namedChildren)Qy(s,t,r,o)}function GM(e,t,n,i){let r=lu(e),o=null;i?o={reason:"trait impl method (dynamic dispatch)",disposition:"implicit-usage"}:n&&(o={reason:"inside #[cfg(test)] mod",disposition:"exclude"});for(let s of r){if(eb(s)){o={reason:"#[allow(dead_code)]",disposition:"exclude"};break}let a=JM(s);if(a){o=a;break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o.reason,disposition:o.disposition})}function KM(e,t,n){let i=lu(e),r=e.namedChildren.find(o=>o.type==="type_identifier")?.text;i.some(YM)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(...)] - generated impl may access fields",disposition:"implicit-usage",containerName:r}),i.some(eb)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",disposition:"exclude",containerName:r}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",disposition:"exclude",containerName:r})}function lu(e){let t=e.parent;if(!t)return[];let n=t.children,i=-1;for(let o=0;o<n.length;o+=1)if(n[o].startIndex===e.startIndex&&n[o].type===e.type){i=o;break}if(i<=0)return[];let r=[];for(let o=i-1;o>=0;o-=1){let s=n[o];if(s.type==="attribute_item"||s.type==="inner_attribute_item")r.push(s.text);else{if(s.type==="line_comment"||s.type==="block_comment")continue;break}}return r}var qM=new Set(["test","bench","tokio::test","async_std::test"]),WM=new Set(["no_mangle","export_name","link_name","used","macro_export","proc_macro","proc_macro_derive","proc_macro_attribute"]),VM=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 JM(e){if(/#\[\s*cfg\s*\(\s*test\s*\)/.test(e))return{reason:"#[cfg(test)]",disposition:"exclude"};let t=QM(e);return t?qM.has(t)?{reason:`#[${t}]`,disposition:"exclude"}:WM.has(t)?{reason:`Rust ABI/export attribute #[${t}]`,disposition:"implicit-usage"}:VM.has(t)?null:{reason:`Rust attribute macro #[${t}]`,disposition:"implicit-usage"}:null}function YM(e){return/#\[\s*derive\s*\(/.test(e)}function eb(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function XM(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function ZM(e){let t=n0(e);if(t.size===0)return[];let n=[];for(let i of e.descendantsOfType("mod_item")){let r=i.childForFieldName("name")?.text;r&&t.has(r)&&n.push({startLine:i.startPosition.row,endLine:i.endPosition.row,reason:'attribute `with = "..."` module - body may be invoked via reflection',disposition:"implicit-usage",containerName:r})}return n}function QM(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 e0(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 t0(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 Jy=/\bwith\s*=\s*"([^"]+)"/g;function n0(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){Jy.lastIndex=0;let i;for(;(i=Jy.exec(n.text))!==null;){let r=i[1],o=r.split("::").pop()??r;o&&t.add(o)}}return t}function tb(e){let t=cu(e);return(n,i,r,o)=>t(n,i,r,o)?.disposition==="exclude"}function cu(e){let t=new Map,n=i=>{let r=t.get(i);if(r)return r;let o=Yy(e,i),s=new Map;for(let a of o){if(!a.containerName)continue;let l=s.get(a.containerName)??[];l.push(a),s.set(a.containerName,l)}return r={ranges:o,containers:s},t.set(i,r),r};return(i,r,o,s)=>{let a=n(i),l=[];for(let u of a.ranges)r>=u.startLine&&r<=u.endLine&&l.push(u);let c=new Set;s&&c.add(s);for(let u of Qo(o))c.add(u);for(let u of c){let d=a.containers.get(u);d&&l.push(...d)}return i0(l)}}function i0(e){if(e.length===0)return null;let n=e.find(i=>i.disposition==="exclude")??e[0];return{disposition:n.disposition,reason:n.reason}}function uu(e,t={}){dl(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function nb(e,t,n={}){dl(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function ib(e,t){if(t.isIgnoredPath(e.relativePath))return mt("ignored-file");if(Le(e.symbol))return mt("module-like-symbol");if(!va(e.symbol))return mt("non-value-symbol");if(!e.isFunctionLike&&e.enclosingSymbol&&va(e.enclosingSymbol))return mt("nested-non-callable-value");if(!t.includeTests&&!r0(e.relativePath))return mt("test-file");if(!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName))return mt("excluded-file-region");let n=re(e.symbol);if(n==="<constructor>")return mt("implicit-constructor");if(e.symbol.startsWith("scip-python ")){if(n==="__all__")return mt("python-runtime-metadata");if(/^__[^_].*__$/.test(n))return mt("python-protocol-member")}return t.isDeclarationOnlyCallable()?mt("declaration-only-callable"):t.isFrameworkContractCallable()?mt("framework-contract-member"):at(e.symbol)?mt("rust-trait-impl-member"):ki(e.symbol)?mt("rust-test-module"):!t.includeMembers&&!o0(e)?mt("member"):e.endLine-e.startLine+1<t.minLoc?mt("below-min-loc"):{accepted:!0}}function r0(e){return V(e)!=="test"}function mt(e){return{accepted:!1,rejectionReason:e}}function va(e){return ke(e)||e.endsWith("().")||e.endsWith(".")}function o0(e){return it(e.symbol)||Qo(e.symbol).length===0}function rb(){return new Map}function ob(e,t,n){let i=new Map;for(let r of Em(e,n))e.isIgnored(r.relative_path)||t.has(r.relative_path)||xa(i,r.symbol_id,r.relative_path,r.ref_count,"scip-mention");return i}function sb(e,t,n,i={}){let r=new Set;if(i.conservative||n.size===0){for(let o of Im(e,t))r.add(o.symbol_id);return r}for(let o of wm(e,t))e.isIgnored(o.relative_path)||n.has(o.relative_path)||r.add(o.symbol_id);return r}function du(e,t){let n=e.get(t);if(!n)return!1;for(let i of n.values())if(i.occurrences>0)return!0;return!1}function Ca(e,t,n){let i=e.get(t);if(!i)return!1;for(let[r,o]of i)if(r!==n&&o.occurrences>0)return!0;return!1}function ab(e){return e?.occurrences??0}function xa(e,t,n,i,r="source-fallback"){if(i<=0)return;let o=cb(e,t,n);o.occurrences+=i,o.sources.add(r)}function lb(e,t,n,i,r){if(i<=0)return;let o=cb(e,t,n);o.occurrences=Math.max(i,o.occurrences),o.sources.add(r)}function cb(e,t,n){let i=e.get(t);i||(i=new Map,e.set(t,i));let r=i.get(n);return r||(r={occurrences:0,sources:new Set},i.set(n,r)),r}var s0=new Set(["componentDidCatch","componentDidMount","componentDidUpdate","componentWillUnmount","getDerivedStateFromError","getDerivedStateFromProps","getSnapshotBeforeUpdate","render","shouldComponentUpdate","UNSAFE_componentWillMount","UNSAFE_componentWillReceiveProps","UNSAFE_componentWillUpdate"]);function ir(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=ae(e,t.relativePath);if(!n)return!1;let i=n.rootNode.descendantsOfType("method_definition").find(s=>s.startPosition.row<=t.startLine&&s.endPosition.row>=t.endLine);if(!i)return!1;if(/\boverride\b/.test(i.text.slice(0,Math.max(0,i.text.indexOf("{")))))return!0;let r=i.parent;for(;r&&r.type!=="class_declaration"&&r.type!=="class";)r=r.parent;if(!r)return!1;let o=r.text.slice(0,Math.max(0,r.text.indexOf("{")));return/\bimplements\b/.test(o)||/\bextends\b/.test(o)?!0:s0.has(t.leaf)&&/\bextends\s+(?:React\.)?(?:Component|PureComponent)\b/.test(o)}function wi(e,t={}){let{scope:n,minLoc:i=1,includeTests:r=!1,skipBarrels:o=!1,includeMembers:s=!1,deadCodeOnly:a=!1,scanLimit:l,semantic:c=!0}=t,u=0,d=$("dead.candidates",()=>{let b=Ae(a0(e,{scope:n,minLoc:i,includeTests:r,includeMembers:s}),l);return u=b.length,b},()=>({definitions:u})),m=0,f=o?$("dead.inactive-barrels",()=>{let b=new Set(gg(e));return m=b.size,b},()=>({paths:m})):new Set,p=0,g=a?rb():$("dead.mention-reference-counts",()=>{let b=ob(e,f,d.map(R=>R.symbolId));return p=b.size,b},()=>({definitions:d.length,symbolsWithReferences:p})),h=0,S=a?$("dead.mentioned-symbol-ids",()=>{let b=sb(e,d.map(R=>R.symbolId),f,{conservative:f.size===0});return h=b.size,b},()=>({definitions:d.length,referencedSymbols:h})):new Set,v=a?d.filter(b=>!S.has(b.symbolId)):d.filter(b=>!Ca(g,b.symbolId,b.relativePath));a?$("dead.source-fallback.dead-code-only",()=>p0(e,v,g,{inactiveBarrelPaths:f}),()=>({definitions:v.length,testReferencesIncluded:!0})):$("dead.source-fallback.ast",()=>f0(e,v,g,{inactiveBarrelPaths:f}),()=>({definitions:v.length,testReferencesIncluded:!0}));let y=a?v.filter(b=>!du(g,b.symbolId)):v.filter(b=>!Ca(g,b.symbolId,b.relativePath)),E=new Set;$("dead.caller-map-supplement",()=>{E=b0(e,y,g,{inactiveBarrelPaths:f,includeSemantic:!a&&c})},()=>({definitions:y.length,semantic:!a&&c}));let w=a?v.filter(b=>!du(g,b.symbolId)):d.filter(b=>!E.has(b.symbolId));return m0(e,u0(w,g))}function a0(e,t){let n=tb(e),i=[];for(let r of vr(e,{scope:t.scope,symbolMatches:va,sqlPrefilter:"function-like"}))ib(r,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n,isDeclarationOnlyCallable:()=>c0(e,r),isFrameworkContractCallable:()=>ir(e,r)}).accepted&&i.push(r);return i}var l0=["method_signature","abstract_method_signature","call_signature","construct_signature"];function c0(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=ae(e,t.relativePath);if(n)return n.rootNode.descendantsOfType([...l0]).some(r=>r.startPosition.row<=t.startLine&&r.endPosition.row>=t.endLine);let i=ie(e,t.relativePath).slice(t.startLine,t.endLine+1).join(`
|
|
119
|
+
`).trim();return i.endsWith(";")&&!i.includes("=>")&&!i.includes("{")}function u0(e,t){return e.map(n=>d0(n,t)).filter(n=>n.cross_file_refs===0).sort((n,i)=>i.loc-n.loc||n.relative_path.localeCompare(i.relative_path)||n.start_line-i.start_line)}function d0(e,t){let n=t.get(e.symbolId)??new Map,i=ab(n.get(e.relativePath)),r=0;for(let[o,s]of n)o!==e.relativePath&&(r+=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:i,cross_file_refs:r}}function m0(e,t){let n=cu(e),i=[],r=0,o=0,s=0,a=0,l=0,c=0;for(let u of t){if(e.isIgnored(u.relative_path))continue;if(Ye(e,u.relative_path)){a++;continue}if(Ue(e,u.symbol,u.relative_path)){l++;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,f=m?"implicit-usage":u.same_file_refs===0?"dead-code":"file-internal";f==="dead-code"?r++:f==="file-internal"?o++:s++,c+=u.loc,i.push({relativePath:u.relative_path,startLine:u.start_line,endLine:u.end_line,loc:u.loc,symbol:u.symbol,shortName:k(u.symbol),sameFileRefs:u.same_file_refs,kind:f,...m?{implicitUsageReason:m}:{}})}return{symbols:i,counts:{total:i.length,deadCode:r,fileInternal:o,implicitUsage:s,loc:c},applicability:{entrySurfaceExcluded:a,externalRootExcluded:l,implicitUsageSignals:s},totalCount:i.length,deadCodeCount:r,fileInternalCount:o,implicitUsageCount:s,totalLoc:c}}function f0(e,t,n,i){if(t.length===0)return;let r=new U(e),o=new Set(t.map(l=>l.symbolId)),s=new Set(t.map(l=>l.leaf).filter(Boolean)),a=new Set(r.sourceFiles());for(let l of he(e))a.add(l);r.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:l=>i.inactiveBarrelPaths.has(l)},l=>{o.has(l.target.symbolId)&&(h0(e,l)||xa(n,l.target.symbolId,l.sourceFile,y0(l),"source-fallback"))})}function p0(e,t,n,i){if(t.length===0)return;let r=new U(e),o=bm(t),s=new Set(r.sourceFiles());for(let u of he(e))s.add(u);let a=new Set(o.keys()),l=new Map,c=u=>{let d=l.get(u);return d||(d=Pm(e,u),l.set(u,d)),d};r.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>i.inactiveBarrelPaths.has(u),resolveTargets:({sourceFile:u,name:d,kind:m})=>{let f=o.get(d);return f?g0(u,d,f,()=>c(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{l.delete(u),nb(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&ub(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||xa(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function g0(e,t,n,i,r){let o=n.filter(c=>c.relativePath===e);if(o.length>0)return o;if(!r.permissive&&n.length===1)return[...n];let s=i(),a=s.get(t);if(a)for(let c of a){let u=n.filter(d=>Pt(c,d.relativePath));if(u.length>0)return u}let l=new Set;for(let c of s.values())for(let u of c)l.add(u);for(let c of l){let u=n.filter(d=>Pt(c,d.relativePath));if(u.length>0&&u.length===n.length)return u}return r.permissive?[...n]:[]}function h0(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&ub(e,t)}function y0(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function ub(e,t){return t.occurrences>1?!1:Ce(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function b0(e,t,n,i){let r=new Set,o=i.includeSemantic!==!1,s=(u,d)=>{d===u.relativePath||e.isIgnored(d)||i.inactiveBarrelPaths.has(d)||lb(n,u.symbolId,d,1,"caller-map")};if($("dead.caller-map.per-symbol-non-semantic",()=>{for(let u of t){let d=ps(e,u,{semantic:!1,semanticEvidence:pe});for(let m of d)s(u,m.file)}},()=>({definitions:t.length,semantic:!1})),!o)return r;let a=0,l=$("dead.caller-map.semantic-candidates",()=>{let u=t.filter(d=>!Ca(n,d.symbolId,d.relativePath));return a=u.length,u},()=>({definitions:t.length,semanticCandidates:a}));if(l.length===0)return r;let c=Cn(e,l);for(let u of c.incompleteSymbolIds)r.add(u);for(let u of c.unavailableSymbolIds)r.add(u);for(let u of l){let d=c.callers.get(u.symbolId);if(d)for(let m of d)s(u,m)}return r}function S0(e,t={}){let{limit:n=30,scope:i}=t,r=i?"AND def_d.relative_path LIKE ?":"",o=i?[`%${i}%`]:[],a=e.all(`SELECT
|
|
120
|
+
gs.symbol,
|
|
121
|
+
COUNT(*) AS ref_count,
|
|
122
|
+
COUNT(DISTINCT ref_d.id) AS file_count,
|
|
123
|
+
def_d.relative_path AS defined_in
|
|
124
|
+
FROM mentions m
|
|
125
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
126
|
+
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
127
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
128
|
+
JOIN (
|
|
129
|
+
SELECT m2.symbol_id, c2.document_id
|
|
130
|
+
FROM mentions m2
|
|
131
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
132
|
+
WHERE m2.role = 1
|
|
133
|
+
GROUP BY m2.symbol_id
|
|
134
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
135
|
+
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
136
|
+
WHERE m.role != 1
|
|
137
|
+
AND def_d.id != ref_d.id
|
|
138
|
+
${e.pathExclusionsFor("def_d")}
|
|
139
|
+
${e.symbolNoiseFor("gs")}
|
|
140
|
+
${r}
|
|
141
|
+
GROUP BY gs.id
|
|
142
|
+
ORDER BY ref_count DESC
|
|
143
|
+
LIMIT ?`,...o,n).filter(l=>!e.isIgnored(l.defined_in)).map(l=>({symbol:l.symbol,shortName:k(l.symbol),refCount:l.ref_count,fileCount:l.file_count,definedIn:l.defined_in,basis:"scip-cross-file-mentions",countUnit:"reference-occurrences"}));return a.length>0?{rows:a,coverage:{semanticEvidence:{enabled:!1,status:"disabled",incompleteSymbolCount:0,unavailableSymbolCount:0}}}:v0(e,i,n)}function v0(e,t,n){let i=ze(e,{scope:t}).filter(a=>!e.isIgnored(a.relativePath)),r=Qt(e,i,{limit:500,semanticEvidence:pe}),o=i.filter(a=>!r.incompleteSymbolIds.has(a.symbolId)&&!r.unavailableSymbolIds.has(a.symbolId)).map(a=>C0(a,r.rows.get(a.symbolId)??[])).filter(a=>a.refCount>0).sort((a,l)=>l.refCount-a.refCount||l.fileCount-a.fileCount).slice(0,n),s=r.incompleteSymbolIds.size>0&&r.unavailableSymbolIds.size>0?"incomplete-and-unavailable":r.incompleteSymbolIds.size>0?"incomplete":r.unavailableSymbolIds.size>0?"unavailable":"complete";return{rows:o,coverage:{semanticEvidence:{enabled:!0,status:s,incompleteSymbolCount:r.incompleteSymbolIds.size,unavailableSymbolCount:r.unavailableSymbolIds.size}}}}function C0(e,t){let n=t.filter(i=>i.file!==e.relativePath);return{symbol:e.symbol,shortName:k(e.symbol),refCount:n.length,fileCount:new Set(n.map(i=>i.file)).size,definedIn:e.relativePath,basis:"source-backed-incoming-evidence",countUnit:"distinct-incoming-evidence-rows"}}function x0(e,t,n={}){return M0(e,t,n)?.map(i=>({symbol:i.symbol,shortName:i.shortName,fromFile:i.fromFile}))??[]}function R0(e,t){let n=fe(e,t),i=I0(e,t);if(i.length>0&&!D0(n))return i;let r=L0(e,t,n);return mu(t)&&r.length>0?r:P0([...i,...r])}function E0(e,t,n={}){let i=lt(e,t);if(!i)return[];let r=mb(e,i),o=n.semantic===!1?null:db(e,i);return(o?w0(o,r):r).filter(a=>!a.used).map(a=>({symbol:a.symbol,shortName:a.shortName,importedIn:a.importer}))}function w0(e,t){let n=new Map;for(let r of t){let o=n.get(r.shortName);o?o.push(r):n.set(r.shortName,[r])}let i=e.map(r=>{let o=n.get(r.shortName),s=o?.shift();return o?.length===0&&n.delete(r.shortName),s?{...r,used:r.used||s.used}:r});return i.push(...[...n.values()].flat()),i}function I0(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
|
|
144
|
+
FROM mentions m
|
|
145
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
146
|
+
JOIN documents d ON c.document_id = d.id
|
|
147
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
148
|
+
WHERE gs.symbol LIKE ?
|
|
149
|
+
AND m.role = 2
|
|
150
|
+
ORDER BY d.relative_path`,`%${t}%`).filter(i=>!e.isIgnored(i.importer)).map(i=>({symbol:i.symbol,shortName:k(i.symbol),fromFile:i.importer}))}function L0(e,t,n=fe(e,t)){let i=n?.relativePath??null,r=n?re(n.symbol):t.replace(/\(\)$/,""),o=n?Le(n.symbol):!1,s=new Set;for(let l of he(e,{includeIgnored:!1}))for(let c of Ce(e,l))T0(c,l,{targetFile:i,targetLeaf:r,targetIsModule:o,targetPattern:t})&&s.add(l);let a=mu(t)?t.trim():null;return[...s].sort().map(l=>({symbol:a??n?.symbol??r,shortName:a??(n?k(n.symbol):r),fromFile:l}))}function D0(e){return!!(e&&(e.symbol.startsWith("scip-clojure ")||ye(e.relativePath)==="clojure"))}function P0(e){let t=new Set,n=[];for(let i of e){let r=`${i.symbol}|${i.fromFile}`;t.has(r)||(t.add(r),n.push(i))}return n.sort((i,r)=>i.fromFile.localeCompare(r.fromFile)||i.shortName.localeCompare(r.shortName))}function T0(e,t,n){return!e.sourcePath||n.targetFile&&pt(e.sourcePath)!==pt(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&_0(t)||e.kind==="namespace"&&F0(e,n.targetPattern)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function F0(e,t){let n=t.trim().replace(/\(\)$/,"");return mu(n)?e.importedName===n||e.localName===n:!1}function mu(e){let t=e.trim().replace(/\(\)$/,"");return t.includes(".")&&!t.includes("/")&&!t.includes(":")}function M0(e,t,n={}){let i=lt(e,t);return i?A0(e,i,n)??(n.semantic===!1?null:db(e,i))??mb(e,i):null}function A0(e,t,n){let r=e.all(`SELECT DISTINCT
|
|
151
|
+
gs.symbol,
|
|
152
|
+
def_d.relative_path AS from_file,
|
|
153
|
+
imp_d.relative_path AS importer,
|
|
154
|
+
EXISTS (
|
|
155
|
+
SELECT 1
|
|
156
|
+
FROM mentions ref_m
|
|
157
|
+
JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
|
|
158
|
+
WHERE ref_m.symbol_id = gs.id
|
|
159
|
+
AND ref_m.role != 1
|
|
160
|
+
AND ref_c.document_id = imp_d.id
|
|
161
|
+
) AS used
|
|
162
|
+
FROM mentions m
|
|
163
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
164
|
+
JOIN documents imp_d ON c.document_id = imp_d.id
|
|
165
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
166
|
+
LEFT JOIN (
|
|
167
|
+
SELECT m2.symbol_id, c2.document_id
|
|
168
|
+
FROM mentions m2
|
|
169
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
170
|
+
WHERE m2.role = 1
|
|
171
|
+
GROUP BY m2.symbol_id
|
|
172
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
173
|
+
LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
174
|
+
WHERE imp_d.relative_path = ?
|
|
175
|
+
AND m.role = 2
|
|
176
|
+
ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(r.length>0){let o=n.semantic===!1?[]:$r(e,t);return r.map(s=>({symbol:s.symbol,shortName:k(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 db(e,t){let n=$r(e,t);return n.length>0?n.map(i=>{let r=fb(i.importedName,i.localName,i.kind);return{symbol:r,shortName:r,fromFile:i.sourcePath??"(external)",importer:t,used:i.kind==="side-effect"?!0:i.isUsed}}):null}function mb(e,t){let n=N0(t,se(e,t));return Ce(e,t).map(i=>{let r=fb(i.importedName,i.localName,i.kind),o=i.kind==="side-effect"||k0(t,i)||n.has(i.localName??i.importedName)?!0:i.used;return{symbol:r,shortName:r,fromFile:i.sourcePath??"(external)",importer:t,used:o}})}function N0(e,t){let n=new Set;if(ye(e)!=="python")return n;let i=/(?:^|\n)\s*__all__\s*(?:\+?=)\s*[[(]([\s\S]*?)[\])]/g;for(let r of t.matchAll(i)){let o=r[1]??"";for(let s of o.matchAll(/(['"])([A-Za-z_]\w*)\1/g))n.add(s[2])}return n}function k0(e,t){if(ye(e)!=="rust"||t.used||t.kind==="side-effect")return!1;let n=t.localName??t.importedName;return n==="_"||/^[A-Z]/.test(n)}function fb(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 _0(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function B0(e,t){let n=fe(e,t);if(!n)return[];let r=new U(e).definitionsForFile(n.relativePath).filter(o=>o.symbol!==n.symbol).filter(o=>hm(n.symbol,o.symbol)).sort((o,s)=>o.startLine-s.startLine||o.endLine-s.endLine).map(o=>({symbol:o.symbol,shortName:k(o.symbol),startLine:o.startLine,endLine:o.endLine,kind:kn(o.symbol)??"unknown"}));return ye(n.relativePath)!=="clojure"?r:$0(r,O0(e,n))}function O0(e,t){let n=re(t.symbol);if(!n)return[];let i=k(t.symbol);return(ee(e,t.relativePath)?.clojureMembers??[]).filter(r=>r.ownerName===n).map(r=>({symbol:`${t.symbol}${r.memberName}().`,shortName:`${i}:${r.memberName}()`,startLine:r.startLine,endLine:r.endLine,kind:r.memberKind}))}function $0(e,t){let n=new Map;for(let i of[...e,...t])n.set(`${i.shortName}:${i.startLine}:${i.endLine}`,i);return[...n.values()].sort((i,r)=>i.startLine-r.startLine||i.endLine-r.endLine)}function j0(e,t){let n=fe(e,t);if(!n)return[];let i=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
|
|
177
|
+
FROM mentions m
|
|
178
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
179
|
+
JOIN (
|
|
180
|
+
SELECT m2.symbol_id, c2.document_id
|
|
181
|
+
FROM mentions m2
|
|
182
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
183
|
+
WHERE m2.role = 1
|
|
184
|
+
GROUP BY m2.symbol_id
|
|
185
|
+
) sym_def ON sym_def.symbol_id = m.symbol_id
|
|
186
|
+
WHERE m.symbol_id = ?
|
|
187
|
+
AND m.role != 1
|
|
188
|
+
AND sym_def.document_id != c.document_id`,n.symbolId);return[{name:k(n.symbol),count:i?.file_count??0,symbol:n.symbol,definedIn:n.relativePath}]}function H0(e,t){let n=lt(e,t);return n?e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
|
|
189
|
+
FROM mentions m
|
|
190
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
191
|
+
JOIN documents d ON c.document_id = d.id
|
|
192
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
193
|
+
JOIN (
|
|
194
|
+
SELECT m2.symbol_id, c2.document_id
|
|
195
|
+
FROM mentions m2
|
|
196
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
197
|
+
WHERE m2.role = 1
|
|
198
|
+
GROUP BY m2.symbol_id
|
|
199
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
200
|
+
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
201
|
+
WHERE d.relative_path = ?
|
|
202
|
+
AND m.role != 1
|
|
203
|
+
AND def_d.id != d.id
|
|
204
|
+
GROUP BY d.id
|
|
205
|
+
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 U0(e,t={}){return z0(e,t).map(n=>({name:k(n.symbol),count:n.file_count,symbol:n.symbol,definedIn:n.defined_in}))}function z0(e,t){let{limit:n=30,scope:i}=t,r=i?"AND def_d.relative_path LIKE ?":"",o=i?[`%${i}%`]:[];return e.all(`SELECT gs.symbol,
|
|
206
|
+
COUNT(DISTINCT c.document_id) AS file_count,
|
|
207
|
+
def_d.relative_path AS defined_in
|
|
208
|
+
FROM mentions m
|
|
209
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
210
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
211
|
+
JOIN (
|
|
212
|
+
SELECT m2.symbol_id, c2.document_id
|
|
213
|
+
FROM mentions m2
|
|
214
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
215
|
+
WHERE m2.role = 1
|
|
216
|
+
GROUP BY m2.symbol_id
|
|
217
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
218
|
+
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
219
|
+
WHERE m.role != 1
|
|
220
|
+
AND def_d.id != c.document_id
|
|
221
|
+
${e.pathExclusionsFor("def_d")}
|
|
222
|
+
${e.symbolNoiseFor("gs")}
|
|
223
|
+
${r}
|
|
224
|
+
GROUP BY gs.id
|
|
225
|
+
HAVING file_count > 1
|
|
226
|
+
ORDER BY file_count DESC
|
|
227
|
+
LIMIT ?`,...o,n)}function G0(e,t={}){let{limit:n=30,scope:i}=t,r=i?"AND d.relative_path LIKE ?":"",o=i?[`%${i}%`]:[];return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
|
|
228
|
+
FROM mentions m
|
|
229
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
230
|
+
JOIN documents d ON c.document_id = d.id
|
|
231
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
232
|
+
JOIN (
|
|
233
|
+
SELECT m2.symbol_id, c2.document_id
|
|
234
|
+
FROM mentions m2
|
|
235
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
236
|
+
WHERE m2.role = 1
|
|
237
|
+
GROUP BY m2.symbol_id
|
|
238
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
239
|
+
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
240
|
+
WHERE m.role != 1
|
|
241
|
+
AND def_d.id != d.id
|
|
242
|
+
${e.pathExclusionsFor("d")}
|
|
243
|
+
${e.symbolNoiseFor("gs")}
|
|
244
|
+
${r}
|
|
245
|
+
GROUP BY d.id
|
|
246
|
+
ORDER BY symbol_count DESC
|
|
247
|
+
LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}))}var pb=`SELECT COUNT(*) AS shared
|
|
248
|
+
FROM (
|
|
249
|
+
SELECT definition_m.symbol_id
|
|
250
|
+
FROM documents definition_d
|
|
251
|
+
JOIN chunks definition_c ON definition_c.document_id = definition_d.id
|
|
252
|
+
JOIN mentions definition_m ON definition_m.chunk_id = definition_c.id
|
|
253
|
+
AND definition_m.role = 1
|
|
254
|
+
JOIN mentions reference_m ON reference_m.symbol_id = definition_m.symbol_id
|
|
255
|
+
AND reference_m.role != 1
|
|
256
|
+
JOIN chunks reference_c ON reference_c.id = reference_m.chunk_id
|
|
257
|
+
JOIN documents reference_d ON reference_d.id = reference_c.document_id
|
|
258
|
+
WHERE definition_d.relative_path = ?
|
|
259
|
+
AND reference_d.relative_path = ?
|
|
260
|
+
UNION
|
|
261
|
+
SELECT definition_m.symbol_id
|
|
262
|
+
FROM documents definition_d
|
|
263
|
+
JOIN chunks definition_c ON definition_c.document_id = definition_d.id
|
|
264
|
+
JOIN mentions definition_m ON definition_m.chunk_id = definition_c.id
|
|
265
|
+
AND definition_m.role = 1
|
|
266
|
+
JOIN mentions reference_m ON reference_m.symbol_id = definition_m.symbol_id
|
|
267
|
+
AND reference_m.role != 1
|
|
268
|
+
JOIN chunks reference_c ON reference_c.id = reference_m.chunk_id
|
|
269
|
+
JOIN documents reference_d ON reference_d.id = reference_c.document_id
|
|
270
|
+
WHERE definition_d.relative_path = ?
|
|
271
|
+
AND reference_d.relative_path = ?
|
|
272
|
+
)`;function K0(e,t,n){let i=lt(e,t)??t,r=lt(e,n)??n,o=e.get(pb,i,r,r,i);return{...gb(i,r,o?.shared??0)}}function q0(e,t={}){let{limit:n=20,scope:i}=t,r=i?"AND def_d.relative_path LIKE ? AND ref_d.relative_path LIKE ?":"",o=i?[`%${i}%`,`%${i}%`]:[];return e.all(`SELECT
|
|
273
|
+
CASE WHEN def_d.relative_path < ref_d.relative_path THEN def_d.relative_path ELSE ref_d.relative_path END AS file1,
|
|
274
|
+
CASE WHEN def_d.relative_path < ref_d.relative_path THEN ref_d.relative_path ELSE def_d.relative_path END AS file2,
|
|
275
|
+
COUNT(DISTINCT gs.id) AS shared
|
|
276
|
+
FROM mentions m
|
|
277
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
278
|
+
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
279
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
280
|
+
JOIN (
|
|
281
|
+
SELECT m2.symbol_id, c2.document_id
|
|
282
|
+
FROM mentions m2
|
|
283
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
284
|
+
WHERE m2.role = 1
|
|
285
|
+
GROUP BY m2.symbol_id
|
|
286
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
287
|
+
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
288
|
+
WHERE m.role != 1
|
|
289
|
+
AND def_d.id != ref_d.id
|
|
290
|
+
${e.pathExclusionsFor("def_d","ref_d")}
|
|
291
|
+
${r}
|
|
292
|
+
GROUP BY file1, file2
|
|
293
|
+
ORDER BY shared DESC, file1, file2
|
|
294
|
+
LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.file1)&&!e.isIgnored(a.file2)).map(a=>gb(a.file1,a.file2,a.shared))}function gb(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 Ii(e){let t=new Map,n=[],i=new Map,r=new Map,o=new Set,s=[],a=0,l=c=>(e.get(c)??[]).values();for(let c of e.keys()){if(i.has(c))continue;let u=[];for(i.set(c,a),r.set(c,a),a+=1,s.push(c),o.add(c),u.push({node:c,iter:l(c),pendingChild:null});u.length>0;){let d=u[u.length-1];if(d.pendingChild!==null){let p=d.pendingChild;d.pendingChild=null,r.set(d.node,Math.min(r.get(d.node),r.get(p)))}let m=d.iter.next();if(m.done){if(r.get(d.node)===i.get(d.node)){let p=[];for(;;){let g=s.pop();if(o.delete(g),p.push(g),t.set(g,n.length),g===d.node)break}n.push(p)}u.pop();continue}let f=m.value;i.has(f)?o.has(f)&&r.set(d.node,Math.min(r.get(d.node),i.get(f))):(i.set(f,a),r.set(f,a),a+=1,s.push(f),o.add(f),d.pendingChild=f,u.push({node:f,iter:l(f),pendingChild:null}))}}return{components:n,componentOf:t}}function mo(e,t={}){return bb(e,t).cycles}function bb(e,t={}){return Sb(e,t)}function Sb(e,t={}){let{scope:n,maxDepth:i=10,edgeBasis:r="symbol-references"}=t,o=Be(e,n,r==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-only"}:void 0),{components:s}=Ii(o),a=s.filter(l=>W0(o,l)).map(l=>{let c=[...l].sort(),u=V0(o,c),d=Y0(u);return{path:u,component:c,edgeBasis:r,witness:!0,classification:d==="real"?"dependency-cycle":"module-structure-candidate",kind:d}});return a.sort((l,c)=>l.kind!==c.kind?l.kind==="real"?-1:1:l.path.length-c.path.length),{cycles:a,truncated:!1,edgeBasis:r,maxDepth:i}}function W0(e,t){if(t.length>1)return!0;let n=t[0];return n!==void 0&&e.get(n)?.has(n)===!0}function V0(e,t){let n=t[0];if(!n)return[];let i=new Set(t);for(let r of[...e.get(n)??[]].filter(o=>i.has(o)).sort()){if(r===n)return[n,n];let o=J0(e,r,n,i);if(o)return[n,...o]}throw new Error(`Cyclic component did not contain a witness path from ${n}.`)}function J0(e,t,n,i){let r=[t],o=new Map([[t,null]]);for(let s=0;s<r.length;s+=1){let a=r[s];if(a===n){let l=[];for(let c=a;c!==null;c=o.get(c)??null)l.push(c);return l.reverse()}for(let l of[...e.get(a)??[]].filter(c=>i.has(c)).sort())o.has(l)||(o.set(l,a),r.push(l))}return null}function Y0(e){for(let i of e){let r=V(i);if(r==="test"||r==="barrel"||r==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":Ki(t)||Ki(n)||hb(t,n)||hb(n,t)||yb(t,n)||yb(n,t)||V(t)==="entry"||V(n)==="entry"?"module-hierarchy":"real"}function hb(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=t.replace(/\.rs$/,"/");return e.startsWith(n)?!e.slice(n.length).includes("/"):!1}function yb(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=e.replace(/\.rs$/,""),i=t.replace(/\.rs$/,"");if(n===i+"_tests"||n===i+"/tests")return!0;let r=e.split("/"),o=t.split("/");if(r.length===o.length&&r.includes("tests")&&o.includes("src")){let s=r[r.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}import{readdirSync as X0}from"fs";import{join as vb}from"path";function Jn(e,t){return ef(e,t)}function Z0(e){return Cb(e).replace(/\/\*\*?$/,"")}function Ra(e,t){let n=Cb(t),i=Z0(n),r=n.endsWith("/**"),o=[],s=(a,l)=>{let c;try{c=X0(a,{withFileTypes:!0})}catch{return}for(let u of c){if(u.name.startsWith("."))continue;let d=l?`${l}/${u.name}`:u.name;Jn(n,d)&&o.push(d),r&&u.isDirectory()&&s(vb(a,u.name),d)}};return s(vb(e,i),i),o.sort()}function Cb(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}var Q0=/\.(test|spec)\.(ts|tsx|js|jsx|mts|cts)$/,xb=new Map;function Rb(e,t,n,i){if(!t?.testPaths?.length)return[];let r=eA(t),o=[];for(let s of tA(e,t.testPaths)){let a=nA(e,s,i),l=a?n(a):null;if(l)for(let c of Ce(e,s)){let u=c.sourcePath;if(!u)continue;let d=n(u);d&&d!==l&&(r.get(l)?.has(d)||o.push({testFile:s,ownerBoundary:l,importedFile:u,importedBoundary:d,reason:"outside-owner-policy"}))}}return iA(o)}function eA(e){let t=e.allowedDependencies??{},n=e.boundaries.map(s=>s.name),i=new Map,r=(s,a)=>{for(let l of t[s]??[])a.has(l)||(a.add(l),r(l,a))};for(let s of n){let a=new Set;r(s,a),i.set(s,a)}let o=new Map;for(let s of n){let a=new Set(i.get(s));for(let l of n)l!==s&&i.get(l)?.has(s)&&a.add(l);o.set(s,a)}return o}function tA(e,t){let n=`${e.config.projectRoot}\0${t.join("\0")}`,i=xb.get(n);if(i)return i;let r=new Set;for(let s of t)for(let a of Ra(e.config.projectRoot,s))Q0.test(a)&&r.add(a);let o=[...r].sort();return xb.set(n,o),o}function nA(e,t,n){let i=t.replace(/^tests\//,"src/").replace(/\.(test|spec)\.(\w+)$/,".$2");if(i!==t&&n(i))return i;let r=t.split("/").pop().replace(/\.(test|spec)\.(\w+)$/,".$2"),o=Ce(e,t).map(s=>s.sourcePath).filter(s=>!!s&&n(s)&&s.split("/").pop()===r);return o.length===1?o[0]:null}function iA(e){let t=new Map;for(let n of e){let i=`${n.testFile}\0${n.importedBoundary}`;t.has(i)||t.set(i,n)}return[...t.values()].sort((n,i)=>n.testFile.localeCompare(i.testFile)||n.importedBoundary.localeCompare(i.importedBoundary))}function Eb(e,t){let n=(e?.boundaries??[]).filter(i=>i.paths.some(r=>Jn(r,t)));return n.length===1?n[0].name:null}var Tn="architecture:";function wb(e,t,n,i={}){let r=oA(e,t);if(!n||n.boundaries.length===0)return{configured:!1,boundaries:[],edges:[],forbiddenEdges:[],reciprocalPairs:[],cycles:[],coarseBoundaries:[],staleAllowances:[],boundaryLimits:[],fragileEdges:[],testBoundaryViolations:[],coverage:{totalFiles:r.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=[],l=[];for(let y of r){let E=n.boundaries.filter(w=>w.paths.some(b=>Jn(b,y))).map(w=>w.name).sort();if(E.length===0)a.push(y);else if(E.length>1)l.push({file:y,boundaries:E});else{let w=E[0];o.set(y,w),s.get(w).add(y)}}let c=new Map;for(let[y,E]of e){let w=o.get(y);if(w)for(let b of E){let R=o.get(b);if(!R||w===R)continue;let C=rr(w,R),L=c.get(C);L||(L={from:w,to:R,fileEdges:[],importers:new Set,importedFiles:new Set},c.set(C,L)),L.fileEdges.push({fromFile:y,toFile:b}),L.importers.add(y),L.importedFiles.add(b)}}let u=[...c.values()].map(y=>sA(y,n)).sort(pA),d=u,m=new Map(d.map(y=>[rr(y.from,y.to),y])),f=new Map(n.boundaries.map(y=>[y.name,new Set]));for(let y of d)f.get(y.from).add(y.to);let p=[];for(let y of d){if(y.from>=y.to)continue;let E=m.get(rr(y.to,y.from));E&&p.push({boundaries:[y.from,y.to],forward:y,reverse:E})}let{components:g}=Ii(f),h=g.filter(y=>y.length>1).map(y=>lA(y,d,n.requireAcyclic===!0)).sort((y,E)=>E.boundaries.length-y.boundaries.length||y.boundaries.join("/").localeCompare(E.boundaries.join("/"))),S=n.allowedDependencies??{},v=n.boundaries.map(y=>y.name).filter(y=>!Object.hasOwn(S,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(S,y.name)})).sort((y,E)=>y.name.localeCompare(E.name)),edges:u,forbiddenEdges:d.filter(y=>y.policyStatus==="forbidden"),reciprocalPairs:p,cycles:h,staleAllowances:uA(n,d),boundaryLimits:dA(n,d,s),fragileEdges:d.filter(y=>y.fragile),testBoundaryViolations:i.testBoundaryViolations??[],coarseBoundaries:cA(e,s,i.isModuleHierarchyFile,n.requireResolvedBoundaries===!0,y=>n.boundaries.find(E=>E.name===y)?.subUnits??"directory"),coverage:{totalFiles:r.length,mappedFiles:o.size,unmappedFiles:a,ambiguousFiles:l},policyCoverage:{declaredRows:n.boundaries.length-v.length,totalBoundaries:n.boundaries.length,missingRows:v,requiresCompletePolicy:n.requireCompletePolicy===!0,requiresCompleteCoverage:n.requireCompleteCoverage===!0,requiresMinimalPolicy:n.requireMinimalPolicy===!0}}}function fo(e,t={}){let n=Be(e,t.scope,{scipEdges:"imports-only",sourceEdges:"imports-and-reexports"}),i=he(e,{includeIgnored:!1}).filter(o=>!t.scope||o.includes(t.scope)),r=new Set(i);return wb(n,i,e.config.architecture,{isModuleHierarchyFile:o=>rA(e,o),testBoundaryViolations:Rb(e,e.config.architecture,o=>Eb(e.config.architecture,o),o=>r.has(o))})}function rA(e,t){let n=V(t);return n==="test"||n==="entry"?!0:n!=="barrel"?!1:J(e,t).length===0}function fu(e){let t=e.forbiddenEdges.map(i=>`${Tn}forbidden-edge:${encodeURIComponent(i.from)}:${encodeURIComponent(i.to)}`);if(e.policyCoverage.requiresCompletePolicy)for(let i of e.policyCoverage.missingRows)t.push(`${Tn}missing-policy-row:${encodeURIComponent(i)}`);if(e.policyCoverage.requiresCompleteCoverage){for(let i of e.coverage.unmappedFiles)t.push(`${Tn}unmapped-file:${encodeURIComponent(i)}`);for(let i of e.coverage.ambiguousFiles)t.push(`${Tn}ambiguous-file:${encodeURIComponent(i.file)}:${i.boundaries.map(r=>encodeURIComponent(r)).sort().join("|")}`)}if(e.policyCoverage.requiresMinimalPolicy)for(let i of e.staleAllowances)t.push(`${Tn}stale-allowance:${encodeURIComponent(i.from)}:${encodeURIComponent(i.to)}`);for(let i of e.testBoundaryViolations)t.push(`${Tn}test-boundary:${encodeURIComponent(i.testFile)}:${encodeURIComponent(i.importedBoundary)}`);for(let i of e.boundaryLimits)t.push(`${Tn}boundary-limit:${i.kind}:${encodeURIComponent(i.boundary)}`);let n=new Map;for(let i of e.coarseBoundaries)i.violatesPolicy&&n.set(i.boundary,(n.get(i.boundary)??0)+1);for(let[i,r]of n){let o=`${Tn}coarse-boundary:${encodeURIComponent(i)}`;t.push(o);for(let s=2;s<=r;s+=1)t.push(`${o}:component:${s}`)}for(let i of e.cycles)i.violatesPolicy&&t.push(`${Tn}cycle:${i.boundaries.map(r=>encodeURIComponent(r)).sort().join("|")}`);return[...new Set(t)].sort()}function oA(e,t){let n=new Set(t);for(let[i,r]of e){n.add(i);for(let o of r)n.add(o)}return[...n].sort()}function sA(e,t){let n=[...e.fileEdges].sort((i,r)=>i.fromFile.localeCompare(r.fromFile)||i.toFile.localeCompare(r.toFile));return{from:e.from,to:e.to,policyStatus:aA(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 aA(e,t,n){return!e.allowedDependencies||!Object.hasOwn(e.allowedDependencies,t)?"undeclared":e.allowedDependencies[t].includes(n)?"allowed":"forbidden"}function lA(e,t,n){let i=[...e].sort(),r=new Set(i),o=t.filter(a=>r.has(a.from)&&r.has(a.to)),s=Math.min(...o.map(a=>a.fileEdgeCount));return{boundaries:i,internalEdges:o,narrowestEdges:o.filter(a=>a.fileEdgeCount===s),violatesPolicy:n}}function cA(e,t,n=mA,i=!1,r=()=>"directory"){let o=[];for(let[s,a]of t){let l=r(s)==="file"?p=>p:fA,c=[...a].filter(p=>!n(p));if(c.length<2)continue;let u=new Set(c),d=new Map,m=new Map;for(let p of c)m.set(l(p),new Set);for(let p of c)for(let g of e.get(p)??[]){if(!u.has(g))continue;let h=l(p),S=l(g);if(h===S)continue;let v=rr(h,S),y=d.get(v);y||(y={from:h,to:S,fileEdges:[]},d.set(v,y)),y.fileEdges.push({fromFile:p,toFile:g}),m.get(h).add(S)}let{components:f}=Ii(m);for(let p of f){if(p.length<2)continue;let g=new Set(p),h=[...d.values()].filter(v=>g.has(v.from)&&g.has(v.to)).map(v=>({from:v.from,to:v.to,fileEdgeCount:v.fileEdges.length,examples:v.fileEdges.slice(0,5)})).sort((v,y)=>v.from.localeCompare(y.from)||v.to.localeCompare(y.to)),S=Math.min(...h.map(v=>v.fileEdgeCount));o.push({boundary:s,violatesPolicy:i,subUnits:[...p].sort(),internalEdges:h,narrowestEdges:h.filter(v=>v.fileEdgeCount===S)})}}return o.sort((s,a)=>a.subUnits.length-s.subUnits.length||s.boundary.localeCompare(a.boundary))}function uA(e,t){let n=new Set(t.map(s=>rr(s.from,s.to))),i=e.allowedDependencies??{},r=new Set(e.boundaries.map(s=>s.name)),o=[];for(let[s,a]of Object.entries(i))if(r.has(s))for(let l of a)!r.has(l)||n.has(rr(s,l))||o.push({from:s,to:l});return o.sort((s,a)=>s.from.localeCompare(a.from)||s.to.localeCompare(a.to))}function dA(e,t,n){let i=[],r=new Map;for(let o of t)r.set(o.from,(r.get(o.from)??0)+1);for(let o of e.boundaries){if(e.maxBoundaryFanOut!==void 0){let a=r.get(o.name)??0;a>e.maxBoundaryFanOut&&i.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&&i.push({boundary:o.name,kind:"files",observed:a,limit:s})}}return i.sort((o,s)=>o.boundary.localeCompare(s.boundary)||o.kind.localeCompare(s.kind))}function mA(e){let t=V(e);return t==="test"||t==="entry"}function fA(e){let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)}function rr(e,t){return`${e}\0${t}`}function pA(e,t){return e.from.localeCompare(t.from)||e.to.localeCompare(t.to)}function gA(e,t={}){let{limit:n=20,scope:i,minFanIn:r=2,minFanOut:o=2,scanLimit:s}=t,a=new U(e),l=Ae(a.productionCallableDefinitions({scope:i,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s),c=t.semantic!==!1,u=Qt(e,l,{limit:500,semantic:c,semanticEvidence:pe}),d=a.calleeEvidenceMap(l,{semantic:c}),m=new Set([...u.incompleteSymbolIds,...d.incompleteSymbolIds]),f=new Set([...u.unavailableSymbolIds,...d.unavailableSymbolIds]);return{rows:l.filter(g=>!m.has(g.symbolId)&&!f.has(g.symbolId)).map(g=>yA(g,u.rows.get(g.symbolId)??[],d.rows.get(g.symbolId)??[])).filter(g=>g.fanIn>=r&&g.fanOut>=o).sort((g,h)=>h.score-g.score||h.fanIn-g.fanIn).slice(0,n),coverage:hA(c,m,f)}}function hA(e,t,n){let i=e?t.size>0&&n.size>0?"incomplete-and-unavailable":t.size>0?"incomplete":n.size>0?"unavailable":"complete":"disabled";return{semanticEvidence:{enabled:e,status:i,incompleteSymbolCount:t.size,unavailableSymbolCount:n.size,excludedSymbolCount:new Set([...t,...n]).size}}}function yA(e,t,n){let i=[...new Set(t.map(d=>d.file))].sort(),r=[...new Set(t.filter(d=>d.source!=="caller-map-inversion"||d.callEvidence==="scip-chunk").map(d=>d.file))].sort(),o=new Map;for(let d of n.slice(0,500)){if(d.file===e.relativePath)continue;let m=`${d.symbol}|${d.file}`;o.has(m)||o.set(m,{symbol:d.symbol,shortName:k(d.symbol),file:d.file,evidenceStrength:d.source==="scip-chunk"?"candidate":"exact",evidenceSource:d.source})}let s=[...o.values()].sort((d,m)=>d.file.localeCompare(m.file)||d.symbol.localeCompare(m.symbol)),a=i.length,l=s.length,c=a*l,u=s.filter(d=>d.evidenceStrength==="candidate").map(d=>d.symbol);return{symbol:e.symbol,shortName:k(e.symbol),fanIn:a,fanOut:l,callerFiles:i,candidateCallerFiles:r,externalCallees:s.map(({symbol:d,shortName:m,file:f})=>({symbol:d,shortName:m,file:f})),externalCalleeEvidence:s,candidateExternalCallees:u,inputBasis:"mixed-static-call-or-reference-evidence",score:c,definedIn:e.relativePath,actionTier:"signal",riskKind:"coordination-hotspot",evidenceReasons:[`${a} incoming file(s) reference this symbol`,`${l} distinct cross-file callee symbol(s) are reached from it`,`centrality score is ${c} (fan-in * fan-out)`,`${r.length} incoming file(s) and ${u.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 po(e,t={}){let{scope:n,minLoc:i=3,scanLimit:r}=t,o=new U(e),s=t.semantic!==!1,a=0,l=$("isolated.candidates",()=>{let b=Ae(o.productionCallableDefinitions({scope:n,minLoc:i,excludeEntrySurfaces:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:typeof r=="number"&&r>0}),r).filter(R=>!ir(e,R));return a=b.length,b},()=>({definitions:a})),c=0,u=$("isolated.strict-callees",()=>{let w=o.symbolsWithNonSelfCallees(l,{additive:!1,semantic:!1});return c=w.size,w},()=>({definitions:l.length,symbols:c})),d=l.filter(w=>!u.has(w.symbolId)),m=0,f=$("isolated.scip-callers",()=>{let w=o.crossFileCallerMap(d,{semantic:!1});return m=w.size,w},()=>({definitions:d.length,symbols:m})),p=new Set(f.keys());for(let w of o.frameworkReferencedSymbolIds(d))p.add(w);let g=d.filter(w=>!p.has(w.symbolId));if(s&&g.length>0){let w=Cn(e,g);for(let b of w.callers.keys())p.add(b);for(let b of w.incompleteSymbolIds)p.add(b);for(let b of w.unavailableSymbolIds)p.add(b);for(let b of o.symbolsWithNonSelfCallees(g,{additive:!1,semantic:!0}))u.add(b);g=g.filter(b=>!p.has(b.symbolId)).filter(b=>!u.has(b.symbolId))}let h=0,S=$("isolated.source-fallback-callers",()=>{let w=o.sourceFallbackCallerFiles(g,{skipPath:b=>V(b)==="test"});return h=w.size,w},()=>({definitions:g.length,symbols:h}));for(let w of S.keys())p.add(w);let v=g.filter(w=>!p.has(w.symbolId)),y=0,E=$("isolated.additive-callees",()=>{let w=o.symbolsWithNonSelfCallees(v,{additive:!0,semantic:s});return y=w.size,w},()=>({definitions:v.length,symbols:y}));for(let w of E)u.add(w);return v.filter(w=>!u.has(w.symbolId)).sort((w,b)=>de(b)-de(w)||w.relativePath.localeCompare(b.relativePath)||w.startLine-b.startLine).map(w=>({symbol:w.symbol,shortName:k(w.symbol),relativePath:w.relativePath,startLine:w.startLine,endLine:w.endLine,loc:de(w)}))}import{SymbolInformation_Kind as Qe}from"@c4312/scip";var Ib=500;function bA(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),i=tf.get(n);if(i!==void 0)return i;for(let[r,o]of us)if(o.toLowerCase().includes(n))return r;return null}function SA(e,t,n={}){let{scope:i,limit:r=100}=n,o=bA(t);return o===null?[]:CA(e,i).map(a=>({row:a,resolvedKind:Db(a)})).filter(a=>a.resolvedKind===o).slice(0,r).map(({row:a,resolvedKind:l})=>({symbol:a.symbol,shortName:k(a.symbol),kind:l,kindName:Rr(l),relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function vA(e,t={}){let n=xA(e,t.scope);for(let i of RA(e,t.scope)){let r=Db(i);r===null||r===0||n.set(r,(n.get(r)??0)+1)}return[...n.entries()].sort((i,r)=>r[1]-i[1]||i[0]-r[0]).map(([i,r])=>({kind:i,kindName:Rr(i),count:r}))}function CA(e,t){return ze(e,{scope:t}).map(EA)}function xA(e,t){let n=new Map;for(let i of Lb(he(e,{scope:t,includeIgnored:!1}))){let r=i.map(()=>"?").join(", "),o=e.all(`SELECT gs.kind AS kind, COUNT(*) AS count
|
|
295
|
+
FROM defn_enclosing_ranges der
|
|
296
|
+
JOIN global_symbols gs ON der.symbol_id = gs.id
|
|
297
|
+
JOIN documents d ON der.document_id = d.id
|
|
298
|
+
WHERE gs.kind IS NOT NULL
|
|
299
|
+
AND gs.kind != 0
|
|
300
|
+
AND gs.symbol NOT LIKE '%#'
|
|
301
|
+
AND d.relative_path IN (${r})
|
|
302
|
+
GROUP BY gs.kind`,...i);for(let s of o)n.set(s.kind,(n.get(s.kind)??0)+s.count)}return n}function RA(e,t){let n=[];for(let i of Lb(he(e,{scope:t,includeIgnored:!1}))){let r=i.map(()=>"?").join(", ");n.push(...e.all(`SELECT gs.symbol,
|
|
303
|
+
gs.kind,
|
|
304
|
+
gs.documentation,
|
|
305
|
+
gs.enclosing_symbol,
|
|
306
|
+
d.relative_path,
|
|
307
|
+
der.start_line,
|
|
308
|
+
der.end_line
|
|
309
|
+
FROM defn_enclosing_ranges der
|
|
310
|
+
JOIN global_symbols gs ON der.symbol_id = gs.id
|
|
311
|
+
JOIN documents d ON der.document_id = d.id
|
|
312
|
+
WHERE (gs.kind IS NULL OR gs.kind = 0 OR gs.symbol LIKE '%#')
|
|
313
|
+
${e.symbolNoiseFor("gs")}
|
|
314
|
+
AND d.relative_path IN (${r})
|
|
315
|
+
ORDER BY d.relative_path, der.start_line, der.end_line, gs.symbol`,...i))}return n}function Lb(e){let t=[];for(let n=0;n<e.length;n+=Ib)t.push(e.slice(n,n+Ib));return t}function EA(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 Db(e){return e.kind!==null&&e.kind!==0?wA(e.kind,e.symbol,e.documentation):IA(e.symbol,e.documentation,e.enclosing_symbol)}function wA(e,t,n){let i=(n??"").toLowerCase();if(kn(t)==="type"){if(i.includes("type "))return Qe.TypeAlias;if(i.includes("interface "))return Qe.Interface;if(i.includes("struct "))return Qe.Struct;if(i.includes("trait "))return Qe.Trait;if(i.includes("class "))return Qe.Class}return e}function IA(e,t,n){let i=Ni(e);if("kind"in i)return null;let r=i.descriptors,o=r[r.length-2]??null,s=kn(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?Qe.TypeAlias:a.includes("interface ")?Qe.Interface:a.includes("struct ")?Qe.Struct:a.includes("trait ")?Qe.Trait:a.includes("class ")?Qe.Class:Qe.Class:s==="method"?o?.suffix==="type"?Qe.Method:Qe.Function:s==="namespace"?Qe.Module:s!=="term"?null:a.includes("async def ")||a.includes("def ")?Qe.Function:(n?kn(n):o?.suffix??null)==="type"?Qe.Field:Qe.Variable}function LA(e,t={}){let{limit:n=10,scope:i,minDepth:r=3,edgeBasis:o="symbol-references"}=t,s=Be(e,i,o==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-only"}:void 0),{components:a,componentOf:l}=Ii(s),c=new Map;for(let h=0;h<a.length;h++)c.set(h,new Set);for(let[h,S]of s){let v=l.get(h);for(let y of S){let E=l.get(y);E!==v&&c.get(v).add(E)}}let u=new Array(a.length),d=new Array(a.length);for(let h=0;h<a.length;h++){let S=[],v=0;for(let y of[...c.get(h)].sort((E,w)=>E-w)){let E=d[y];(E>v||E===v&&DA(u[y],S,a)<0)&&(v=E,S=u[y])}u[h]=[h,...S],d[h]=1+v}function m(h){return u[h]}let f=a.map(h=>[...h].sort()),p=new Set,g=[];for(let h=0;h<a.length;h++){let v=m(h).map(w=>f[w]),y=v.map(w=>w[0]);if(v.length<r)continue;let E=y.join(" ");p.has(E)||(p.add(E),g.push(PA(y,v,o)))}return g.sort((h,S)=>S.depth-h.depth||h.chain.join("\0").localeCompare(S.chain.join("\0"))),TA(g).slice(0,n)}function DA(e,t,n){if(t.length===0)return-1;let i=e.map(o=>[...n[o]].sort()[0]??"").join("\0"),r=t.map(o=>[...n[o]].sort()[0]??"").join("\0");return i.localeCompare(r)}function PA(e,t,n){let i=t.reduce((o,s)=>o+s.length,0),r=t.filter(o=>o.length>1).length;return{chain:e,components:t,depth:t.length,fileCount:i,edgeBasis:n,actionTier:"signal",chainKind:"transitive-dependency-depth",evidenceReasons:[`${t.length} condensed dependency component(s) form the representative transitive path`,`${i} file(s) are represented; ${r} 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 TA(e){let t=[];for(let n of e)t.some(i=>FA(n.chain,i.chain))||t.push(n);return t}function FA(e,t){if(e.length>=t.length)return!1;let n=t.length-e.length;for(let i=0;i<e.length;i++)if(e[i]!==t[n+i])return!1;return!0}function MA(e,t){let n=fe(e,t);if(!n)return[];let i=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
|
|
316
|
+
WHERE id = ? LIMIT 1`,n.symbolId);if(!i)return[];let r=[{symbol:i.symbol,shortName:k(i.symbol),depth:0}],o=i.enclosing_symbol,s=1,a=new Set([i.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;r.push({symbol:d.symbol,shortName:k(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(r.length>1)return r;let l=Ni(i.symbol);if("kind"in l)return r;let c=l.descriptors;if(c.length<=1)return r;let u=[r[0]];for(let d=c.length-2,m=1;d>=0;d--,m++){let p=c.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:p,shortName:p,depth:m})}return u}function AA(e,t={}){let i=new U(e).productionCallableDefinitions({scope:t.scope,requireCallableSymbol:!0,includeSuppressed:!0}),r=Mb(e,i),o=t.search?.trim().toLocaleLowerCase();return i.map(s=>Ab(e,s,r.get(s.symbolId)??[])).filter(s=>s!==null).map(s=>s.result).filter(s=>!o||_A(s).includes(o)).sort(BA)}function NA(e,t,n={}){let i=rt(e,t);if(!i.match)return{kind:"missing",query:t};if(i.total>1)return{kind:"ambiguous",query:t,total:i.total,candidates:[{symbol:i.match.symbol,shortName:k(i.match.symbol),relativePath:i.match.relativePath,startLine:i.match.startLine},...i.candidates]};let r=new U(e),o=r.definitionsForFile(i.match.relativePath).find(f=>f.symbol===i.match.symbol);if(!o?.isFunctionLike)return{kind:"not-entry",query:t,symbol:i.match.symbol,shortName:k(i.match.symbol),file:i.match.relativePath,reason:"The resolved symbol is not a callable definition."};let s=Mb(e,[o]),a=Ab(e,o,s.get(o.symbolId)??[]);if(!a)return{kind:"not-entry",query:t,symbol:o.symbol,shortName:k(o.symbol),file:o.relativePath,reason:"The callable is neither an external root nor an uncalled callable on a detected entry surface."};let l=OA(e,r,o),c=new Set(n.expand??[]),u=UA(l,c),d=new Set(u.regions.filter(f=>f.expanded).map(f=>f.id)),m=[...c].filter(f=>!d.has(f)).sort();return{kind:"matched",query:t,entry:a.result,regions:u.regions,regionEdges:u.regionEdges,unmatchedExpansions:m,coverage:{completeWithinIndexedStaticCallEdges:!0,completeWithinSelectedStaticEvidence:!0,candidateReachabilityIncluded:l.edges.some(f=>f.evidenceStrength==="candidate"),dynamicDispatchRepresented:!1,symbolCount:l.symbols.length,symbolEdgeCount:l.edges.length,exactSymbolEdgeCount:l.edges.filter(f=>f.evidenceStrength==="exact").length,candidateSymbolEdgeCount:l.edges.filter(f=>f.evidenceStrength==="candidate").length,regionCount:u.regions.length,regionEdgeCount:u.regionEdges.length,externalCallCount:l.externalCalls.length}}}function Mb(e,t){let n=t.filter(i=>Nb(e,i.relativePath)||qi(e,i.symbol,i.relativePath).length>0);return mf(e,n,{semantic:!1,semanticEvidence:pe})}function Ab(e,t,n){let i=kA(e,t),r=i.length>0,o=Nb(e,t.relativePath)&&n.length===0;if(!r&&!o)return null;let s=[...i];return o&&s.push("entry-surface-without-indexed-caller"),{definition:t,result:{symbol:t.symbol,shortName:k(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,documentation:t.documentation,confidence:r?"root":"candidate",evidence:s,indexedCallerCount:n.length}}}function Nb(e,t){return Ye(e,t)||/(?:^|\/)entry\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(t)}function kA(e,t){let n=qi(e,t.symbol,t.relativePath),i=[];return Pb(n,["package-surface-file","transitive-package-surface"])&&Ct(e,t)&&i.push("package-public-export"),n.includes("rust-public-library")&&i.push("rust-public-library"),n.includes("framework-entrypoint")&&i.push("framework-dispatched-export"),Pb(n,["configured-file","configured-path-prefix","configured-qualified-var","configured-symbol-pattern"])&&i.push("configured-entry-root"),i}function Pb(e,t){return t.some(n=>e.includes(n))}function _A(e){return[e.symbol,e.shortName,e.file,e.documentation??"",...e.evidence].join(`
|
|
317
|
+
`).toLocaleLowerCase()}function BA(e,t){return Tb(e.confidence)-Tb(t.confidence)||e.file.localeCompare(t.file)||e.startLine-t.startLine||e.symbol.localeCompare(t.symbol)}function Tb(e){return e==="root"?0:1}function OA(e,t,n){let i=new Map([[n.symbol,0]]),r=new Map,o=new Map([[n.symbol,n]]),s=new Map,a=new Map,l=[n];for(;l.length>0;){let c=t.calleeMap(l,{additive:!1,semantic:!1}),u=[];for(let d of l){let m=i.get(d.symbol)??0;r.set(d.symbol,Fb(d,m));for(let f of c.get(d.symbolId)??[]){let p=$A(t,f,o);if(!p){let v=HA(d,f);a.set(KA(v),v);continue}let g=m+1,h=i.get(p.symbol);(h===void 0||g<h)&&i.set(p.symbol,g),r.set(p.symbol,Fb(p,Math.min(g,h??g)));let S=jA(d,p,f);s.set(GA(S),S),h===void 0&&u.push(p)}}l=u}return{symbols:[...r.values()].sort(qA),edges:[...s.values()].sort(WA),externalCalls:[...a.values()].sort(VA)}}function $A(e,t,n){let i=n.get(t.symbol);if(i)return i;let r=e.definitionsForFile(t.file).find(o=>o.symbol===t.symbol)??null;return r&&n.set(r.symbol,r),r}function Fb(e,t){return{symbol:e.symbol,shortName:k(e.symbol),file:e.relativePath,depth:t}}function jA(e,t,n){return{fromSymbol:e.symbol,fromShortName:k(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:k(t.symbol),toFile:t.relativePath,source:n.source,evidenceStrength:n.source==="scip-chunk"?"candidate":"exact"}}function HA(e,t){return{fromSymbol:e.symbol,fromShortName:k(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:k(t.symbol),reportedFile:t.file,source:t.source,evidenceStrength:t.source==="scip-chunk"?"candidate":"exact"}}function UA(e,t){let n=go(e.symbols,c=>c.file),i=go(e.edges.filter(c=>c.fromFile===c.toFile),c=>c.fromFile),r=go(e.externalCalls,c=>c.fromFile),o=zA(e.edges.filter(c=>c.fromFile!==c.toFile)),s=go(o,c=>c.toRegionId),a=go(o,c=>c.fromRegionId);return{regions:[...n.entries()].map(([c,u])=>{let d=pu(c),m=t.has(d),f=i.get(c)??[],p=r.get(c)??[];return{id:d,file:c,minDepth:Math.min(...u.map(g=>g.depth)),symbolCount:u.length,internalEdgeCount:f.length,externalCallCount:p.length,incomingRegionIds:ho((s.get(d)??[]).map(g=>g.fromRegionId)),outgoingRegionIds:ho((a.get(d)??[]).map(g=>g.toRegionId)),expanded:m,symbols:m?u:[],internalEdges:m?f:[],externalCalls:m?p:[]}}).sort((c,u)=>c.minDepth-u.minDepth||c.file.localeCompare(u.file)),regionEdges:o}}function zA(e){let t=new Map;for(let n of e){let i=`${n.fromFile}\0${n.toFile}`,r=t.get(i)??[];r.push(n),t.set(i,r)}return[...t.values()].map(n=>{let i=n[0];return{fromRegionId:pu(i.fromFile),fromFile:i.fromFile,toRegionId:pu(i.toFile),toFile:i.toFile,callCount:n.length,exactCallCount:n.filter(r=>r.evidenceStrength==="exact").length,candidateCallCount:n.filter(r=>r.evidenceStrength==="candidate").length,fromSymbols:ho(n.map(r=>r.fromShortName)),toSymbols:ho(n.map(r=>r.toShortName)),evidence:ho(n.map(r=>r.source))}}).sort((n,i)=>n.fromFile.localeCompare(i.fromFile)||n.toFile.localeCompare(i.toFile))}function go(e,t){let n=new Map;for(let i of e){let r=t(i),o=n.get(r)??[];o.push(i),n.set(r,o)}return n}function pu(e){return`file:${e}`}function ho(e){return[...new Set(e)].sort()}function GA(e){return`${e.fromSymbol}\0${e.toSymbol}`}function KA(e){return`${e.fromSymbol}\0${e.toSymbol}`}function qA(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function WA(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function VA(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function Bt(e,t){let n=new Set;for(let i of e)t.has(i)&&n.add(i);return n}function et(e,t){let n=new Set;for(let i of e)t.has(i)||n.add(i);return n}function Yn(e,t){if(e.size===0&&t.size===0)return 0;let n=0;for(let r of e)t.has(r)&&(n+=1);let i=e.size+t.size-n;return i===0?0:n/i}function kb(e,t){if(e.size===0)return 0;let n=0;for(let i of e)t.has(i)&&(n+=1);return n/e.size}function gu(e,t){if(t<=0)return new Map;let n=new Map;for(let[i,r]of e)r>0&&n.set(i,Math.log(t/r));return n}function or(e){let t=[...e.values()].sort((i,r)=>i-r);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 sr(e,t){let n=0;for(let i of e){let r=t.get(i)??0;n+=r*r}return Math.sqrt(n)}function _b(e,t,n,i={}){let r=0,o=0,s=0,a=i.medianIdf??or(n),l=[],c=[];for(let m of e){let f=n.get(m)??0;o+=f*f,t.has(m)&&(r+=f*f,f>=a?l.push(m):c.push(m))}if(l.length===0&&c.length===0)return{similarity:0,significantShared:[],trivialShared:[]};for(let m of t){let f=n.get(m)??0;s+=f*f}let u=Math.sqrt(o)*Math.sqrt(s),d=u>0?r/u:0;return l.sort((m,f)=>(n.get(f)??0)-(n.get(m)??0)),{similarity:d,significantShared:l,trivialShared:c}}function Bb(e,t,n,i){let r=0,o=i.medianIdf??or(n),s=[],a=[];for(let u of e){if(!t.has(u))continue;let d=n.get(u)??0;r+=d*d,d>=o?s.push(u):a.push(u)}if(s.length===0&&a.length===0)return{similarity:0,significantShared:[],trivialShared:[]};let l=i.magnitudeA*i.magnitudeB,c=l>0?r/l:0;return s.sort((u,d)=>(n.get(d)??0)-(n.get(u)??0)),{similarity:c,significantShared:s,trivialShared:a}}function yo(e,t,n={}){let{minSimilarity:i=.4,limit:r=20}=n,o=()=>fN(e,t,{minSimilarity:i,limit:r,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"}),s=iN(e,t,{semantic:n.semantic!==!1});if(s.kind==="not-callable")return[];if(s.kind==="callee-evidence-unusable")return o();let a=s.target;if(!ke(a.symbol))return[];if(a.callees.size===0)return o();let l=YA(e,a,i,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return l.length>0?l.slice(0,r):o()}function Su(e,t,n,i={}){let r=fe(e,t),o=fe(e,n);if(!r||!o)return null;let s=yo(e,r.symbol,{minSimilarity:0,limit:Number.POSITIVE_INFINITY,semantic:i.semantic,scanLimit:i.scanLimit}).find(c=>c.symbolB===o.symbol||c.symbolA===o.symbol);if(!s)return null;let a=r.endLine-r.startLine+1,l=o.endLine-o.startLine+1;return{symbolA:{symbol:r.symbol,shortName:k(r.symbol),file:r.relativePath,loc:a},symbolB:{symbol:o.symbol,shortName:k(o.symbol),file:o.relativePath,loc:l},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:JA(s)}}function JA(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 YA(e,t,n,i){let r=ar(e).calleeIndex({minCallees:3,scanLimit:i.scanLimit,semantic:i.semantic}),o=dN(t,r.corpus),s=lN(o,r),a=XA(o,r),l=or(a),c=sr(o.callees,a),u=[];for(let d of s){if(d.callees.size<3)continue;let m=sr(d.callees,a),f=Hb(o,d,a,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:l,magnitudeA:c,magnitudeB:m});f&&u.push(f)}return u.sort((d,m)=>m.similarity-d.similarity),u}function XA(e,t){let n=new Map(t.docFreq);for(let i of e.callees)n.set(i,(n.get(i)??0)+1);return gu(n,t.corpus.length+1)}function Hb(e,t,n,i){let r=QA(e,t,n,i);if(!eN(r,i))return null;let{similarity:o,significantShared:s,trivialShared:a}=r,l=s.length>0?s:a,c=qb(l,"callees");return{symbolA:e.symbol,shortNameA:k(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:k(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:l.map(k),uniqueToA:[...et(e.callees,t.callees)].map(k),uniqueToB:[...et(t.callees,e.callees)].map(k),...c}}function ZA(e,t,n,i){let r=i.magnitudeA??sr(e.callees,n),o=i.magnitudeB??sr(t.callees,n),s=0,a=0,l=0,c=i.medianIdf??or(n);for(let m of e.callees){if(!t.callees.has(m))continue;let f=n.get(m)??0;s+=f*f,l+=1,f>=c&&(a+=1)}if(l===0)return!1;let u=r*o;return(u>0?s/u:0)<i.minSimilarity?!1:a>=i.requireSignificantShared||l>=i.requireSharedCount}function QA(e,t,n,i){return i.magnitudeA===void 0||i.magnitudeB===void 0?_b(e.callees,t.callees,n,{medianIdf:i.medianIdf}):Bb(e.callees,t.callees,n,{medianIdf:i.medianIdf,magnitudeA:i.magnitudeA,magnitudeB:i.magnitudeB})}function eN(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 bo(e,t={}){let{minSimilarity:n=.5,limit:i=20,scope:r,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,l=t.semantic!==!1,c=ft(),u=0,d=0,m=0,f=0,p=0,g=0,h=0;return $("similar.all",()=>{let v=ar(e).calleeIndex({minCallees:o,scope:r,scanLimit:a,semantic:l}),y=v.corpus;u=y.length;let E=t.focusFiles,w=[],b=0;return $("similar.all.pair-scan",()=>{for(let R=0;R<y.length;R+=1){let C=y[R],L=E?.has(C.file)??!1,I=v.weightedMagnitudes[R],x=new Set;for(let P of C.callees){let _=v.candidateIndexesByCallee.get(P);if(_)for(let D of _)D<=R||E&&!L&&!E.has(y[D].file)||x.add(D)}c&&(m+=x.size,x.size>0&&(d+=1));for(let P of x){let _=y[P];if(s&&C.file===_.file){c&&(p+=1);continue}if(Ub(C,_)){c&&(g+=1);continue}c&&(f+=1);let D=Hb(C,_,v.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:v.medianIdf,magnitudeA:I,magnitudeB:v.weightedMagnitudes[P]});D&&(tN(w,D,i,b),c&&(h+=1),b+=1)}}},()=>({corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:f,crossFileSkips:p,signatureSkips:g,insertedResults:h,topResults:w.length})),$("similar.all.sort-project",()=>(w.sort((R,C)=>C.result.similarity-R.result.similarity||R.order-C.order),w.map(R=>R.result)),()=>({topResults:w.length}))},()=>({minSimilarity:n,limit:i,scope:r,minCallees:o,crossFileOnly:s,scanLimit:a,semantic:l,corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:f,crossFileSkips:p,signatureSkips:g,insertedResults:h}))}function vu(e,t={}){let{minSimilarity:n=.5,scope:i,minCallees:r=4,crossFileOnly:o=!1,scanLimit:s}=t,a=t.semantic!==!1,l=ft(),c=0,u=0,d=0,m=0,f=0,p=0,g=0;return $("similar.all-count",()=>{let S=ar(e).calleeIndex({minCallees:r,scope:i,scanLimit:s,semantic:a}),v=S.corpus;c=v.length;let y=t.focusFiles;return $("similar.all-count.pair-scan",()=>{for(let E=0;E<v.length;E+=1){let w=v[E],b=y?.has(w.file)??!1,R=S.weightedMagnitudes[E],C=new Set;for(let L of w.callees){let I=S.candidateIndexesByCallee.get(L);if(I)for(let x of I)x<=E||y&&!b&&!y.has(v[x].file)||C.add(x)}l&&(d+=C.size,C.size>0&&(u+=1));for(let L of C){let I=v[L];if(o&&w.file===I.file){l&&(f+=1);continue}if(Ub(w,I)){l&&(p+=1);continue}l&&(m+=1),ZA(w,I,S.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:S.medianIdf,magnitudeA:R,magnitudeB:S.weightedMagnitudes[L]})&&(g+=1)}}},()=>({corpusSize:c,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:f,signatureSkips:p,insertedResults:g})),g},()=>({minSimilarity:n,scope:i,minCallees:r,crossFileOnly:o,scanLimit:s,semantic:a,corpusSize:c,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:f,signatureSkips:p,insertedResults:g}))}function Ub(e,t){if(e.paramCount<0||t.paramCount<0)return!1;let n=Math.abs(e.paramCount-t.paramCount),i=Math.max(2,Math.ceil(Math.max(e.paramCount,t.paramCount)*.5));return n>i}var zb=vt({kind:"source-fingerprints",invalidation:Je("source-fingerprints"),serialize:MN,deserialize:FN});function tN(e,t,n,i){if(n<=0)return;if(e.length<n){e.push({result:t,order:i});return}let r=0;for(let s=1;s<e.length;s+=1){let a=e[s],l=e[r];(a.result.similarity<l.result.similarity||a.result.similarity===l.result.similarity&&a.order>l.order)&&(r=s)}let o=e[r];t.similarity<=o.result.similarity||(e[r]={result:t,order:i})}var nN=["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 iN(e,t,n){let i=fe(e,t);if(!i)return{kind:"not-callable"};if(!ke(i.symbol))return{kind:"not-callable"};let r=new U(e),o=ai(e,i,{semantic:n.semantic,semanticEvidence:pe});return o.semanticIncomplete||o.semanticUnavailable?{kind:"callee-evidence-unusable"}:{kind:"resolved",target:{symbol:i.symbol,file:i.relativePath,callees:Ea(o.rows.map(s=>s.symbol)),paramCount:r.callableSignature(i)?.paramCount??-1}}}var rN=Fe("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),oN=Fe("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function Gb(e,t){let{minCallees:n,scope:i,excludeSymbol:r,scanLimit:o}=t,s=t.semantic!==!1,a=rN.get(e,()=>new Map),l=`${n}|${i??""}|${o??""}|${s}`,c=!0,u=0,d=0;return $("similar.callee-fingerprints.resolve",()=>{let m=a.get(l);if(c=m!==void 0,m||(m=cN(e,{minCallees:n,scope:i,scanLimit:o,semantic:s}),a.set(l,m)),u=m.length,r===void 0)return m;let f=m.filter(p=>p.symbol!==r);return d=m.length-f.length,f},()=>({minCallees:n,scope:i,scanLimit:o,semantic:s,cacheHit:c,corpusSize:u,excludeSymbol:r!==void 0,excludedSymbols:d}))}function sN(e,t){let{minCallees:n,scope:i,scanLimit:r}=t,o=t.semantic!==!1,s=oN.get(e,()=>new Map),a=`${n}|${i??""}|${r??""}|${o}`,l=!0,c=0,u=0,d=0;return $("similar.callee-index.resolve",()=>{let m=s.get(a);return l=m!==void 0,m||(m=aN(Gb(e,{minCallees:n,scope:i,scanLimit:r,semantic:o})),s.set(a,m)),c=m.corpus.length,u=m.docFreq.size,d=m.candidateIndexesByCallee.size,m},()=>({minCallees:n,scope:i,scanLimit:r,semantic:o,cacheHit:l,corpusSize:c,indexedCallees:u,candidateBuckets:d}))}function ar(e){return{calleeCorpus:t=>Gb(e,t),calleeIndex:t=>sN(e,t),sourceCorpus:(t={})=>Xb(e,t),sourceIndex:(t={})=>jb(e,t),sourceCandidates:(t,n)=>(n.candidateMode??"full")==="target-pruned"?RN(e,t,{minSimilarity:n.minSimilarity,scanLimit:n.scanLimit}):xN(t,jb(e,{scanLimit:n.scanLimit}))}}function aN(e){let t=ft(),n=0,i=$("similar.callee-index.doc-frequency",()=>{let m=new Map;for(let f of e)for(let p of f.callees)m.set(p,(m.get(p)??0)+1);return n=m.size,m},()=>({corpusSize:e.length,uniqueCallees:n})),r=Math.max(8,Math.ceil(Math.sqrt(e.length))),o=$("similar.callee-index.idf-weights",()=>gu(i,e.length),()=>({corpusSize:e.length,uniqueCallees:i.size})),s=$("similar.callee-index.weighted-magnitudes",()=>e.map(m=>sr(m.callees,o)),()=>({corpusSize:e.length})),a=0,l=0,c=0,u=$("similar.callee-index.candidate-buckets",()=>{let m=new Map;for(let f=0;f<e.length;f+=1){let p=e[f];for(let g of p.callees){if((i.get(g)??0)>r){t&&(l+=1);continue}let h=m.get(g);h||(h=[],m.set(g,h)),h.push(f),t&&(a+=1)}}return t&&(c=m.size),m},()=>({corpusSize:e.length,buckets:c,candidateRefs:a,ubiquitousSkips:l,ubiquityThreshold:r})),d=$("similar.callee-index.median-idf",()=>or(o),()=>({uniqueCallees:o.size}));return{corpus:e,candidateIndexesByCallee:u,docFreq:i,idfWeights:o,weightedMagnitudes:s,medianIdf:d,ubiquityThreshold:r}}function lN(e,t){let n=new Map;for(let i of e.callees)for(let r of t.candidateIndexesByCallee.get(i)??[]){let o=t.corpus[r];o.symbol!==e.symbol&&n.set(o.symbol,o)}return n.size>0?[...n.values()]:t.corpus.filter(i=>i.symbol!==e.symbol)}function cN(e,t){let{minCallees:n,scope:i,scanLimit:r,semantic:o}=t,s=ft(),a=new U(e),l=0,c=$("similar.callee-fingerprints.candidates",()=>{let g=Ae(a.productionCallableDefinitions({scope:i,minLoc:5,sortByLocDesc:typeof r=="number"&&r>0}),r);return l=g.length,g},()=>({scope:i,scanLimit:r,candidateCount:l})),u=0,d=$("similar.callee-fingerprints.callee-map",()=>{let g=a.calleeEvidenceMap(c,{semantic:o});if(s)for(let h of g.rows.values())u+=h.length;return g},()=>({candidateCount:l,semantic:o,calleeEdges:u})),m=0,f=0,p=0;return $("similar.callee-fingerprints.shape",()=>{let h=c.filter(y=>!d.incompleteSymbolIds.has(y.symbolId)&&!d.unavailableSymbolIds.has(y.symbolId)).map(y=>({symbol:y.symbol,file:y.relativePath,callees:Ea((d.rows.get(y.symbolId)??[]).map(E=>E.symbol)),paramCount:a.callableSignature(y)?.paramCount??-1})),S=uN(h);s&&(p=S.filter((y,E)=>y.callees.size!==h[E].callees.size).length);let v=S.filter(y=>y.callees.size>=n);return m=v.length,s&&(f=v.reduce((y,E)=>y+E.callees.size,0)),v},()=>({candidateCount:l,fingerprintCount:m,retainedCalleeCount:f,minCallees:n,siblingSaturatedFingerprints:p}))}var Kb=5;function uN(e){let t=new Map;for(let n of e){let i=t.get(n.file);i||(i=new Map,t.set(n.file,i));for(let r of n.callees)i.set(r,(i.get(r)??0)+1)}return e.map(n=>{let i=t.get(n.file);if(!i)return n;let r=[...n.callees].filter(s=>(i.get(s)??0)>=Kb);if(r.length===0)return n;let o=new Set(n.callees);for(let s of r)o.delete(s);return{...n,callees:o}})}function dN(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 i=[...e.callees].filter(o=>(n.get(o)??0)+1>=Kb);if(i.length===0)return e;let r=new Set(e.callees);for(let o of i)r.delete(o);return{...e,callees:r}}function Ea(e){return new Set([...e].filter(t=>!mN(t)))}function mN(e){return nN.some(t=>e.includes(t))}function fN(e,t,n){let i=yN(e,t);if(!i||i.tokens.size<3)return[];let r=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=n.candidateMode??"full",a=0,l=0,c=0,u=0;return $("similar.source-shape",()=>{let m=ar(e).sourceCandidates(i,{minSimilarity:r,scanLimit:n.scanLimit,candidateMode:s});a=m.length;for(let f of m){if(f.symbol===i.symbol||f.tokens.size<3)continue;l+=1;let p=Bt(i.tokens,f.tokens);if(p.size<2){c+=1;continue}let g=new Set([...i.tokens,...f.tokens]),h=g.size>0?p.size/g.size:0;if(h<r){u+=1;continue}o.push({symbolA:i.symbol,shortNameA:k(i.symbol),fileA:i.file,symbolB:f.symbol,shortNameB:k(f.symbol),fileB:f.file,similarity:h,similarityBasis:"source-tokens",sharedCallees:[...p].sort(),uniqueToA:[...et(i.tokens,f.tokens)].sort(),uniqueToB:[...et(f.tokens,i.tokens)].sort(),...qb([...p],"source-tokens")})}return o.sort((f,p)=>p.similarity-f.similarity||f.shortNameB.localeCompare(p.shortNameB)),o.slice(0,n.limit)},()=>({symbol:i.symbol,file:i.file,targetTokens:i.tokens.size,candidateMode:s,candidates:a,comparedPairs:l,sharedSkips:c,similaritySkips:u,results:o.length}))}function qb(e,t){let n=e.flatMap(yu),i=e.flatMap(h=>Ob(h,t)),r=hu(n,Wb),o=hu(n,Vb),s=hu(i,bu),a=[...new Set(i.filter($b))],l=e.filter(h=>{let S=Ob(h,t);return S.some(v=>bu.has(v))&&S.some($b)}).length,c=[];r.length>0&&c.push(`access/query scaffolding: ${r.slice(0,5).join(", ")}`),o.length>0&&c.push(`framework/generic scaffolding: ${o.slice(0,5).join(", ")}`),s.length>0&&c.push(`domain behavior verbs: ${s.slice(0,5).join(", ")}`),s.length>0&&a.length>0&&c.push(`domain-specific terms: ${a.slice(0,5).join(", ")}`);let u=t==="source-tokens"&&n.length>0&&n.every(h=>Jb.has(h));u&&c.push("shared source tokens are generic scaffolding");let d=s.length>0&&a.length>0,m=r.length+o.length>0,f=t==="callees"&&d&&e.length>=4&&a.length>=4&&l>=2,p=f?"domain-behavior":d?m?"mixed":"domain-behavior":r.length>0?"access-query-scaffolding":o.length>0||u?"framework-scaffolding":"structural-overlap";p==="structural-overlap"&&e.length>0&&c.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let g=p==="domain-behavior"&&(e.length>=3||f)?"direct":"signal";return{evidenceClass:p,actionTier:g,evidenceClassReasons:c,recommendation:pN(p,g)}}function pN(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 hu(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function yu(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function Ob(e,t){if(t==="source-tokens")return yu(e);let n=re(e);return yu(n.length>0?n:gN(e))}function gN(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(i=>i.trim()).filter(i=>/[A-Za-z]/.test(i)).at(-1)?.replace(/\.$/,"")??e}function $b(e){return e.length>3&&!bu.has(e)&&!Wb.has(e)&&!Vb.has(e)&&!Jb.has(e)&&!hN.has(e)}var bu=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),Wb=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),Vb=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"]),Jb=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),hN=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 yN(e,t){let n=fe(e,t);if(!n||!ke(n.symbol))return null;let i=bN(e,n);return i?{symbol:n.symbol,file:n.relativePath,tokens:i}:null}function bN(e,t){let n=re(t.symbol),i=DN(e,t.relativePath,t.startLine,t.endLine,n),r=eS(i,n);return r.size>0?r:null}var SN=Fe("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),vN=Fe("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function Yb(e){return`${e.scanLimit??""}`}function Xb(e,t={}){let n=SN.get(e,()=>new Map),i=Yb(t),r=n.get(i);return r||(r=LN(e,t),n.set(i,r)),r}function jb(e,t={}){let n=vN.get(e,()=>new Map),i=Yb(t),r=n.get(i);return r||(r=CN(Xb(e,t)),n.set(i,r)),r}function CN(e){let t=new Map;for(let r of e)for(let o of r.tokens)t.set(o,(t.get(o)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),i=new Map;for(let r of e)for(let o of r.tokens){if((t.get(o)??0)>n)continue;let s=i.get(o);s||(s=[],i.set(o,s)),s.push(r)}return{corpus:e,candidateByToken:i,docFreq:t,ubiquityThreshold:n}}function xN(e,t){let n=new Map;for(let i of e.tokens)for(let r of t.candidateByToken.get(i)??[])r.symbol!==e.symbol&&n.set(r.symbol,r);return n.size>0?[...n.values()]:t.corpus.filter(i=>i.symbol!==e.symbol)}function RN(e,t,n){let i=ft(),r=new U(e),o=EN(t.tokens.size,n.minSimilarity),s=0,a=0,l=0,c=$("similar.source-shape.target-files",()=>{let p=[...t.tokens],g=[];for(let h of he(e,{includeIgnored:!1})){s+=1;let S=se(e,h);S&&(a+=1,wN(S,p,o)&&g.push(h))}return l=g.length,g},()=>({symbol:t.symbol,targetTokens:t.tokens.size,requiredSharedTokens:o,scannedFiles:s,readableFiles:a,candidateFiles:l})),u=0,d=$("similar.source-shape.target-definitions",()=>{let p=Ae(r.productionCallableDefinitions({files:c,sortByLocDesc:typeof n.scanLimit=="number"&&n.scanLimit>0}),n.scanLimit);return u=p.length,p},()=>({symbol:t.symbol,candidateFiles:l,scanLimit:n.scanLimit,definitionCount:u})),m=0;return $("similar.source-shape.target-fingerprints",()=>{let p=Zb(e,d);return i&&(m=p.length),p},()=>({symbol:t.symbol,definitionCount:u,fingerprintCount:m})).filter(p=>p.symbol!==t.symbol)}function EN(e,t){return Math.max(2,Math.ceil(e*t))}function wN(e,t,n){if(t.length<n)return!1;let i=e.toLowerCase(),r=0;for(let o of t)if(IN(i,o)&&(r+=1,r>=n))return!0;return!1}function IN(e,t){return t==="num"?/\b\d+\b/.test(e):e.includes(t)}function LN(e,t={}){let n=new U(e),{scanLimit:i}=t,r=Ae(n.productionCallableDefinitions({sortByLocDesc:typeof i=="number"&&i>0}),i);return Zb(e,r)}function Zb(e,t){let n=new Map;for(let r of t){let o=n.get(r.relativePath)??[];o.push(r),n.set(r.relativePath,o)}let i=new Map;for(let[r,o]of n){let s=se(e,r);if(!s)continue;let a=Ft(e,r,s),l=TN(e,r,a),c=!1,u=null;for(let d of o){let m=PN(d),f=l.get(m),p=f?new Set(f.tokens):null;p||(u??=ie(e,r),p=eS(Qb(u,d.startLine,d.endLine,d.leaf),d.leaf),l.set(m,{key:m,symbol:d.symbol,startLine:d.startLine,endLine:d.endLine,leaf:d.leaf,tokens:[...p].sort()}),c=!0),p.size>0&&i.set(d.symbol,{symbol:d.symbol,file:d.relativePath,tokens:p})}c&&AN(e,r,a,l)}return t.map(r=>i.get(r.symbol)).filter(r=>!!r)}function DN(e,t,n,i,r){let o=ie(e,t);return o.length===0?"":Qb(o,n,i,r)}function Qb(e,t,n,i){if(n>=t&&n-t<=12)return e.slice(t,n+1).join(`
|
|
318
|
+
`);let r=[new RegExp(`\\bdef\\s+${He(i)}\\b`),new RegExp(`\\bfun\\s+${He(i)}\\b`),new RegExp(`\\bfn\\s+${He(i)}\\b`),new RegExp(`\\bfunction\\s+${He(i)}\\b`),new RegExp(`\\b${He(i)}\\s*\\(`)],o=e.findIndex(s=>r.some(a=>a.test(s)));if(o>=0){let s=o;for(let a=o+1;a<e.length&&a<=o+8;a++){let l=e[a]??"";if(a>o&&kN(l)||(s=a,l.trim()===""&&a>o+1))break}return e.slice(o,s+1).join(`
|
|
319
|
+
`)}return e.slice(t,Math.min(e.length,t+8)).join(`
|
|
320
|
+
`)}function PN(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function TN(e,t,n){return zb.read(e,t,n)??new Map}function FN(e){try{let t=JSON.parse(e);if(!Array.isArray(t.entries))return null;let n=new Map;for(let i of t.entries){if(!i||typeof i.key!="string"||typeof i.symbol!="string"||typeof i.startLine!="number"||typeof i.endLine!="number"||typeof i.leaf!="string"||!Array.isArray(i.tokens)||!i.tokens.every(r=>typeof r=="string"))return null;n.set(i.key,i)}return n}catch{return null}}function MN(e){let t={entries:[...e.values()].sort((n,i)=>n.key.localeCompare(i.key))};return JSON.stringify(t)}function AN(e,t,n,i){zb.write(e,t,n,new Map(i))}function eS(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"]),i=NN(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=>!i.has(s));return new Set(o)}function NN(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 kN(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function ln(e,t){let n=new Map;return e.forEach((i,r)=>{let o=new Set;for(let s of t(i)){if(o.has(s))continue;o.add(s);let a=n.get(s);a?a.push(r):n.set(s,[r])}}),{candidatesFor:(i,r)=>{let o=new Set;for(let s of t(i)){let a=n.get(s);if(a)for(let l of a)l!==r&&o.add(l)}return[...o].sort((s,a)=>s-a)}}}function cn(e){let t=tS(e.profile?.name),n=()=>{let i=[];t=tS(e.profile?.name,e);let r=(s,a)=>{let l=e.profiles[s],c=e.profiles[a];t.candidatePairs+=1,t.comparedPairs+=1;let u=e.compare(l,c);u&&i.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 l of _N(e,s)){let c=e.profiles[l];e.focusFiles&&!e.focusFiles.has(a.file)&&!e.focusFiles.has(c.file)||r(s,l)}}}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 l=e.profiles[a],c=e.focusFiles?.has(l.file)??!1;for(let u of BN(e,a))e.focusFiles&&!c&&!e.focusFiles.has(e.profiles[u].file)||r(a,u);if(i.length>s){t.overrunApplied=!0;break}}}i.sort(e.sort??((s,a)=>a.similarity-s.similarity)),t.matchedResults=i.length;let o=i.slice(0,e.limit);return t.emittedResults=o.length,e.onProfile?.({...t}),o};return e.profile?$(`pairwise-profile:${e.profile.name}`,n,()=>({...ON(e.profile?.metadata),...t})):n()}function _N(e,t){if(e.candidateIndex)return nS(e,t,-1);let n=[];for(let i=0;i<e.profiles.length;i+=1)i!==t&&n.push(i);return n}function BN(e,t){if(e.candidateIndex)return nS(e,t,t);let n=[];for(let i=t+1;i<e.profiles.length;i+=1)n.push(i);return n}function nS(e,t,n){let i=e.profiles[t],r=new Set;for(let o of e.candidateIndex?.candidatesFor(i,t,e.profiles)??[])o<=n||o!==t&&(o<0||o>=e.profiles.length||r.add(o));return[...r].sort((o,s)=>o-s)}function tS(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 ON(e){return typeof e=="function"?e():e??{}}function $N(e,t={}){let{minSimilarity:n=.5,limit:i=20,scope:r,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:l}=jN(e,{scope:r,minDeps:s}),c=ln(a,u=>u.deps);return cn({profiles:a,limit:i,filePattern:o,overrunFactor:5,candidateIndex:c,profile:{name:"similar-files"},compare:(u,d)=>UN(u,d,n,l)})}function jN(e,t){let{scope:n,minDeps:i}=t,r=Be(e,n),{universalDeps:o,distinctiveDeps:s}=HN(r),a=[];for(let[l,c]of r)c.size>=i&&a.push({file:l,deps:new Set([...c].filter(u=>!o.has(u)))});return{profiles:a,distinctiveDeps:s}}function HN(e){let t=new Set,n=new Set,i=e.size;if(i===0)return{universalDeps:t,distinctiveDeps:n};let r=new Map;for(let s of e.values())for(let a of s)r.set(a,(r.get(a)??0)+1);let o=Math.max(3,Math.ceil(i*.03));for(let[s,a]of r)a>=5&&a/i>.3?t.add(s):a<=o&&n.add(s);return{universalDeps:t,distinctiveDeps:n}}function UN(e,t,n,i){let r=new Set;for(let c of e.deps)t.deps.has(c)&&r.add(c);if(r.size<3||e.deps.size<4||t.deps.size<4)return null;let o=0;for(let c of r)i.has(c)&&o++;if(o<2)return null;let s=Yn(e.deps,t.deps);if(s<n)return null;let a=[];for(let c of e.deps)t.deps.has(c)||a.push(c);let l=[];for(let c of t.deps)e.deps.has(c)||l.push(c);return{fileA:e.file,fileB:t.file,similarity:s,sharedDeps:[...r],uniqueToA:a,uniqueToB:l}}function Xn(e){let t=[],n=[],i=[];for(let c of e.primitiveGroups)c.values.length!==0&&iS(c.bucket,n,i).push(`${c.reasonPrefix}: ${c.values.join(", ")}`);for(let c of e.nameGroups)zN(c.names,c.label,e.genericWords,e.stripPrefixes??[],t,iS(c.fallbackBucket,n,i));let r=t.length>0,o=n.length>0,s=i.length>0,a=r?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...i,...n].slice(0,6),recommendation:e.recommendation(a)}}function wa(e,t){if(e.size===0||t.size===0)return 0;let r=Bt(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(Yn(e,t),r)}function Zn(e,t){let n=Object.fromEntries(e.map(i=>[i.name,i.count]));for(let i of t)if(Object.entries(i.min).every(([o,s])=>(n[o]??0)>=s))return{pass:!0,reason:i.reason,counts:n};return{pass:!1,reason:"shared tokens did not meet calibrated overlap thresholds",counts:n}}function Ia(e,t,n){let i=t.map(l=>{let c=l.value(e),u=l.weightedValue?l.weightedValue(e,c):c;return{axis:l,value:c,weighted:u,qualifies:l.qualifies?l.qualifies(e,c):c>0}}),r=i.filter(l=>l.qualifies&&l.axis.reason).map(l=>l.axis.reason(e,l.value)),o=i.filter(l=>l.qualifies&&l.axis.dominantEligible!==!1).sort((l,c)=>c.weighted-l.weighted)[0],s=o&&o.weighted>0?o.axis.axis:n,a=[...new Set(i.filter(l=>l.qualifies).map(l=>l.axis.axis).concat(r.length>0?[]:[s]))];return{dominantPressure:s,pressureKinds:a,reasons:r}}function Ee(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function ot(e){return[...e].sort()}function zN(e,t,n,i,r,o){let s=[],a=[];for(let l of e)GN(l,i).filter(u=>!n.has(u)).length>0?s.push(l):a.push(l);s.length&&r.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 GN(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 i of t)n=n.replace(i,"");return n.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function iS(e,t,n){return e==="generic"?t:n}function So(e,t={}){let{minSimilarity:n=.62,minTokens:i=8,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:l}=t,c=At(e).reactProfiles({scope:o,minJsxTokens:i,scanLimit:s}).filter(d=>d.kind==="component").map(d=>({file:d.file,component:d.name,tokens:d.jsxTokens,profile:d})),u=ln(c,d=>d.tokens);return cn({profiles:c,limit:r,filePattern:a,focusFiles:l,candidateIndex:u,profile:{name:"react-component-duplicates"},compare:(d,m)=>KN(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 KN(e,t,n){let i=Bt(e.tokens,t.tokens);if(i.size<6||!qN(i))return null;let r=Yn(e.tokens,t.tokens);if(r<n)return null;let o=Ee(i,"component:"),s=Ee(i,"native:"),a=Ee(i,"prop:"),l=Ee(i,"event:"),c=Ee(i,"binding:"),u=WN({sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:l,sharedBindings:c});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:r,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:ot(i),sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:l,sharedBindings:c,evidenceClass:u.evidenceClass,actionTier:u.actionTier,evidenceClassReasons:u.reasons,recommendation:u.recommendation,uniqueToA:ot(et(e.tokens,t.tokens)).slice(0,25),uniqueToB:ot(et(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function qN(e){let t=0,n=0;for(let i of e)i.startsWith("component:")&&(t+=1),(i.startsWith("prop:")||i.startsWith("event:")||i.startsWith("native:")||i.startsWith("jsx:"))&&(n+=1);return Zn([{name:"component",count:t},{name:"shape",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{shape:4},reason:"shared JSX structure"}]).pass}function WN(e){return Xn({genericWords:JN,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:VN})}function VN(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 JN=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 vo(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:i=6,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:l}=t,c=At(e).reactProfiles({scope:o,minBehaviorTokens:Math.max(3,i),scanLimit:s}).map(d=>({file:d.file,component:d.name,tokens:d.behaviorTokens,profile:d})),u=ln(c,d=>d.tokens);return cn({profiles:c,limit:r,filePattern:a,focusFiles:l,candidateIndex:u,profile:{name:"react-hook-candidates"},compare:(d,m)=>YN(d,m,n,i),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 YN(e,t,n,i){let r=Bt(e.tokens,t.tokens);if(r.size<i||!QN(r))return null;let o=wa(e.tokens,t.tokens);if(o<n)return null;let s=Ee(r,"hook:"),a=Ee(r,"react-hook:"),l=Ee(r,"effect:"),c=Ee(r,"state:"),u=Ee(r,"request:"),d=Ee(r,"handler:"),m=Ee(r,"handler-verb:"),f=XN({sharedHooks:s,sharedReactHooks:a,sharedEffects:l,sharedState:c,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:ot(r),sharedHooks:s,sharedReactHooks:a,sharedEffects:l,sharedState:c,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m,evidenceClass:f.evidenceClass,actionTier:f.actionTier,evidenceClassReasons:f.reasons,recommendation:f.recommendation,uniqueToA:ot(et(e.tokens,t.tokens)).slice(0,25),uniqueToB:ot(et(t.tokens,e.tokens)).slice(0,25),reason:ek({sharedHooks:s,sharedReactHooks:a,sharedEffects:l,sharedState:c,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function XN(e){return Xn({genericWords:tk,stripPrefixes:nk,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:ZN})}function ZN(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 QN(e){let t=0,n=0,i=0,r=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:")?i+=1:u.startsWith("request:")?r+=1:u.startsWith("handler:")||u.startsWith("handler-verb:")?o+=1:u.startsWith("state:")?s+=1:u.startsWith("state-hook:")&&(a+=1);let l=s+a,c=t+n+i+r+o+l;return Zn([{name:"requests",count:r},{name:"customHooks",count:t},{name:"namedStates",count:s},{name:"handlers",count:o},{name:"effects",count:i},{name:"reactHooks",count:n},{name:"namedBehavior",count:c}],[{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 ek(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 tk=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"]),nk=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function Cu(e,t={}){let{minComponentLines:n=300,minFileLines:i=800,minJsxTokens:r=80,minBehaviorTokens:o=40,limit:s=20,scope:a,scanLimit:l,filePattern:c}=t;return At(e).reactProfiles({scope:a,scanLimit:l}).filter(d=>d.kind==="component").filter(d=>!c||d.file.includes(c)||d.name.includes(c)).map(d=>ik(d,{minComponentLines:n,minFileLines:i,minJsxTokens:r,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 ik(e,t){let n=Math.max(80,Math.floor(t.minComponentLines/2)),i=Ia(e,rk({minComponentLines:t.minComponentLines,minFileLines:t.minFileLines,minJsxTokens:t.minJsxTokens,minBehaviorTokens:t.minBehaviorTokens,substantialComponentLines:n}),"component"),{reasons:r}=i;if(r.length===0)return null;let o=i.dominantPressure,s=i.pressureKinds,a=ok(e),l=sk(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:l,recommendation:ak(l,a),reasons:r,loc:e.loc}}function rk(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 ok(e){let t=e.file.split(/[\\/]+/).filter(Boolean),n=t.slice(0,-1).map(m=>m.toLowerCase()),i=(t.at(-1)??e.name).replace(/\.[^.]+$/,""),o=n.findIndex(m=>ck.has(m))>=0,s=n.some(m=>lk.has(m));if(rS(i)||rS(e.name))return"component";let l=uk.has(i.toLowerCase()),c=/(?:Page|Route|Screen)$/.test(e.name),u=o&&/View$/.test(e.name),d=!s&&i.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()===e.name.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()&&/(?:Page|Route|Screen|View)$/.test(i);return l||c||u||d?"route-page":"component"}function rS(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&oS.has(t.at(-1))?!0:[...oS].some(n=>e.endsWith(dk(n)))}function sk(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 ak(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 lk=new Set(["component","components","panel","panels","partial","partials"]),oS=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"]),ck=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),uk=new Set(["page","route","screen"]);function dk(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Co(e,t={}){let{minSimilarity:n=.62,minTokens:i=8,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:l}=t,c=mk(e,{scope:o,minTokens:i,scanLimit:s}),u=ln(c,d=>d.tokens);return cn({profiles:c,limit:r,filePattern:a,focusFiles:l,candidateIndex:u,profile:{name:"vue-component-duplicates"},compare:(d,m)=>pk(d,m,n),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function mk(e,t){return At(e).vueProfiles({scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:fk(n)}))}function fk(e){return e.totalLines}function pk(e,t,n){let i=Bt(e.tokens,t.tokens);if(i.size<6||!gk(i))return null;let r=Yn(e.tokens,t.tokens);if(r<n)return null;let o=Ee(i,"component:"),s=Ee(i,"prop:"),a=Ee(i,"event:"),l=Ee(i,"directive:"),c=Ee(i,"slot:"),u=Ee(i,"id:"),d=hk({sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:l,sharedSlots:c,sharedIdentifiers:u});return{fileA:e.file,fileB:t.file,similarity:r,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:ot(i),sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:l,sharedSlots:c,sharedIdentifiers:u,evidenceClass:d.evidenceClass,actionTier:d.actionTier,evidenceClassReasons:d.reasons,recommendation:d.recommendation,uniqueToA:ot(et(e.tokens,t.tokens)).slice(0,25),uniqueToB:ot(et(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function gk(e){let t=0,n=0;for(let i of e)i.startsWith("component:")&&(t+=1),(i.startsWith("prop:")||i.startsWith("event:")||i.startsWith("directive:")||i.startsWith("slot:"))&&(n+=1);return Zn([{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 hk(e){return Xn({genericWords:bk,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:yk})}function yk(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 bk=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 xo(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:i=6,limit:r=20,scope:o,scanLimit:s,filePattern:a,focusFiles:l}=t,c=At(e).vueProfiles({scope:o,minBehaviorTokens:Math.max(3,i),scanLimit:s}).map(d=>({file:d.file,tokens:d.behaviorTokens,profile:d})),u=ln(c,d=>d.tokens);return cn({profiles:c,limit:r,filePattern:a,focusFiles:l,candidateIndex:u,profile:{name:"vue-composable-candidates"},compare:(d,m)=>Sk(d,m,n,i),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function Sk(e,t,n,i){let r=Bt(e.tokens,t.tokens);if(r.size<i||!xk(r))return null;let o=wa(e.tokens,t.tokens);if(o<n)return null;let s=Ee(r,"composable:"),a=Ee(r,"store:"),l=Ee(r,"reactivity:"),c=Ee(r,"lifecycle:"),u=Ee(r,"request:"),d=Ee(r,"function:"),m=Ee(r,"function-verb:"),f=Ee(r,"template-binding:"),p=Ee(r,"template-event:"),g=vk({sharedComposables:s,sharedStores:a,sharedReactivity:l,sharedLifecycle:c,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:p});return{fileA:e.file,fileB:t.file,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:ot(r),sharedComposables:s,sharedStores:a,sharedReactivity:l,sharedLifecycle:c,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:p,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:ot(et(e.tokens,t.tokens)).slice(0,25),uniqueToB:ot(et(t.tokens,e.tokens)).slice(0,25),reason:Rk({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:c,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function vk(e){return Xn({genericWords:Ek,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:Ck})}function Ck(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 xk(e){let t=0,n=0,i=0,r=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:")?i+=1:u.startsWith("lifecycle:")?r+=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 l=t+n,c=l+i+r+o+a;return Zn([{name:"requests",count:i},{name:"lifecycle",count:r},{name:"functions",count:o},{name:"reusableHooks",count:l},{name:"reactivity",count:s},{name:"namedBehavior",count:c}],[{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 Rk(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 Ek=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 xu(e,t={}){let{minTotalLines:n=800,minTemplateLines:i=300,minScriptLines:r=300,minStyleLines:o=500,limit:s=20,scope:a,scanLimit:l,filePattern:c}=t;return At(e).vueProfiles({scope:a,scanLimit:l}).filter(d=>!c||d.file.includes(c)).map(d=>wk(d,{minTotalLines:n,minTemplateLines:i,minScriptLines:r,minStyleLines:o})).filter(d=>d!==null).sort((d,m)=>m.totalLines-d.totalLines||d.file.localeCompare(m.file)).slice(0,s)}function wk(e,t){let n=Ia(e,Ik(t),"total"),{reasons:i}=n;if(i.length===0)return null;let r=n.dominantPressure,o=n.pressureKinds.includes("total")?[...new Set([...n.pressureKinds,r])]:n.pressureKinds,s=Lk(e.file),a=Dk(r,s),l=e.totalLines+e.delegatedComposableLines;return{file:e.file,totalLines:l,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:r,pressureKinds:o,contextKind:s,recommendationKind:a,recommendation:Pk(a,s),reasons:i,loc:l}}function Ik(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 Lk(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(i=>Tk.has(i))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function Dk(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 Pk(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 Tk=new Set(["landing","page","pages","route","routes","view","views"]);function Fk(e,t={}){let{minSimilarity:n=.5,limit:i=15,scope:r,minChainLength:o=3,maxChainLength:s=8}=t,a=Be(e,r),l=$k(a,o,s);if(l.length===0)return[];let c=Mk(l);return c.length<2?[]:Ok(kk(c,n,i),i)}function Mk(e){let t=Ak(e),n=[];for(let i of e){let r=i.filter(o=>!t.has(o));r.length>=2&&n.push({original:i,filtered:r})}return n}function Ak(e){let{nodeFreq:t,tailFreq:n}=Nk(e),i=e.length*.9,r=e.length*.8,o=new Set;for(let[a,l]of t)l>i&&o.add(a);for(let[a,l]of n)l>r&&o.add(a);let s=["index.ts","index.js","cli.ts","main.ts","health.ts","health.js"];for(let a of t.keys()){let l=a.split("/").pop()??"";s.includes(l)&&o.add(a)}return o}function Nk(e){let t=new Map,n=new Map;for(let i of e){let r=new Set;for(let o of i)r.has(o)||(t.set(o,(t.get(o)??0)+1),r.add(o));for(let o=Math.max(0,i.length-2);o<i.length;o++)n.set(i[o],(n.get(i[o])??0)+1)}return{nodeFreq:t,tailFreq:n}}function kk(e,t,n){let i=[];for(let r=0;r<e.length;r++){for(let o=r+1;o<e.length;o++){let s=_k(e[r],e[o],t);s&&i.push(s)}if(i.length>n*10)break}return i.sort((r,o)=>Math.abs(o.similarity-r.similarity)>.01?o.similarity-r.similarity:r.divergencePoints.length-o.divergencePoints.length),i}function _k(e,t,n){if(!Bk(e.filtered,t.filtered))return null;let{distance:i,ops:r}=jk(e.filtered,t.filtered),o=Math.max(e.filtered.length,t.filtered.length);if(o===0)return null;let s=1-i/o;if(s<n||i===0)return null;let a=r.filter(c=>c.type==="substitute").map(c=>({index:c.indexA,nodeA:e.filtered[c.indexA],nodeB:t.filtered[c.indexB]}));return a.length===0||r.filter(c=>c.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:s,editDistance:i,divergencePoints:a,commonPrefix:Hk(e.original,t.original),commonSuffix:Uk(e.original,t.original)}}function Bk(e,t){let n=new Set(e);return t.some(i=>n.has(i))}function Ok(e,t){let n=[];for(let i of e)if(n.some(o=>sS(i.chainA,o.chainA)&&sS(i.chainB,o.chainB))||n.push(i),n.length>=t)break;return n}function $k(e,t,n){let i=[];for(let o of e.keys()){if(i.length>=500)break;aS(e,o,[o],new Set([o]),t,n,i,500)}return i}function aS(e,t,n,i,r,o,s,a){if(s.length>=a)return;if(n.length>=o){n.length>=r&&s.push([...n]);return}let l=e.get(t);if(!l||l.size===0){n.length>=r&&s.push([...n]);return}let c=!1;for(let u of l)if(!i.has(u)&&(i.add(u),n.push(u),aS(e,u,n,i,r,o,s,a),n.pop(),i.delete(u),c=!0,s.length>=a))return;!c&&n.length>=r&&s.push([...n])}function jk(e,t){let n=e.length,i=t.length,r=Array.from({length:n+1},()=>Array(i+1).fill(0));for(let l=0;l<=n;l++)r[l][0]=l;for(let l=0;l<=i;l++)r[0][l]=l;for(let l=1;l<=n;l++)for(let c=1;c<=i;c++)e[l-1]===t[c-1]?r[l][c]=r[l-1][c-1]:r[l][c]=1+Math.min(r[l-1][c],r[l][c-1],r[l-1][c-1]);let o=[],s=n,a=i;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&&r[s][a]===r[s-1][a-1]+1?(o.unshift({type:"substitute",indexA:s-1,indexB:a-1}),s--,a--):a>0&&r[s][a]===r[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:r[n][i],ops:o}}function Hk(e,t){let n=[];for(let i=0;i<Math.min(e.length,t.length)&&e[i]===t[i];i++)n.push(e[i]);return n}function Uk(e,t){let n=[],i=e.length-1,r=t.length-1;for(;i>=0&&r>=0&&e[i]===t[r];)n.unshift(e[i]),i--,r--;return n}function sS(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),i=e.join("\u2192");return n.includes(i)}function Ot(e){let t=zk(e.profile?.name),n=()=>{let i=e.candidates(),r=e.filterCandidate?i.filter(e.filterCandidate):i,o=e.orderCandidates?[...r].sort(e.orderCandidates):r,s=Ae(o,e.scanLimit);t={pipeline:e.profile?.name,loadedCandidates:i.length,filteredCandidates:r.length,scannedCandidates:s.length,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:s.length<r.length,resultLimitApplied:!1};let a=e.prepare?.(s)??void 0,l=[];for(let u of s){t.evaluatedCandidates+=1;let d=e.evaluate(u,a);d&&l.push(d)}t.matchedResults=l.length,e.orderResults&&l.sort(e.orderResults);let c=typeof e.limit=="number"?l.slice(0,e.limit):l;return t.emittedResults=c.length,t.resultLimitApplied=c.length<l.length,e.onProfile?.({...t}),c};return e.profile?$(`candidate-pipeline:${e.profile.name}`,n,()=>({...Gk(e.profile?.metadata),...t})):n()}function zk(e){return{pipeline:e,loadedCandidates:0,filteredCandidates:0,scannedCandidates:0,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:!1,resultLimitApplied:!1}}function Gk(e){return typeof e=="function"?e():e??{}}function Ro(e,t={}){let{scope:n,minLoc:i=10,minCallees:r=6,limit:o=20,scanLimit:s}=t,a=new U(e);return Ot({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:i,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,profile:{name:"extract-candidates"},prepare:l=>a.calleeEvidenceMap(l,{semantic:t.semantic!==!1}),evaluate:(l,c)=>c.incompleteSymbolIds.has(l.symbolId)||c.unavailableSymbolIds.has(l.symbolId)?null:Kk(l,c.rows.get(l.symbolId)??[],r),orderResults:(l,c)=>c.clusters.length-l.clusters.length||c.loc-l.loc,limit:o})}function Kk(e,t,n){let i=new Set(t.map(c=>c.symbol));if(i.size<n)return null;let r=Yk(i,t),o=Xk(i,r);if(o.length<2)return null;let s=Zk(o,r);if(s.length===0)return null;let a=k(e.symbol),l=qk(a,i.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:de(e),totalCallees:i.size,extractionKind:l.extractionKind,actionTier:"signal",evidenceReasons:l.evidenceReasons,recommendation:l.recommendation,clusters:s}}function qk(e,t,n,i){let r=Math.max(...i.map(l=>l.callees.length)),o=Math.max(...i.map(l=>l.isolation)),s=[`${t} distinct callees across ${n} co-occurrence cluster(s)`,`${i.length} extractable cluster(s) passed size and isolation thresholds`,`largest extractable cluster has ${r} callees at ${Math.round(o*100)}% isolation`],a=Wk(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."}:r>=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 Wk(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 i=Vk(e);return Jk.has(i)?`caller verb suggests orchestration: ${i}`:null}function Vk(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 Jk=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function Yk(e,t){let n=new Map;for(let r of e)n.set(r,new Set);let i=new Map;for(let r of t){let o=i.get(r.chunkId);o||(o=new Set,i.set(r.chunkId,o)),o.add(r.symbol)}for(let r of i.values()){let o=[...r];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 Xk(e,t){let n=new Set,i=[];for(let r of e){if(n.has(r))continue;let o=new Set,s=[r];for(;s.length>0;){let a=s.pop();if(!n.has(a)){n.add(a),o.add(a);for(let l of t.get(a)??[])n.has(l)||s.push(l)}}i.push(o)}return i}function Zk(e,t){return e.filter(n=>n.size>=3).map(n=>Qk(n,e,t)).filter(n=>n.isolation>.5).sort((n,i)=>i.isolation-n.isolation)}function Qk(e,t,n){let i=new Set;for(let a of t)if(a!==e)for(let l of a)i.add(l);let r=0;for(let a of e)for(let l of n.get(a)??[])i.has(l)&&r++;let o=e.size*i.size,s=o>0?1-r/o:1;return{callees:[...e].map(k),isolation:s}}import{posix as lr}from"path";import{spawnSync as e_}from"child_process";import{createHash as t_}from"crypto";import{existsSync as n_}from"fs";import{dirname as lS,join as i_}from"path";import{fileURLToPath as r_}from"url";var dS=Fi("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),cS=vt({kind:"consumer-file-usage",invalidation:Je("consumer-file-usage"),serialize:p_,deserialize:g_});function un(e,t){return{forDefinitions(n,i){return o_(e,t,n,i)}}}function Qn(e){let t=new Map;for(let[n,i]of e)t.set(n,new Set(i.files.map(r=>r.file)));return t}function Da(e,t,n){return fS(e,t,n).partition}function o_(e,t,n,i){let r=mS(n.length),o=ft()?gn(e):null,s=o?s_(n,i,o):void 0,a=s?{workIdentity:s,workOutcome:"computed"}:{};return $("consumer-evidence.product",()=>{let l=$("consumer-evidence.provenance",()=>a_(e,t,n,i),()=>({...a,definitions:n.length,semantic:i.semantic,sourceFallback:i.sourceFallback!==!1})),c=new Map;r={...r,...l.counters};let u=l_(n,l.sources);return $("consumer-evidence.classify",()=>{let d=c_(e,n,l.sources,u);for(let m of n){let f=d.get(m.symbolId)??d_();r.realFiles+=f.partition.realConsumers.length,r.reexportOnlyFiles+=f.partition.barrelConsumers,r.importOnlyFiles+=f.partition.importOnlyConsumers,c.set(m.symbolId,{definition:m,files:f.files,semanticIncomplete:l.incompleteSymbolIds.has(m.symbolId),semanticUnavailable:l.unavailableSymbolIds.has(m.symbolId),...f.partition})}},()=>({...a,...u,realFiles:r.realFiles,reexportOnlyFiles:r.reexportOnlyFiles,importOnlyFiles:r.importOnlyFiles})),c},()=>({...a,...r}))}function s_(e,t,n){let i=t_("sha256").update("consumer-evidence-v3-calibrated-semantic\0").update(n).update("\0").update(t.semantic?"semantic\0":"indexed\0").update(t.sourceFallback===!1?"no-source-fallback":"source-fallback");for(let r of e.map(o=>o.symbol).sort())i.update("\0").update(r);return i.digest("hex").slice(0,24)}function mS(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function a_(e,t,n,i){let r=mS(n.length),o=new Map,s=new Set,a=new Set;if(Ru(o,r,"indexed",t.crossFileCallerMap(n,{semantic:!1})),i.semantic){let l=Cn(e,n);Ru(o,r,"semantic",l.callers);for(let c of l.incompleteSymbolIds)s.add(c);for(let c of l.unavailableSymbolIds)a.add(c)}return i.sourceFallback!==!1&&Ru(o,r,"source-fallback",t.sourceFallbackCallerFiles(n)),r.totalFiles=[...o.values()].reduce((l,c)=>l+c.size,0),{sources:o,counters:r,incompleteSymbolIds:s,unavailableSymbolIds:a}}function l_(e,t){return{definitions:e.length,consumerFiles:[...t.values()].reduce((n,i)=>n+i.size,0),nativeAttempted:!1,nativeUsed:!1,nativeReason:"not-attempted"}}function Ru(e,t,n,i){let r=0;for(let[o,s]of i){let a=e.get(o);a||(a=new Map,e.set(o,a));for(let l of s){r++;let c=a.get(l)??new Set;c.add(n),a.set(l,c)}}n==="indexed"?t.indexedFiles+=r:n==="semantic"?t.semanticFiles+=r:t.fallbackFiles+=r}function c_(e,t,n,i){let r=x_(e,t,n,i);return r||u_(e,t,n)}function u_(e,t,n){let i=new Map;for(let r of t){let o=n.get(r.symbolId)??new Map;i.set(r.symbolId,fS(e,r,[...o.keys()],o))}return i}function fS(e,t,n,i=new Map){let r=[],o=0,s=0,a=re(t.symbol),l=[];for(let c of n){let u;h_(e,c,t.relativePath,a)?(o++,u="reexport-only"):Eu(e,c,a)?(s++,u="import-only"):(r.push(c),u="real"),l.push({file:c,sources:[...i.get(c)??[]],classification:u})}return{partition:{realConsumers:r,barrelConsumers:o,importOnlyConsumers:s},files:l}}function d_(){return{partition:{realConsumers:[],barrelConsumers:0,importOnlyConsumers:0},files:[]}}function Eu(e,t,n){if(!n)return!1;let i=ye(t);if(!i)return!1;let r=dS.get(e,t,()=>pS(e,t,i));return r.importedLeaves.has(n)&&!r.usedLeaves.has(n)}function pS(e,t,n){let i=Nn(e).forFile(t,{text:!0,ast:!0}),r=i.text;if(!r)return f_();let o=Ft(e,t,r),s=cS.read(e,t,o);if(s)return s;let a=m_(i.ast,n);return cS.write(e,t,o,a),a}function m_(e,t){let n=new Set,i=new Set;if(!e)return{importedLeaves:n,usedLeaves:i};let r=t==="rust"?new Set(["use_declaration"]):t==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),o=(s,a)=>{let l=a||r.has(s.type);(s.type==="identifier"||s.type==="type_identifier"||s.type==="property_identifier"||s.type==="field_identifier")&&(l?n.add(s.text):i.add(s.text));for(let c of s.children)o(c,l)};return o(e.rootNode,!1),{importedLeaves:n,usedLeaves:i}}function f_(){return{importedLeaves:new Set,usedLeaves:new Set}}function p_(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function g_(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 h_(e,t,n,i){if(!i)return!1;let r=Nn(e).forFile(t,{lines:!0,reexports:!0}),o=r.lines??[];if(o.length===0)return!1;let s=r.reexports??[];return gS(o,s,i)}function gS(e,t,n){if(e.length===0||t.length===0)return!1;let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`\\b${i}\\b`),o=0;for(let s=0;s<e.length;s++){if(!r.test(e[s]??""))continue;if(o++,!t.find(l=>l.startLine<=s&&s<=l.endLine))return!1}return o>0}var y_="CODEBASEIQ_NATIVE_CONSUMER_CLASSIFY",b_="CODEBASEIQ_NATIVE_KERNELS_BIN",S_="CODEBASEIQ_NATIVE_CONSUMER_CLASSIFY_MIN_FILES",uS=1e3,v_=5e3,C_=64*1024*1024,La;function x_(e,t,n,i){let r=process.env[y_]?.toLowerCase();if(r!=="1"&&r!=="true")return i.nativeReason=r==="0"||r==="false"?"disabled":"opt-in-required",null;if(i.consumerFiles<P_())return i.nativeReason="below-threshold",null;let o=T_();if(!o)return i.nativeReason="binary-missing",null;i.nativeAttempted=!0;let s=R_(e,t,n),a=e_(o,["consumer-classify"],{input:JSON.stringify(s),encoding:"utf8",timeout:v_,maxBuffer:C_,windowsHide:!0});if(a.status!==0||a.error)return i.nativeReason=a.error?`spawn-error:${a.error.message}`:`exit-${a.status??"null"}`,null;try{let l=JSON.parse(a.stdout),c=w_(l,t);return c?(i.nativeUsed=!0,i.nativeReason="used",c):(i.nativeReason="invalid-response",null)}catch{return i.nativeReason="invalid-json",null}}function R_(e,t,n){let i=new Map,r=[];for(let a of t){let l=re(a.symbol),u=[...(n.get(a.symbolId)??new Map).entries()].map(([d,m])=>{let f=i.get(d)??new Set;return l&&f.add(l),i.set(d,f),{file:d,sources:[...m]}});r.push({symbol_id:a.symbolId,leaf:l,consumer_files:u})}let o={},s={};for(let[a,l]of i){let c=ye(a);if(c){let d=dS.get(e,a,()=>pS(e,a,c));o[a]={imported_leaves:[...d.importedLeaves],used_leaves:[...d.usedLeaves]}}let u=E_(e,a,l);u.length>0&&(s[a]=u)}return{definitions:r,file_usages:o,reexport_only_leaves:s}}function E_(e,t,n){if(n.size===0)return[];let i=Nn(e).forFile(t,{lines:!0,reexports:!0}),r=i.lines??[],o=i.reexports??[];return r.length===0||o.length===0?[]:[...n].filter(s=>gS(r,o,s))}function w_(e,t){if(!Array.isArray(e.entries)||e.entries.length!==t.length)return null;let n=new Set(t.map(r=>r.symbolId)),i=new Map;for(let r of e.entries){let o=I_(r);if(!o||!n.has(o.symbol_id))return null;i.set(o.symbol_id,{partition:{realConsumers:o.real_consumers,barrelConsumers:o.barrel_consumers,importOnlyConsumers:o.import_only_consumers},files:o.files})}for(let r of n)if(!i.has(r))return null;return i}function I_(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(i=>typeof i=="string"))return null;let n=[];for(let i of t.files){if(!i||typeof i!="object")return null;let r=i;if(typeof r.file!="string"||!Array.isArray(r.sources)||!r.sources.every(L_)||!D_(r.classification))return null;n.push({file:r.file,sources:r.sources,classification:r.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 L_(e){return e==="indexed"||e==="semantic"||e==="source-fallback"}function D_(e){return e==="real"||e==="reexport-only"||e==="import-only"}function P_(){let e=process.env[S_];if(!e)return uS;let t=Number(e);return Number.isFinite(t)&&t>=0?t:uS}function T_(){if(La!==void 0)return La;let e=process.env[b_],t=process.platform==="win32"?"codebaseiq-kernels.exe":"codebaseiq-kernels";return La=[...e?[e]:[],...F_().map(i=>i_(i,"target","release",t))].find(i=>n_(i))??null,La}function F_(){let e=new Set,t=lS(r_(import.meta.url));for(let n=0;n<5;n++)e.add(t),t=lS(t);return[...e]}var M_=20,A_=1,N_=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"]]),k_=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),__=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 B_(e,t={}){let n=Lu(t.limit,M_),i=Lu(t.minConsumers,A_),r=new U(e),o=r.fileDependencyGraph(t.scope),s=iB(he(e,{includeIgnored:!1})),a=sB(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?O_(e,r,t.target):$_(e,t.scope,t.scanLimit)).map(u=>j_(e,r,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=i||t.target).sort(nB).slice(0,n)}function O_(e,t,n){let i=z_(e,n);if(i)return[vS(i)];let r=fe(e,n);if(!r)return[];let o=t.definitionsForFile(r.relativePath).find(s=>s.symbolId===r.symbolId);return o?[G_(o)]:[{unit:{kind:"symbol",file:r.relativePath,shortName:k(r.symbol),symbol:r.symbol,startLine:r.startLine,endLine:r.endLine}}]}function $_(e,t,n){let i=he(e,{scope:t,includeIgnored:!1}),r=Lu(n,i.length);return i.slice(0,r).map(o=>vS(o))}function j_(e,t,n,i,r,o,s){let a=i.definition?H_(e,t,i.definition,r.semantic):null,l=a?.files??U_(n,i.unit.file),c=i.definition?a.coverage==="complete"?l.length>0?"exact":"none":a.coverage:l.length>0?"file-level":"none",u=c==="incomplete"||c==="unavailable"||c==="incomplete-and-unavailable",d=i.unit.file,m=qt(lr.dirname(d)),f=q_(l),p=K_(m),g=Pu([...hS(m),...f?hS(f):[]]),h=u?"repository-level-review":W_(i.unit,m,f,l),S=u?{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:`Compiler-resolved consumer evidence is ${c}; no relocation destination is safe to score.`}:V_(h,i.unit,m,f,l,o,s),v=Q_(i.unit,c,f,l,m,S.whyNoSuggestedHome),y=eB(i.unit,m,f,l,S.suggestedHome,S.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:i.unit,candidatePath:d,currentDirectory:m,directoryAncestry:p,consumerFiles:l,consumerCoverage:c,nearestCommonOwner:f,boundaryMarkers:g,recommendedTier:h,suggestedHome:S.suggestedHome,destinationConfidence:S.confidence,whyNoSuggestedHome:S.whyNoSuggestedHome,counterevidence:u?[...v,"Known consumer files are retained, but missing compiler evidence can hide additional owners."]:v,reasons:y,recommendation:u?"Retain the current location until compiler-resolved consumer evidence is complete.":tB(h,S.suggestedHome,c)}}function H_(e,t,n,i){let r=un(e,t).forDefinitions([n],{semantic:i!==!1,sourceFallback:!0}).get(n.symbolId),o=r?.semanticIncomplete?r.semanticUnavailable?"incomplete-and-unavailable":"incomplete":r?.semanticUnavailable?"unavailable":"complete";return{files:wS(r?.files.map(s=>s.file)??[]),coverage:o}}function U_(e,t){let n=[];for(let[i,r]of e.entries())i!==t&&r.has(t)&&n.push(i);return wS(n)}function z_(e,t){let n=zo(t),i=he(e,{includeIgnored:!1}),r=i.find(s=>s===n);if(r)return r;let o=i.find(s=>s.endsWith(`/${n}`));return o||(i.find(s=>s.includes(n))??null)}function G_(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:k(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function vS(e){return{unit:{kind:"file",file:e,shortName:lr.basename(e)}}}function K_(e){if(e===".")return[{path:".",depth:0,markers:[]}];let t=[],n=e.split("/").filter(Boolean);for(let i=0;i<n.length;i+=1){let r=n.slice(0,i+1).join("/");t.push({path:r,depth:i,markers:Du(r)})}return t}function hS(e){return e==="."?[]:CS(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function Du(e){return Pu(CS(e).map(({marker:t})=>t))}function CS(e){let t=e.split("/").filter(Boolean),n=[];for(let i=0;i<t.length;i+=1){let r=N_.get(t[i]);r&&n.push({marker:r,prefix:t.slice(0,i+1).join("/")})}return n}function q_(e){if(e.length===0)return null;let t=e.map(i=>qt(lr.dirname(i))),n=t[0].split("/").filter(Boolean);for(let i of t.slice(1)){let r=i.split("/").filter(Boolean),o=[],s=Math.min(n.length,r.length);for(let a=0;a<s&&n[a]===r[a];a+=1)o.push(n[a]);n=o}return n.length===0?".":n.join("/")}function W_(e,t,n,i){return n?e.kind==="symbol"&&i.length===1?i[0]===e.file?"same-file":"sibling-folder":n==="."||n==="src"?"repository-level-review":bS(n,"package")?"package-level-shared":bS(n,"app")?"app-level-shared":SS(n,["feature","domain","module"])||SS(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function V_(e,t,n,i,r,o,s){let a=J_(e,i);if(a)return ei(a);let l=rB(t.file),c=Y_(e,n,l,r,s);if(c)return c;let u=i;if(qt(n)===qt(u))return ei(`${n} is already the nearest common owner for its consumers.`);let d=X_(u,n,l,s);return d||Z_(u,n,l,o,s)}function J_(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 Y_(e,t,n,i,r){if(e==="same-file"){let o=i[0]??null;return o?wu(o):ei("No same-file consumer path was available.")}if(e==="sibling-folder"&&i.length===1){let o=qt(lr.dirname(i[0])),s=ES(t,n,o,r);return s?ei(s):wu(o)}return null}function X_(e,t,n,i){return lB(e)?xS(e,t,n,i,`Nearest shared owner ${e} is outside source root ${n}.`):null}function Z_(e,t,n,i,r){if(e===".")return ei("The nearest common owner is the repository root.");let o=`${e}/shared`,s=xS(o,t,n,r,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||i.has(o)?s:ei(`${o} does not exist in the indexed project.`)}function xS(e,t,n,i,r){if(!RS(e,n))return ei(r);let o=ES(t,n,e,i);return o?ei(o):wu(e)}function wu(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function ei(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function Q_(e,t,n,i,r,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."),i.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&&r.startsWith(`${n}/`)&&s.push("Candidate already lives under the nearest common owner."),o&&s.push(`No exact suggested home: ${o}`),s}function eB(e,t,n,i,r,o){let s=[];return s.push(`${e.shortName} currently lives in ${t}.`),n?s.push(`${i.length} consumer file(s) share ${n} as their nearest common owner.`):s.push("No consumer owner could be inferred from the current index."),r?s.push(`Suggested home is ${r}.`):o&&s.push(`No exact suggested home: ${o}`),s}function tB(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 nB(e,t){return yS(t)-yS(e)||e.candidatePath.localeCompare(t.candidatePath)}function yS(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 iB(e){let t=new Set(["."]);for(let n of e){let i=qt(lr.dirname(n));for(;!t.has(i)&&(t.add(i),i!==".");)i=qt(lr.dirname(i))}return t}function rB(e){let t=Iu(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function RS(e,t){let n=qt(e),i=qt(t);return i==="."||n===i||n.startsWith(`${i}/`)}function oB(e,t,n){let i=Iu(e),r=Iu(t);return(RS(e,t)?i.slice(r.length):i).some(s=>n.has(s.toLowerCase()))}function ES(e,t,n,i){return qt(e)===qt(n)||!oB(e,t,i)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function sB(...e){let t=new Set(__);for(let n of e)for(let i of n??[]){let r=aB(i);r&&t.add(r)}return t}function aB(e){let t=e.trim().toLowerCase();return t===""?null:t}function bS(e,t){return Du(e).includes(t)}function SS(e,t){let n=Du(e);return t.some(i=>n.includes(i))}function lB(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?k_.has(n):!1}function qt(e){let t=zo(e);return t===""?".":t}function Iu(e){let t=zo(e);return t==="."?[]:t.split("/").filter(Boolean)}function Lu(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function wS(e){return Pu([...e]).sort((t,n)=>t.localeCompare(n))}function Pu(e){return[...new Set(e)]}function Tu(e,t,n={}){return cB(e,t,n)}function cB(e,t,n){let{maxDepth:i=5,scope:r}=n,o=i===Number.MAX_SAFE_INTEGER,s=o?null:500,a=fe(e,t);if(!a)return{rows:[],coverage:{status:"incomplete",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:i,reachedDepth:0,perSymbolEvidenceLimit:s,remainingFrontierSymbols:0,reasons:["The requested symbol could not be resolved."],semanticEvidence:"incomplete"}};let l=[],c=new Set([a.symbolId]),u=new Set,d=[a],m=0,f=!1,p=!1,g=!1;for(let v=1;v<=i&&d.length!==0;v++){m=v;let y=[],E=Qt(e,d,{...o?{}:{limit:s+1},semanticEvidence:pe});E.incompleteSymbolIds.size>0&&(p=!0),E.unavailableSymbolIds.size>0&&(g=!0);for(let w of d){let b=E.rows.get(w.symbolId)??[];s!==null&&b.length>s&&(f=!0);let R=s===null?b:b.slice(0,s);for(let C of uB(e,w,r,R)){let L=`${C.file}|${C.shortName}`;if(C.symbolId!==null){if(c.has(C.symbolId))continue;c.add(C.symbolId)}else if(u.has(L))continue;u.add(L),l.push({symbol:C.symbol,shortName:C.shortName,file:C.file,depth:v}),C.symbolId!==null&&C.symbolMatch&&y.push(C.symbolMatch)}}d=y}l.sort((v,y)=>v.depth-y.depth||v.file.localeCompare(y.file));let h=d.length>0,S=[];return h&&S.push(`${d.length} symbol(s) remain eligible beyond depth ${i}.`),f&&S.push(`At least one symbol had more than ${s} incoming evidence row(s).`),p&&S.push("Compiler-resolved incoming evidence was incomplete for at least one traversed symbol."),g&&S.push("Compiler-resolved incoming evidence was unavailable for at least one traversed symbol."),S.length===0&&S.push("The discovered reverse evidence frontier was exhausted."),{rows:l,coverage:{status:p||g?"incomplete":h||f?"bounded":"accounted",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:i,reachedDepth:m,perSymbolEvidenceLimit:s,remainingFrontierSymbols:d.length,reasons:S,semanticEvidence:p&&g?"incomplete-and-unavailable":p?"incomplete":g?"unavailable":"complete"}}}function uB(e,t,n,i){let r=i.filter(u=>!e.isIgnored(u.file)).filter(u=>!n||u.file.includes(n)),o=new Set(r.map(u=>u.file)),s=[];for(let u of dB(e,t,n)){if(o.has(u))continue;let d=J(e,u),m=d.length>0?Ge(d,d[0].startLine):null;s.push({symbol:m?.symbol??u,file:u})}let a=[...r,...s],l=[],c=new Set;for(let u of a){let d=ri(e,u.symbol);if(!d){let f=`${u.file}|${u.symbol}`;if(c.has(f))continue;c.add(f),l.push({symbolId:null,symbol:u.symbol,shortName:k(u.symbol),file:u.file,symbolMatch:null});continue}if(d.symbolId===t.symbolId||e.isIgnored(d.relativePath)||!mB(d))continue;let m=`${d.symbolId}|${d.relativePath}`;c.has(m)||(c.add(m),l.push({symbolId:d.symbolId,symbol:d.symbol,shortName:k(d.symbol),file:d.relativePath,symbolMatch:d}))}return l}function dB(e,t,n){let i=n?"AND consumer_d.relative_path LIKE ?":"",r=[t.symbolId,t.documentId];return n&&r.push(`%${n}%`),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
|
|
321
|
+
FROM mentions m
|
|
322
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
323
|
+
JOIN documents consumer_d ON consumer_d.id = c.document_id
|
|
324
|
+
WHERE m.symbol_id = ?
|
|
325
|
+
AND m.role != 1
|
|
326
|
+
AND c.document_id != ?
|
|
327
|
+
${e.pathExclusionsFor("consumer_d")}
|
|
328
|
+
${i}`,...r).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function mB(e){if(e.symbol.startsWith("scip-clojure ")||ye(e.relativePath)==="clojure")return!0;let t=kn(e.symbol);return t==="method"||t==="type"||e.symbol.endsWith("().")}function LS(e,t){let n=pt(t),i=[],r="complete",o=V(n);o==="entry"&&Fn(i,"operational-root","structural entrypoint path"),o==="worker"&&Fn(i,"operational-root","worker launch convention"),bc(n)&&Fn(i,"operational-root","framework-discovered entrypoint"),fB(e,n)&&Fn(i,"operational-root","configured entry root");let s=!1;try{s=En(e,n),s&&Fn(i,"published-api","package manifest export");for(let a of rg(e,n))Fn(i,"operational-root",a)}catch(a){r="partial",Fn(i,"metadata-unavailable",`package metadata unavailable: ${IS(a)}`)}try{let a=nt(e.config.projectRoot,n,{maxBytes:8388608,inputKind:"change-surface source"});pB(a)&&Fn(i,"operational-root","module contains a direct-execution process guard")}catch(a){r="partial",Fn(i,"metadata-unavailable",St(a)?"indexed source file is unavailable on disk":`source metadata unavailable: ${IS(a)}`)}return{operationalRoot:i.some(a=>a.kind==="operational-root"),publishedApi:s,coverage:r,reasons:i}}function fB(e,t){let n=e.config.entryRoots;return n?n.files?.some(i=>pt(i)===t)?!0:n.pathPrefixes?.some(i=>t.startsWith(pt(i)))??!1:!1}function pB(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 Fn(e,t,n){e.some(i=>i.kind===t&&i.detail===n)||e.push({kind:t,detail:n})}function IS(e){return e instanceof Error?e.message:String(e)}function Fu(e,t,n={}){let i=lt(e,t);if(!i)return null;let r=hB(e,i);if(!r||e.isIgnored(r.relative_path))return null;let o=[],s=0,a=!0,l=yB(e,r.relative_path),c=LS(e,r.relative_path),u=n.semantic===!1?{callers:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set}:Cn(e,l);for(let d of l){let m=bB(e,r,d,u.callers.get(d.symbolId)??new Set);s+=m;let f=gB(n.semantic!==!1,d.symbolId,u),p=f==="complete"||f==="disabled";p||(a=!1);let g=p?m:null,h=g===null?void 0:SB(g),S=[...c.reasons,...m>0?[{kind:"external-consumers",detail:`${m} known external consumer${m===1?"":"s"}`}]:[],...p?[]:[{kind:"semantic-consumer-coverage",detail:`compiler-resolved consumer evidence is ${f}`}]];o.push({symbol:d.symbol,shortName:k(d.symbol),startLine:d.startLine,endLine:d.endLine,externalConsumers:g,knownExternalConsumers:m,consumerCoverage:f,externalConsumerRiskLevel:h,riskLevel:vB(h,c,!p),riskReasons:S})}return{file:r.relative_path,symbols:o,totalExternalConsumers:a?s:null,knownTotalExternalConsumers:s,fileRisk:c}}function gB(e,t,n){if(!e)return"disabled";let i=n.incompleteSymbolIds.has(t),r=n.unavailableSymbolIds.has(t);return i&&r?"incomplete-and-unavailable":i?"incomplete":r?"unavailable":"complete"}function hB(e,t){return e.get(`SELECT id, relative_path FROM documents
|
|
329
|
+
WHERE relative_path = ?
|
|
330
|
+
${e.pathExclusionsFor("documents")}
|
|
331
|
+
LIMIT 1`,t)??null}function yB(e,t){return new U(e).definitionsForFile(t).sort((n,i)=>n.startLine-i.startLine||n.endLine-i.endLine)}function bB(e,t,n,i){let r=e.all(`SELECT DISTINCT consumer_d.relative_path
|
|
332
|
+
FROM mentions m
|
|
333
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
334
|
+
JOIN documents consumer_d ON consumer_d.id = c.document_id
|
|
335
|
+
WHERE m.symbol_id = ?
|
|
336
|
+
AND m.role != 1
|
|
337
|
+
AND c.document_id != ?`,n.symbolId,t.id);return new Set([...r.map(o=>o.relative_path),...[...i].filter(o=>o!==t.relative_path)]).size}function SB(e){return e>10?"high":e>0?"medium":"low"}function vB(e,t,n){return e==="high"?"high":n||e==="medium"||t.operationalRoot||t.publishedApi||t.coverage==="partial"?"medium":"low"}function CB(e,t={}){let{scope:n,minLoc:i=1,maxDepth:r=5,scanLimit:o}=t,s=new U(e),a=xB(e,n,i,o),l=new Mu;for(let g of a)l.add(g);let c=[],u=[];a.length>0&&c.push(DS(e,0,a,l));let d=a.map(g=>g.definition).filter(g=>g!==null),m=new Set(a.map(g=>g.symbol));for(let g=1;g<=r&&d.length>0;g++){let h=s.calleeMap(d,{semantic:!1}),S=new Set;for(let y of d)for(let E of h.get(y.symbolId)??[])m.has(E.symbol)||S.add(E.symbol);let v=[];for(let y of S){m.add(y);let E=PS(e,y);if(!E||e.isIgnored(E.relativePath)||Ye(e,E.relativePath)||Ue(e,E.symbol,E.relativePath)||s.fileKind(E.relativePath)==="test"||s.hasSuppressionComment(E))continue;let w=EB(e,E,l);w.removable?v.push(RB(E,"cascade")):w.blockingFiles.length>0&&u.push({shortName:k(E.symbol),file:E.relativePath,blockingFiles:w.blockingFiles.slice(0,3)})}if(v.length===0)break;for(let y of v)l.add(y);c.push(DS(e,g,v,l)),d=v.map(y=>y.definition).filter(y=>y!==null)}let f=c.reduce((g,h)=>g+h.loc,0),p=c.reduce((g,h)=>g+h.entries.length,0);return{batches:c,totalSymbols:p,totalLoc:f,blocked:u}}function xB(e,t,n,i){let r=wi(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:i,semantic:!1}),o=[];for(let s of r.symbols)s.kind==="dead-code"&&(Ye(e,s.relativePath)||Ue(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:PS(e,s.symbol)}));return o}function RB(e,t){return{symbol:e.symbol,shortName:k(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function PS(e,t){let n=e.get(`SELECT d.relative_path
|
|
338
|
+
FROM global_symbols gs
|
|
339
|
+
JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
340
|
+
JOIN documents d ON d.id = der.document_id
|
|
341
|
+
WHERE gs.symbol = ?
|
|
342
|
+
LIMIT 1`,t);return n?J(e,n.relative_path).find(i=>i.symbol===t)??null:null}function EB(e,t,n){let i=Cr(e,t);if(i.length===0)return{removable:!1,blockingFiles:[]};let r=new Set;for(let o of i)o.file===t.relativePath&&o.line>=t.startLine&&o.line<=t.endLine||n.contains(o.file,o.line)||r.add(o.file);return{removable:r.size===0,blockingFiles:[...r]}}function DS(e,t,n,i){let r=[...n].sort((a,l)=>a.file.localeCompare(l.file)||a.startLine-l.startLine),o=new Set(r.map(a=>a.file)),s=[];for(let a of o){let l=J(e,a);l.length>0&&l.every(c=>i.contains(a,c.startLine))&&s.push(a)}return{depth:t,entries:r.map(({definition:a,...l})=>l),loc:r.reduce((a,l)=>a+l.loc,0),filesEmptied:s.sort()}}var Mu=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 i=this.ranges.get(t);return i?i.some(r=>n>=r.start&&n<=r.end):!1}};import{execFileSync as cr}from"child_process";import{existsSync as wB}from"fs";import{basename as TS}from"path";function Pa(e){let t=new Map;for(let n of e){let i=t.get(n.file);i||(i=[],t.set(n.file,i)),i.push(n)}return t}var Bu="Unable to compute git diff.",IB={semanticConsumers:Sp,sourceFallbackConsumers:Ur},Ou={resolveCommit:al,readBatch({projectRoot:e,resolvedBase:t,relativePaths:n}){let i=n.map(r=>`${t}:./${r}
|
|
343
|
+
`).join("");return cr("git",["cat-file","--batch"],{cwd:e,input:i,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"],windowsHide:!0})}};function Ta(e,t={}){let n=t.plan??ur(e,t);return n.note?LB(n.note,n.changedFileLines):n.changedFiles.length===0?DB(n.changedFileLines):Fa(n.changedFiles,[NS(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function ur(e,t={}){let{base:n="HEAD"}=t;try{let i=al(e.config.projectRoot,n),r=PB(e.config.projectRoot,i),o=r.changedFileLines,s=kB(e,o),a=_B(e,r.changedRanges);return{changedFileLines:o,changedFiles:s,changedRanges:a,renamedFiles:MB(e.config.projectRoot,i,s,r),note:o.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:Bu}}}function NS(e,t,n,i=[],r={}){let o=r.evidenceRuntime??IB,s=new U(e),a=new Set(n),l=Pa(i),c=[],u=new Map,d=t.flatMap(C=>s.definitionsForFile(C)).filter(ZB),m=d.filter(C=>OB(C,l)),f=jB(e,d,m,l),p=zB([...m,...f.definitions]).sort((C,L)=>C.relativePath.localeCompare(L.relativePath)||C.startLine-L.startLine),g=p.map(C=>C.symbolId),h=JB(e,g),S=YB(e,g,n),v=p.filter(C=>(h.get(C.symbolId)??0)===0),y=AS("semantic-consumers",v.length,()=>o.semanticConsumers(e,v)),E=y.values,w=v.filter(C=>(E.get(C.symbolId)?.size??0)===0),b=AS("source-fallback-consumers",w.length,()=>o.sourceFallbackConsumers(e,w)),R=b.values;for(let C of p)qB(e,C,a,c,u,E.get(C.symbolId)??new Set,R.get(C.symbolId)??new Set,h.get(C.symbolId)??0,S.get(C.symbolId)??new Set);return{changedSymbols:c,consumerEntries:[...u.entries()].map(([C,L])=>({file:C,symbols:[...L].sort()})),attributionNotes:f.notes,evidenceTiers:[y.status,b.status]}}function Fa(e,t){let n=new Map,i=t.flatMap(a=>a.changedSymbols),r=t.flatMap(a=>a.attributionNotes??[]),o=WB(t);for(let a of t)for(let l of a.consumerEntries){let c=n.get(l.file);c||(c=new Set,n.set(l.file,c));for(let u of l.symbols)c.add(u)}let s=XB(n);return{changedFiles:[...e],changedSymbols:i,affectedConsumers:s,attributionNotes:r,evidenceTiers:o,summary:{totalChangedFiles:e.length,totalChangedSymbols:i.length,totalAffectedFiles:s.length}}}function LB(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:HS(),summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function DB(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:HS(),summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function PB(e,t){let n=cr("git",["diff","--name-status","--find-renames",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864,windowsHide:!0}),i=cr("git",["diff","--name-status","--find-renames","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024,windowsHide:!0}),r=cr("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024,windowsHide:!0}),o=cr("git",["diff","--unified=0",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024,windowsHide:!0}),s=cr("git",["diff","--unified=0","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024,windowsHide:!0}),a=AB([n,i]);return{changedFileLines:[...new Set([...a.changedFiles,...BS(r)])],changedRanges:$S([...MS(o),...MS(s)]),renamedFiles:a.renamedFiles,deletedFiles:a.deletedFiles}}function TB(e,t,n){let i=typeof e=="string"?{projectRoot:e,base:t,relativePath:n}:e;if(typeof i.projectRoot!="string"||typeof i.base!="string"||typeof i.relativePath!="string")throw new TypeError("fileContentAtBase requires projectRoot, base, and relativePath.");let r={projectRoot:i.projectRoot,base:i.base,relativePath:i.relativePath},{relativePath:o}=r,s=$u(r);if(s.state==="unavailable")throw new Error(`Base content unavailable for ${o}: ${s.reason}`);return s.state==="present"?s.content:null}function $u(e,t=Ou){return _S(e.relativePath),ju({projectRoot:e.projectRoot,base:e.base,relativePaths:[e.relativePath]},t).get(e.relativePath)??{state:"unavailable",reason:`Base-content lookup omitted ${e.relativePath}.`}}function ju(e,t=Ou){for(let s of e.relativePaths)_S(s);let n=[...new Set(e.relativePaths)];if(n.length===0)return new Map;let i;try{i=t.resolveCommit(e.projectRoot,e.base)}catch(s){return Au(n,Nu(s))}let r;try{r=t.readBatch({projectRoot:e.projectRoot,resolvedBase:i,relativePaths:n})}catch(s){return Au(n,Nu(s))}let o;try{o=FB(r,n)}catch(s){return Au(n,`Malformed git cat-file batch output: ${Nu(s)}`)}return new Map(n.map(s=>{let a=o.get(s)??null;return[s,a===null?{state:"absent"}:{state:"present",content:a}]}))}function Hu(e,t=Ou){let n=ju({projectRoot:e.projectRoot,base:e.base,relativePaths:e.preloadPaths??[]},t);return i=>(n.has(i)||n.set(i,$u({projectRoot:e.projectRoot,base:e.base,relativePath:i},t)),n.get(i)??{state:"unavailable",reason:`Base-content reader omitted ${i}.`})}function kS(e,t=e.changedFiles){let n=new Map(e.renamedFiles.map(i=>[i.to,i.from]));return[...new Set(t.map(i=>n.get(i)??i))]}function _S(e){pn(e)}function Au(e,t){return new Map(e.map(n=>[n,{state:"unavailable",reason:t}]))}function Nu(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 FB(e,t){let n=new Map,i=0;for(let r of t){let o=e.indexOf(10,i);if(o<0)throw new Error("git cat-file batch output ended before object header");let s=e.subarray(i,o).toString("utf-8");if(i=o+1,s.endsWith(" missing")){n.set(r,null);continue}let a=/^[0-9a-f]+ ([^ ]+) (\d+)$/.exec(s);if(!a)throw new Error(`unexpected git cat-file batch header: ${s}`);let[,l,c]=a,u=Number(c);if(!Number.isFinite(u)||u<0)throw new Error(`unexpected git cat-file batch size: ${s}`);if(i+u>e.length)throw new Error("git cat-file batch output ended before blob payload");let d=e.subarray(i,i+u);n.set(r,l==="blob"?d.toString("utf-8"):null),i+=u,e[i]===10&&(i+=1)}return n}function MB(e,t,n,i){if(n.length===0)return[];let r=new Map,o=new Set;for(let a of i.renamedFiles)n.includes(a.to)&&(r.set(a.to,a),o.add(a.from));let s=i.deletedFiles;if(s.length===0)return[...r.values()].sort((a,l)=>a.to.localeCompare(l.to));for(let a of n){if(r.has(a)||!wB(`${e}/${a}`))continue;let l=s.filter(d=>!o.has(d)).filter(d=>TS(d)===TS(a));if(l.length===0)continue;let c=nt(e,a),u=l.map(d=>({from:d,to:a,similarity:NB(TB({projectRoot:e,base:t,relativePath:d})??"",c)})).sort((d,m)=>m.similarity-d.similarity)[0];u&&u.similarity>=.45&&(r.set(a,u),o.add(u.from))}return[...r.values()].sort((a,l)=>a.to.localeCompare(l.to))}function AB(e){let t=new Set,n=new Map,i=new Set;for(let r of e.flatMap(o=>BS(o))){let[o,s,a]=r.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")&&i.add(s)}}return{changedFiles:[...t],renamedFiles:[...n.values()],deletedFiles:[...i]}}function NB(e,t){let n=new Set(FS(e)),i=new Set(FS(t));if(n.size===0&&i.size===0)return 1;if(n.size===0||i.size===0)return 0;let r=0;for(let o of n)i.has(o)&&(r+=1);return 2*r/(n.size+i.size)}function FS(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function BS(e){return e.split(`
|
|
344
|
+
`).map(t=>t.trim()).filter(t=>t.length>0)}function kB(e,t){let n=OS(e),i=[];for(let r of t){let o=n(r);o&&!e.isIgnored(o)&&i.push(o)}return i}function _B(e,t){let n=OS(e),i=[];for(let r of t){let o=n(r.file);o&&!e.isIgnored(o)&&i.push({...r,file:o})}return $S(i)}function OS(e){let n=e.all(`SELECT relative_path FROM documents
|
|
345
|
+
ORDER BY id`).map(r=>r.relative_path).map(r=>({path:r,normalized:pn(r)})),i=new Map;for(let r of n){let o=i.get(r.normalized);i.set(r.normalized,o===void 0||o===r.path?r.path:null)}return r=>{let o=pn(r),s=i.get(o);if(s)return s;let a=n.filter(l=>l.normalized.endsWith(o));return a.length===1?a[0].path:null}}function MS(e){let t=[],n=null;for(let i of e.split(`
|
|
346
|
+
`)){if(i.startsWith("+++ ")){n=BB(i.slice(4).trim());continue}if(!n||!i.startsWith("@@ "))continue;let r=/@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(i);if(!r)continue;let o=Math.max(0,Number(r[1])-1),s=r[2]===void 0?1:Number(r[2]);t.push({file:n,startLine:o,endLine:Math.max(o,o+Math.max(s,1)-1)})}return t}function BB(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function $S(e){let t=new Set,n=[];for(let i of e){let r=`${i.file}:${i.startLine}:${i.endLine}`;t.has(r)||(t.add(r),n.push(i))}return n}function OB(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(i=>Uu(e.startLine,e.endLine,i.startLine,i.endLine))}function $B(e,t,n){let i=new Map,r=[],o=jS(e),s=GB(n);for(let a of t){let l=o.get(a.file)??[];if(l.some(d=>Uu(d.startLine,d.endLine,a.startLine,a.endLine)))continue;let c=s.get(a.file)??[],u=KB(c,a);if(u){let d=l.find(m=>m.startLine>=u.startLine&&m.startLine<=u.endLine);if(d){i.set(d.symbolId,d),r.push(ku(a,"ast-widened"));continue}}if(c.length===0){let d=[...l].filter(m=>m.startLine<=a.startLine).sort((m,f)=>f.startLine-m.startLine||m.endLine-f.endLine)[0];if(d){i.set(d.symbolId,d),r.push(ku(a,"nearest-preceding"));continue}}r.push(ku(a,"unattributed"))}return{definitions:[...i.values()],notes:r}}function jB(e,t,n,i){let r=jS(n),o=[],s=[],a=[...new Set(t.map(l=>l.relativePath))];for(let l of a){let c=i.get(l)??[];if(c.length===0)continue;let u=r.get(l)??[];for(let d of c)u.some(m=>Uu(m.startLine,m.endLine,d.startLine,d.endLine))||o.push(d);o.some(d=>d.file===l)&&s.push(...HB(e,l))}return $B(t,o,s)}function HB(e,t){let n=ae(e,t);return n?n.rootNode.namedChildren.filter(UB).map(i=>({file:t,startLine:i.startPosition.row,endLine:i.endPosition.row})).filter(i=>i.endLine>=i.startLine):[]}function UB(e){return e.endPosition.row<e.startPosition.row?!1:!new Set(["import_statement","comment"]).has(e.type)}function zB(e){let t=new Map;for(let n of e)t.set(n.symbolId,n);return[...t.values()]}function jS(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath)??[];i.push(n),t.set(n.relativePath,i)}return t}function GB(e){let t=new Map;for(let n of e){let i=t.get(n.file)??[];i.push(n),t.set(n.file,i)}return t}function KB(e,t){return e.filter(n=>n.startLine<=t.startLine&&n.endLine>=t.endLine).sort((n,i)=>n.endLine-n.startLine-(i.endLine-i.startLine))[0]}function ku(e,t){return{file:e.file,startLine:e.startLine,endLine:e.endLine,method:t}}function Uu(e,t,n,i){return e<=i&&n<=t}function qB(e,t,n,i,r,o,s,a,l){let c=Math.max(a,o.size,s.size);if(!QB(t,c))return;let u=k(t.symbol);i.push({symbol:t.symbol,shortName:u,file:t.relativePath,startLine:t.startLine,endLine:t.endLine,fanIn:c});for(let d of l)_u(e,n,r,d,u);for(let d of o)_u(e,n,r,d,u);for(let d of s)_u(e,n,r,d,u)}function AS(e,t,n){try{return{values:n(),status:{tier:e,state:"complete",attemptedSymbols:t}}}catch(i){return{values:new Map,status:{tier:e,state:"failed",attemptedSymbols:t,reason:VB(i)}}}}function WB(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"}),i=n.reduce((o,s)=>o+s.attemptedSymbols,0),r=[...new Set(n.filter(o=>o.state==="failed").map(o=>o.reason))];return r.length===0?{tier:t,state:"complete",attemptedSymbols:i}:{tier:t,state:"failed",attemptedSymbols:i,reason:r.join("; ").slice(0,500)}})}function HS(){return[{tier:"semantic-consumers",state:"complete",attemptedSymbols:0},{tier:"source-fallback-consumers",state:"complete",attemptedSymbols:0}]}function VB(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 JB(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
|
|
347
|
+
FROM mentions m
|
|
348
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
349
|
+
WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
|
|
350
|
+
AND m.role != 1
|
|
351
|
+
GROUP BY m.symbol_id`,...t);return new Map(n.map(i=>[i.symbol_id,i.fan_in]))}function YB(e,t,n){if(t.length===0||n.length===0)return new Map;let i=e.all(`SELECT DISTINCT m.symbol_id, ref_d.relative_path
|
|
352
|
+
FROM mentions m
|
|
353
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
354
|
+
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
355
|
+
WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
|
|
356
|
+
AND m.role != 1
|
|
357
|
+
AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
|
|
358
|
+
${e.pathExclusionsFor("ref_d")}`,...t,...n),r=new Map;for(let o of i){let s=r.get(o.symbol_id);s||(s=new Set,r.set(o.symbol_id,s)),s.add(o.relative_path)}return r}function _u(e,t,n,i,r){if(e.isIgnored(i)||t.has(i))return;let o=n.get(i);o||(o=new Set,n.set(i,o)),o.add(r)}function XB(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function ZB(e){return!(Le(e.symbol)||e.parentTypeName!==null&&!it(e.symbol))}function QB(e,t){return it(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}var eO=5;function tO(e,t={}){let{base:n="HEAD",minContainment:i=.7,minCallees:r=3,minSiteCoverage:o=.4,maxHelpers:s=Number.POSITIVE_INFINITY,limit:a=20,scanLimit:l}=t,c=t.semantic!==!1,u=t.diffPlan??ur(e,{base:n}),d={available:u.note!==Bu,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 U(e),f=new Set(u.changedFiles),p=new Map(u.renamedFiles.map(R=>[R.to,R.from]));if(t.baseContentAt&&t.baseContentResultAt)throw new Error("Specify only one of baseContentAt or baseContentResultAt.");let g=t.baseContentResultAt?t.baseContentResultAt:t.baseContentAt?lO(t.baseContentAt):Hu({projectRoot:e.config.projectRoot,base:n,preloadPaths:kS(u)}),h=aO(m,f,p,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 S=h.definitions.slice(0,s);h.definitions.length>s&&(d.note=`helper scoring capped at ${s} of ${h.definitions.length} new symbols`);let v=m.calleeEvidenceMap(S,{semantic:c}),y=S.filter(R=>!v.incompleteSymbolIds.has(R.symbolId)&&!v.unavailableSymbolIds.has(R.symbolId)).map(R=>({def:R,callees:Ea((v.rows.get(R.symbolId)??[]).map(C=>C.symbol))}));for(let R of S)!v.incompleteSymbolIds.has(R.symbolId)&&!v.unavailableSymbolIds.has(R.symbolId)||d.skipped.push({helperShortName:k(R.symbol),helperFile:R.relativePath,reason:"compiler-resolved callee evidence is incomplete or unavailable \u2014 unsafe to score"});let E=ar(e),w,b=()=>(w??=E.calleeIndex({minCallees:Math.min(3,r),scanLimit:l,semantic:c}),w);for(let{def:R,callees:C}of y){let L=k(R.symbol);if(C.size<r){d.skipped.push({helperShortName:L,helperFile:R.relativePath,reason:`fewer than ${r} meaningful callees \u2014 too small to score`});continue}let I=b(),x=sO(C,I);if(x===0){d.skipped.push({helperShortName:L,helperFile:R.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let P=cO(e,R.symbolId);if(P.length===0){d.skipped.push({helperShortName:L,helperFile:R.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}d.helpersChecked+=1;let _=nO({candidateIndex:I,changed:f,helperCallees:C,helperFile:R.relativePath,helperSymbol:R.symbol,minContainment:i,minSiteCoverage:o,migratedFiles:P});_.length!==0&&(_.sort((D,T)=>US(T.migrationScope)-US(D.migrationScope)||T.containment-D.containment||T.siteCoverage-D.siteCoverage||D.file.localeCompare(T.file)),d.findings.push({helperSymbol:R.symbol,helperShortName:L,helperFile:R.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:C.size,specificHelperCalleeCount:x,migratedFiles:P.sort(),leftovers:_.slice(0,eO)}))}return d.findings.sort((R,C)=>(C.leftovers[0]?.containment??0)-(R.leftovers[0]?.containment??0)||R.helperFile.localeCompare(C.helperFile)),d.findings=d.findings.slice(0,a),d}function nO(e){let t=[],n=iO(e.helperSymbol,e.helperFile,e.migratedFiles),i=new Set;for(let r of e.helperCallees)for(let o of e.candidateIndex.candidateIndexesByCallee.get(r)??[])i.add(o);for(let r of i){let o=e.candidateIndex.corpus[r];if(o.symbol===e.helperSymbol||e.changed.has(o.file)||o.callees.has(e.helperSymbol))continue;let s=kb(e.helperCallees,o.callees);if(s<e.minContainment)continue;let a=[...e.helperCallees].filter(u=>o.callees.has(u)),l=o.callees.size===0?0:a.length/o.callees.size;if(l<e.minSiteCoverage||!a.some(u=>(e.candidateIndex.docFreq.get(u)??0)<=e.candidateIndex.ubiquityThreshold))continue;let c=rO(n,o.symbol,o.file);t.push({symbol:o.symbol,shortName:k(o.symbol),file:o.file,...c,containment:s,siteCoverage:l,uniqueSiteCalleeCount:Math.max(0,o.callees.size-a.length),sharedCallees:a.map(k).sort()})}return t}function US(e){return e==="same-scope"?2:e==="unknown"?1:0}function iO(e,t,n){let i=new Set([...zu(t),...Gu(re(e))]);for(let r of n)for(let o of zu(r))i.add(o);return i}function rO(e,t,n){let i=new Set([...zu(n),...Gu(re(t))]);if(e.size===0||i.size===0)return{migrationScope:"unknown",migrationScopeReasons:["insufficient path/name tokens to infer migration scope"]};let r=[...i].filter(o=>e.has(o)).sort();return r.length>0?{migrationScope:"same-scope",migrationScopeReasons:[`shares migration-scope token(s): ${r.slice(0,5).join(", ")}`]}:{migrationScope:"possible-subtype",migrationScopeReasons:["no path/name tokens shared with the helper or already migrated files"]}}var oO=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 zu(e){return Gu(e.replace(/\.[^.]+$/,""))}function Gu(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!oO.has(t))}function sO(e,t){let n=0;for(let i of e)(t.docFreq.get(i)??0)<=t.ubiquityThreshold&&(n+=1);return n}function aO(e,t,n,i){let r=[];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=i(s);if(a.state==="unavailable")return{definitions:[],unavailable:a};(a.state==="absent"||!new RegExp(`\\b${He(o.leaf)}\\b`).test(a.content))&&r.push(o)}return{definitions:r}}function lO(e){return t=>{let n=e(t);return n===null?{state:"absent"}:{state:"present",content:n}}}function cO(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
|
|
359
|
+
FROM mentions m
|
|
360
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
361
|
+
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
362
|
+
WHERE m.symbol_id = ?
|
|
363
|
+
AND m.role != 1
|
|
364
|
+
${e.pathExclusionsFor("ref_d")}`,t).map(i=>i.relative_path)}import{execFileSync as uO}from"child_process";var WS=2e3,Ma=50,dO=64,mO=8,fO=3,pO=2160*60*60,gO=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,hO=3,yO=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,bO=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function SO(e){let t=Fe(e,{clearGroups:["whole-project"]});return(n,i,r)=>{let o=r??Ku(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:i(n.config.projectRoot,o)})).value)}}function Aa(e){let t=Fe(e,{clearGroups:["whole-project"]});return(n,i,r,o)=>{let s=o??Ku(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 l=t.get(n,()=>({head:s,values:new Map}));if(l.values.has(i))return l.values.get(i)??null;let c=r(n.config.projectRoot,s);return l.values.set(i,c),c}}var vO=Aa("git-commit-history");function Wt(e,t={}){let n=t.historyMode??"bounded",i=t.head;return{capability:r=>CO(e,r,i),commitHistory:()=>Eo(e,n,i),fileChurn:()=>EO(e,n,i),changeAmplification:()=>wO(e,n,i),trackedFiles:()=>LO(e,i),fileAddRecords:()=>PO(e,n,i),coChangePairs:(r={})=>_O(e,r,n,i),coChangePairsForFiles:(r,o={})=>YS(e,r,o,n,i),directionalCoChangePairsForFiles:(r,o={})=>BO(e,r,o,n,i)}}function Eo(e,t="bounded",n){return vO(e,dr(t),(i,r)=>xO(i,r,t),n)}function CO(e,t,n){let i=n??Ku(e.config.projectRoot);return i?{slot:t,available:!0,head:i}:{slot:t,available:!1,head:null,reason:"git history is unavailable for this project"}}function Ku(e){try{return dn(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function dn(e,t){return uO("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:3e4,killSignal:"SIGKILL"})}function xO(e,t,n){let i;try{i=dn(e,["log","--no-merges","--name-only",...Na(n),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}return{head:t,...Vu(i,Ma)}}function RO(e){return gO.test(e.subject)}function EO(e,t,n){let i=Eo(e,t,n);if(!i)return null;let r=new Map;for(let o of i.commits){let s=RO(o);for(let a of o.files){let l=r.get(a)??{changes:0,fixChanges:0,lastChangedAt:0};l.changes+=1,s&&(l.fixChanges+=1),o.timestamp>l.lastChangedAt&&(l.lastChangedAt=o.timestamp),r.set(a,l)}}return r}function wO(e,t,n){let i=Eo(e,t,n);if(!i||i.commits.length===0)return null;let r=i.commits.map(o=>o.files.length).filter(o=>o>0).sort((o,s)=>o-s);return r.length===0?null:{medianFilesPerCommit:zS(r,.5),p90FilesPerCommit:zS(r,.9),commitsAnalyzed:r.length}}function zS(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var IO=SO("git-tracked-files");function LO(e,t){return IO(e,n=>{try{let i=dn(n,["ls-files"]);return new Set(i.split(`
|
|
365
|
+
`).map(r=>r.trim()).filter(r=>r!==""))}catch{return null}},t)}var DO=Aa("git-file-adds"),GS="__git__/file-adds",KS=vt({kind:"git-file-adds",invalidation:Je("git-file-adds"),serialize:FO,deserialize:MO});function VS(e){return Wt(e).fileAddRecords()}function PO(e,t,n){let i=dr(t);return DO(e,i,(r,o)=>TO(e,r,o,t),n)}function TO(e,t,n,i){let r=KS.read(e,qS(i),n);if(r)return r;let o=AO(t,i);return o&&KS.write(e,qS(i),n,o),o}function FO(e){return JSON.stringify([...e.entries()])}function MO(e){if(!e)return null;try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=new Map;for(let i of t){if(!Array.isArray(i)||i.length!==2||typeof i[0]!="string")return null;let r=i[1];if(!r||typeof r.commitsAgo!="number"||!Number.isFinite(r.commitsAgo)||typeof r.addedAt!="number"||!Number.isFinite(r.addedAt))return null;n.set(i[0],{commitsAgo:r.commitsAgo,addedAt:r.addedAt})}return n}catch{return null}}function AO(e,t){let n;try{n=dn(e,["log","--no-merges","--find-renames","--name-status",...Na(t),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let i=new Map,r=new Map,o=-1;for(let s of n.split("")){if(s.trim()==="")continue;o+=1;let a=s.indexOf(`
|
|
366
|
+
`),l=a>=0?s.slice(0,a):s,[,c]=l.split("\0"),u=Number(c)||0;if(!(a<0))for(let d of s.slice(a+1).split(`
|
|
367
|
+
`)){let m=NO(d);if(!m)continue;if(m.status==="R"&&m.from&&m.to){let p=r.get(m.to)??new Set([m.to]);r.set(m.from,p);continue}if(m.status!=="A"||!m.to)continue;let f={commitsAgo:o,addedAt:u};i.set(m.to,f);for(let p of r.get(m.to)??[])i.set(p,f)}}return i}function NO(e){let t=e.trim().split(" "),n=t[0]??"";if(!n)return null;let i=n[0]??"";if(i==="R"){let o=t[1],s=t[2];return o&&s?{status:i,from:o,to:s}:null}let r=t[1];return r?{status:i,to:r}:null}var JS=Aa("git-co-change-pairs"),kO=Aa("git-directional-co-change-pairs");function _O(e,t,n,i){let r=`all\0${dr(n)}\0${qu(t)}`,o=JS(e,r,()=>{let s=Eo(e,n,i);return s?Wu(s,t):null},i);return o&&[...o]}function YS(e,t,n,i,r){if(t.size===0)return[];let o=`files\0${dr(i)}\0${XS(t)}\0${qu(n)}`,s=JS(e,o,()=>{let a=Eo(e,i,r);return a?Wu(a,n,t):null},r);return s&&[...s]}function BO(e,t,n,i,r){if(t.size===0)return[];let o=n.maxFilesPerCommit??Ma;if(t.size>dO)return YS(e,t,n,i,r);let s=`directional\0${dr(i)}\0${XS(t)}\0${qu({...n,maxFilesPerCommit:o})}`,a=kO(e,s,(l,c)=>{let u=OO(l,c,t,o,i);return u?Wu(u,n,t):null},r);return a&&[...a]}function qu(e){let t=e.minTogether??4,n=e.minConfidence??.6,i=e.maxFilesPerCommit??Ma;return`${t}\0${n}\0${i}`}function XS(e){return[...e].sort().join("\0")}function Wu(e,t,n){let{minTogether:i=4,minConfidence:r=.6,maxFilesPerCommit:o=Ma}=t,s=new Map,a=new Map,l=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>l&&(l=d.timestamp);let f=HO(m),p=n===void 0||m.some(g=>n.has(g));for(let g of m)s.set(g,(s.get(g)??0)+1);if(p)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 S=`${m[g]}\0${m[h]}`,v=a.get(S)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};v.together+=1,f?v.broadTogether+=1:v.focusedTogether+=1,d.timestamp>v.lastTogetherAt&&(v.lastTogetherAt=d.timestamp),v.timestamps.push(d.timestamp),v.subjects.push(d.subject),a.set(S,v)}}let c=[],u=l-pO;for(let[d,m]of a){let f=m.together;if(f<i)continue;let[p,g]=d.split("\0"),h=s.get(p)??f,S=s.get(g)??f,v=Math.max(f/h,f/S);if(v<r)continue;let y=m.broadTogether/f,E=m.timestamps.filter(w=>w>=u).length;c.push({fileA:p,fileB:g,together:f,confidence:v,changesA:h,changesB:S,focusedTogether:m.focusedTogether,broadTogether:m.broadTogether,broadCommitRatio:y,lastTogetherAt:m.lastTogetherAt,recentTogether:E,commitScope:zO(m.broadTogether,f),recency:E>0?"recent":"stale",subjectContext:GO(m.subjects)})}return c.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),c}function OO(e,t,n,i,r){let o;try{o=$O(e,r)}catch{return null}if(o.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:0};let s;try{s=dn(e,["log","--no-merges","--format=%H",...Na(r),"--",...[...n].sort()])}catch{return null}let a=new Set(o.map(m=>m.hash)),l=s.split(`
|
|
368
|
+
`).map(m=>m.trim()).filter(m=>m!==""&&a.has(m)),c=jO(e,o,i);if(l.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:c};let u;try{u=dn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...l])}catch{return null}let d=Vu(u,i);return{head:t,...d,newestAnalyzedAt:c}}function $O(e,t){return dn(e,["log","--no-merges","--format=%H%x00%ct",...Na(t)]).split(`
|
|
369
|
+
`).map(i=>i.trim()).filter(i=>i!=="").map(i=>{let[r,o]=i.split("\0");return{hash:r??"",timestamp:Number(o)||0}}).filter(i=>i.hash!=="")}function Na(e){return e==="full"?[]:["-n",String(ZS())]}function ZS(){return is(process.env.CODEBASEIQ_GIT_HISTORY_MAX_COMMITS)??WS}function dr(e){return e==="full"?"full":`bounded:${ZS()}`}function qS(e){let t=dr(e);return t===`bounded:${WS}`?GS:`${GS}:${t}`}function jO(e,t,n){for(let r=0;r<t.length;r+=20){let o=t.slice(r,r+20),s;try{s=dn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...o.map(l=>l.hash)])}catch{return t[0]?.timestamp??0}let a=Vu(s,n);if(a.commits.length>0)return a.commits[0].timestamp}return 0}function Vu(e,t){let n=[],i=0;for(let r of e.split("")){if(r.trim()==="")continue;let o=r.indexOf(`
|
|
370
|
+
`),s=o>=0?r.slice(0,o):r,[a,l,c]=s.split("\0");if(!a||!l)continue;let u=o>=0?r.slice(o+1).split(`
|
|
371
|
+
`).map(d=>d.trim()).filter(d=>d!==""):[];if(u.length>t){i+=1;continue}n.push({hash:a,timestamp:Number(l)||0,subject:c??"",files:u})}return{commits:n,skippedBulkCommits:i}}function HO(e){return e.length>=mO?!0:UO(e).size>=fO}function UO(e){let t=new Set;for(let n of e){let i=n.indexOf("/");t.add(i>=0?n.slice(0,i):".")}return t}function zO(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function GO(e){let t=new Set,n=[],i=[];for(let r of e){!i.includes(r)&&i.length<hO&&i.push(r);for(let o of KO(r))t.add(o);for(let o of r.match(yO)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:i,externalIssueLabelStatus:"unavailable"}}function KO(e){let t=new Set,n=bO.exec(e)?.[1]?.toLowerCase();return n&&t.add(qO(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 qO(e){return e==="feat"?"feature":e}var QS=/(?:^|\/)(?: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 wo(e,t,n={}){let{minTogether:i=4,minConfidence:r=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=Wt(e,{historyMode:n.historyMode,...n.head?{head:n.head}:{}}),l=a.commitHistory(),c=t!==void 0,u=a.coChangePairs({minTogether:c?Math.min(i,2):i,minConfidence:c?0:r,maxFilesPerCommit:s});if(!l||!u)return{available:!1,commitsAnalyzed:0,findings:[]};let d=typeof n.scanLimit=="number"?u.slice(0,n.scanLimit):u,m=Be(e),f=rv(e),p=JO(e,m,f),g=n.includeLinked===!0||c,h=[];for(let S of d){if(QS.test(S.fileA)||QS.test(S.fileB)||!ev(e,S.fileA)||!ev(e,S.fileB)||c&&!S.fileA.includes(t)&&!S.fileB.includes(t)||!c&&(V(S.fileA)==="test"||V(S.fileB)==="test"||QO(S.fileA,S.fileB)||XO(S.fileA,S.fileB)))continue;let v=p(S.fileA,S.fileB);if(!g&&v)continue;let y=WO(S.fileA,S.fileB),E=VO(S,y,v);if(h.push({...S,structurallyLinked:v,partnerClass:y.partnerClass,partnerClassReasons:y.reasons,...E?{declaredCouplingSuggestion:E}:{}}),h.length>=o)break}return{available:!0,commitsAnalyzed:l.commits.length,findings:h}}function ev(e,t){return Tt(e.config.projectRoot,t)}function WO(e,t){let n=nv(e),i=nv(t),r=[],o=l=>{r.includes(l)||r.push(l)},s=(l,c)=>n.tags.has(l)&&i.tags.has(c)||n.tags.has(c)&&i.tags.has(l);if(s("doc","code"))return o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:r};if(n.tags.has("test")||i.tags.has("test"))return o("one side is classified as a test file"),{partnerClass:"test-code",reasons:r};if(s("schema","script"))return o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:r};if(s("model","view"))return o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:r};if(s("config","code"))return o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:r};let a=u$(n.tokens,i.tokens).filter(l=>!l$.has(l));return iv(e,t)||a.length>=2?(o(iv(e,t)?"both files live in the same directory":`files share feature tokens: ${a.slice(0,4).join(", ")}`),{partnerClass:"same-feature",reasons:r}):(o("no specific relationship pattern matched"),{partnerClass:"unknown",reasons:r})}function VO(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!a$.has(t.partnerClass))return;let i=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${d$(i)}`,files:i,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 JO(e,t=Be(e),n=rv(e)){return(i,r)=>e$(t,n,i,r)}var YO=/(?:^|\/)(?:locales|i18n)\//i;function tv(e){return YO.test(e)}function XO(e,t){return tv(e)&&tv(t)?!0:ZO(e,t)}function ZO(e,t){if(!e.endsWith(".json")||!t.endsWith(".json"))return!1;let n=e.lastIndexOf("/"),i=t.lastIndexOf("/");if(n<0||i<0)return!1;let r=e.slice(0,n),o=t.slice(0,i);if(r===o)return!1;let s=e.slice(n+1),a=t.slice(i+1);if(s!==a)return!1;let l=r.lastIndexOf("/"),c=o.lastIndexOf("/"),u=l>=0?r.slice(0,l):"",d=c>=0?o.slice(0,c):"";return u===d}function QO(e,t){let n=e.lastIndexOf("/"),i=t.lastIndexOf("/");if(e.slice(0,n)!==t.slice(0,i))return!1;let r=e.slice(n+1).split(".")[0],o=t.slice(i+1).split(".")[0];return r!==""&&r===o}function rv(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function e$(e,t,n,i){return e.get(n)?.has(i)===!0||e.get(i)?.has(n)===!0?!0:t.some(r=>r.has(n)&&r.has(i))}var t$=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,n$=/(?:^|\/)(?:\.[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,i$=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,r$=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,o$=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,s$=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,a$=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),l$=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 nv(e){let t=e.replace(/\\/g,"/"),n=new Set;return t$.test(t)&&n.add("doc"),n$.test(t)&&n.add("config"),i$.test(t)&&n.add("schema"),r$.test(t)&&n.add("script"),o$.test(t)&&n.add("model"),s$.test(t)&&n.add("view"),V(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:c$(t)}}function iv(e,t){let n=e.lastIndexOf("/"),i=t.lastIndexOf("/"),r=n>=0?e.slice(0,n):"",o=i>=0?t.slice(0,i):"";return r!==""&&r===o}function c$(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 u$(e,t){let n=new Set(t);return[...new Set(e.filter(i=>n.has(i)))].sort()}function d$(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}function Ba(e,t){let n=m$(e,t)??f$(e,t)??p$(e,t)??g$(e,t);return h$(e,n,t)}function m$(e,t){let n=-1,i=null;for(let r=0;r<=t;r+=1){let o=Ju(e[r]??"");o&&(i===null?(i=o,n=r):o===i&&(i=null,n=-1))}if(i===null||n<0)return null;for(let r=t+1;r<e.length;r+=1)if(Ju(e[r]??"")===i)return{start:n,end:r+1};return{start:n,end:e.length}}function Ju(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function f$(e,t){if(!ka(e[t]??""))return null;let n=t;for(;n>0&&ka(e[n-1]??"");)n-=1;let i=t+1;for(;i<e.length&&ka(e[i]??"");)i+=1;return{start:n,end:i}}function ka(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function p$(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if(_a(o)!==null)break;if(Yu(o)!==null)return null;n-=1}if(n<0)return null;let i=_a(e[n]??"");if(i===null)return null;let r=n+1;for(;r<e.length;){let o=e[r]??"",s=_a(o);if(s!==null){if(s<=i)break;r+=1;continue}if(Yu(o)!==null)break;r+=1}return{start:n,end:r}}function _a(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function g$(e,t){let n=e[t]??"";if(sv(n)||n.trim().length===0)return{start:t,end:t+1};let i=t;for(;i>0&&ov(e[i-1]??"");)i-=1;let r=t+1;for(;r<e.length&&ov(e[r]??"");)r+=1;return{start:i,end:r}}function ov(e){return Yu(e)===null}function Yu(e){return e.trim().length===0?"blank":sv(e)?"heading":Ju(e)?"fence":ka(e)?"table":_a(e)!==null?"list":null}function sv(e){return/^#{1,6}\s+/.test(e.trim())}function h$(e,t,n){let{start:i,end:r}=t;if(r-i>40){let s=Math.floor(20);i=Math.max(i,n-s),r=Math.min(r,i+40),i=Math.max(t.start,r-40)}let o=e.slice(i,r).join(`
|
|
372
|
+
`).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function Li(e,t){return t.filter(n=>e.includes(n))}var y$=/<!--\s*codebaseiq:\s*snapshot\s*-->/i;function av(e,t){if((e.config.docs?.snapshotPaths??[]).some(r=>Jn(r,t)))return!0;let i=se(e,t);return i.length>0&&y$.test(i)}var lv={classifyCitation:S$,citationContexts:v$,citationKindLabel:x$,citationRemediation:R$,referenceTargets:E$,hasLineAnchoredCitation:b$};function b$(e){return e.some(t=>(t.lineReferences?.length??0)>0)}function S$(e){let t=e.join(`
|
|
373
|
+
`).toLowerCase(),n=[],i=Li(t,[".codebaseiq","declaredcouplings","suppression","suppressions","config","configuration","json"]);if(i.length>0)return n.push(`configuration/example terms near citation: ${i.join(", ")}`),{citationKind:"configuration-example",actionTier:"support",reasons:n};let r=Li(t,["accepted","intentional","intentionally","retained","historical"]);if(r.length>0)return n.push(`intentional-record terms near citation: ${r.join(", ")}`),{citationKind:"intentional-record",actionTier:"support",reasons:n};let o=Li(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 v$(e,t,n){let i=se(e,t);if(!i&&!Tt(e.config.projectRoot,t))return[];let r=i.split(/\r?\n/),o=n.flatMap(C$),s=[];for(let a=0;a<r.length;a+=1){let l=r[a]??"";o.some(c=>l.includes(c))&&s.push(Ba(r,a))}return s}function C$(e){let t=e.split("/");return[e,`./${e}`,t.slice(-3).join("/"),t.slice(-2).join("/")].filter((n,i,r)=>n.length>0&&r.indexOf(n)===i)}function x$(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 R$(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 E$(e,t,n){let i=Pa(n),r=new Set;for(let o of t)w$(e,o,i.get(o)??[])&&r.add(o);return r}function w$(e,t,n){if(!I$.test(t)||!Tt(e.config.projectRoot,t))return!0;if(n.length===0)return!1;let i=nt(e.config.projectRoot,t,{inputKind:"changed source file"}).split(/\r?\n/),r=L$(i);for(let o of n)for(let s=o.startLine;s<=o.endLine;s+=1)if((i[s]??"").trim()!==""&&!r.has(s))return!0;return!1}var I$=/\.(?:[cm]?[jt]sx?)$/i;function L$(e){let t=new Set,n=!1;for(let i=0;i<e.length;i+=1){let r=e[i].trim();!n&&D$(r)&&(n=!0),n&&(t.add(i),r.endsWith(";")&&(n=!1))}return t}function D$(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}var cv=vt({kind:"doc-path-evidence",invalidation:Je("doc-path-evidence"),serialize:U$,deserialize:z$}),Io=/\.(?:md|mdx|rst|txt)$/i;function P$(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var T$=3,F$=/([A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6})(?::([1-9][0-9]*))?\b/g;function M$(e,t={}){let{doc:n,limit:i=20,minCoupling:r=T$,includeSnapshotExcluded:o=!1}=t,s=_$(e,t.historyMode??"bounded");if(!s)return{available:!1,commitsAnalyzed:0,docsScanned:0,findings:[]};let a=[];for(let l of s.docFiles){if(n!==void 0&&!l.includes(n)||n===void 0&&!B$(e,l)||n!==void 0&&!Tt(e.config.projectRoot,l))continue;let c=av(e,l);if(c&&!o)continue;let{value:u,estimated:d}=A$(e,l,s.changeTimes.get(l)),m=N$(e,l),f=new Map,{resolved:p,broken:g,citations:h}=$$(e,l,s.tracked,s.trackedBySuffix,s.everSeenInHistory),S=new Map(h.map(y=>[y.file,y]));for(let y of p){if(y===l||Io.test(y))continue;let E=(s.changeTimes.get(y)??[]).filter(b=>b>u).length;if(E===0)continue;let w=S.get(y);f.set(y,{file:y,evidence:"reference",coChanges:0,changesSinceDocUpdate:E,...Xu("reference",m,w?.contexts),citationContexts:w?.contexts,citedLines:w?.lineReferences})}for(let[y,E]of s.coupling.get(l)??[]){if(E<r||!s.tracked.has(y))continue;let w=(s.changeTimes.get(y)??[]).filter(R=>R>u).length;if(w===0)continue;let b=f.get(y);b?(b.evidence="both",b.coChanges=E,Object.assign(b,Xu("both",m,b.citationContexts))):f.set(y,{file:y,evidence:"co-change",coChanges:E,changesSinceDocUpdate:w,...Xu("co-change",m)})}if(f.size===0&&g.length===0)continue;let v=[...f.values()].sort((y,E)=>E.changesSinceDocUpdate-y.changesSinceDocUpdate);a.push({doc:l,docLastChangedAt:u,staleness:v.reduce((y,E)=>y+E.changesSinceDocUpdate,0)+g.length*10,subjects:v.slice(0,8),brokenReferences:g,...c?{snapshotExcluded:!0}:{},...d?{docLastChangedAtEstimated:!0}:{}})}return a.sort((l,c)=>c.staleness-l.staleness),{available:!0,commitsAnalyzed:s.historyCommitCount,docsScanned:s.docFiles.length,findings:a.slice(0,i)}}function A$(e,t,n){if(n&&n.length>0)return{value:Math.max(...n),estimated:!1};try{return{value:Math.floor(Qd(e.config.projectRoot,t).mtimeMs/1e3),estimated:!0}}catch(i){if(Tt(e.config.projectRoot,t))throw i;return{value:0,estimated:!1}}}function N$(e,t){let n=se(e,t).slice(0,6e3);if(!n)return{docIntent:"unknown",reasons:["doc text unavailable"]};let i=`${t}
|
|
374
|
+
${n}`.toLowerCase(),r=Li(i,["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(r.length>0)return{docIntent:"historical-note",reasons:[`historical-note terms: ${r.join(", ")}`]};let o=Li(i,["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 Xu(e,t,n=[]){let i=e==="co-change"||n.length===0?null:lv.classifyCitation(n);return{actionTier:k$(e,t.docIntent,i?.actionTier),docIntent:t.docIntent,docIntentReasons:t.reasons,...i?{citationKind:i.citationKind,citationKindReasons:i.reasons}:{}}}function k$(e,t,n){return t==="historical-note"?"support":n||(e==="co-change"?"signal":"direct")}function _$(e,t){let n=Wt(e,{historyMode:t}),i=n.commitHistory();if(!i)return null;let r=n.trackedFiles()??new Set,o=new Map,s=new Map,a=new Set;for(let l of i.commits){let c=[...new Set(l.files)],u=c.filter(m=>Io.test(m)),d=c.filter(m=>!Io.test(m));for(let m of c){a.add(m);let f=o.get(m)??[];f.push(l.timestamp),o.set(m,f)}for(let m of u){let f=s.get(m);f||(f=new Map,s.set(m,f));for(let p of d)f.set(p,(f.get(p)??0)+1)}}return{changeTimes:o,coupling:s,docFiles:[...r].filter(l=>Io.test(l)),everSeenInHistory:a,historyCommitCount:i.commits.length,tracked:r,trackedBySuffix:O$(r)}}function B$(e,t){return Io.test(t)&&!P$(t)&&Tt(e.config.projectRoot,t)}function O$(e){let t=new Map;for(let n of e){let i=n.split("/");for(let r of[2,3]){if(i.length<r)continue;let o=i.slice(-r).join("/"),s=t.get(o)??[];s.push(n),t.set(o,s)}}return t}function $$(e,t,n,i,r){let o=new Set,s=new Set,a=j$(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let l=a.candidates,c=a.contextsByCandidate,u=a.lineReferencesByCandidate,d=new Map,m=new Map,f=(p,g)=>{let h=c.get(g);if(h&&h.length>0){let v=d.get(p)??[];v.push(...h),d.set(p,uv(v).slice(0,3))}let S=u.get(g);S&&S.length>0&&m.set(p,Zu([...m.get(p)??[],...S]))};for(let p of l){if(n.has(p)){o.add(p),f(p,p);continue}let g=i.get(p);if(g&&g.length===1){o.add(g[0]),f(g[0],p);continue}g&&g.length>1||r.has(p)&&s.add(p)}return{resolved:o,broken:[...s],citations:[...d].map(([p,g])=>({file:p,contexts:g,lineReferences:m.get(p)}))}}function j$(e,t,n){let i=n;if(i===void 0&&(i=se(e,t),!i&&!Tt(e.config.projectRoot,t)))return null;let r=Ft(e,t,i),o=cv.read(e,t,r);if(o)return o;let s=H$(i);return cv.write(e,t,r,s),s}function H$(e){let t=e.split(/\r?\n/),n=new Set,i=new Map,r=new Map;for(let o=0;o<t.length;o+=1){let s=t[o]??"";for(let a of s.matchAll(F$)){let l=(a[1]??"").replace(/^\.?\//,"");if(l.length===0)continue;n.add(l);let c=a[2]?Number(a[2]):null;c!==null&&Number.isSafeInteger(c)&&r.set(l,Zu([...r.get(l)??[],c]));let u=Ba(t,o);if(u.length===0)continue;let d=i.get(l)??[];d.push(u),i.set(l,uv(d).slice(0,3))}}return{candidates:[...n],contextsByCandidate:i,lineReferencesByCandidate:r}}function U$(e){let t={candidates:e.candidates,contextsByCandidate:[...e.contextsByCandidate.entries()],lineReferencesByCandidate:[...e.lineReferencesByCandidate.entries()]};return JSON.stringify(t)}function z$(e){try{let t=JSON.parse(e);if(!am(t))return null;let n=fl(t.candidates),i=K$(t.contextsByCandidate),r=G$(t.lineReferencesByCandidate);return!n||!i?null:{candidates:n,contextsByCandidate:new Map(i),lineReferencesByCandidate:new Map(r??[])}}catch{return null}}function G$(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 i=[];for(let r of n[1]){if(typeof r!="number"||!Number.isSafeInteger(r))return null;i.push(r)}t.push([n[0],Zu(i)])}return t}function K$(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 i=fl(n[1]);if(!i)return null;t.push([n[0],i])}return t}function uv(e){let t=[];for(let n of new Set(e))t.some(i=>q$(i,n))||t.push(n);return t}function Zu(e){return[...new Set(e)].sort((t,n)=>t-n)}function q$(e,t){if(e===t)return!0;let n=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),i=t.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),r=Math.min(n.length,i.length);if(r===0)return!1;if(r<3)return e.includes(t)||t.includes(e);let o=new Set(i),s=n.filter(a=>o.has(a)).length;return s>=3&&s/r>=.6}import{createHash as W$}from"crypto";var V$=3;function Lo(e,t={}){let{scope:n,maxLoc:i=15,minLoc:r=V$,limit:o,scanLimit:s}=t,a=VS(e),l=J$(e,{scope:n,maxLoc:i,scanLimit:s}).map(u=>Y$(e,u,a,r)).filter(u=>u!==null),c=fv(l);return o?c.slice(0,o):c}function mv(e){let t=mn(e);return hn(t).replace(/\s+/g,"")}function fv(e){let t=new Map;for(let i of e){if(i.normalizedBody.length<8)continue;let r=Z$(i.normalizedBody),o=t.get(r)??[];o.push(i),t.set(r,o)}let n=[];for(let[i,r]of t){let o=new Set(r.map(a=>a.file));if(r.length<2||o.size<2)continue;let s=[...r].sort(Q$).map(({normalizedBody:a,...l})=>l);n.push({hash:i,canonical:s[0],functions:s})}return n.sort((i,r)=>{let o=r.functions.length-i.functions.length;if(o!==0)return o;let s=dv(r)-dv(i);return s!==0?s:i.canonical.file.localeCompare(r.canonical.file)}),n}function J$(e,t){let n=ze(e,{scope:t.scope}).filter(i=>i.isFunctionLike&&!e.isIgnored(i.relativePath)).filter(i=>!Wo(e,i.relativePath,i.startLine,"similar")).filter(i=>de(i)<=t.maxLoc);return n.sort((i,r)=>de(r)-de(i)||i.relativePath.localeCompare(r.relativePath)),Ae(n,t.scanLimit)}function Y$(e,t,n,i){let r=Vt(e,t);if(!r||X$(r)<i)return null;let o=Qu(e,t);return o?{symbol:t.symbol,shortName:k(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:de(t),ageCommits:n?.get(t.relativePath)?.commitsAgo??null,normalizedBody:o}:null}function Qu(e,t){let n=Vt(e,t);return n&&mv(n)||null}function Vt(e,t){let n=ie(e,t.relativePath);return n.length===0?null:n.slice(t.startLine,t.endLine+1).join(`
|
|
375
|
+
`)}function mn(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(t>=0&&n>t)return e.slice(t+1,n);let i=e.indexOf("=>");return i>=0?e.slice(i+2).replace(/;+\s*$/,""):e}function X$(e){return mn(e).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0).length}function Z$(e){return W$("sha256").update(e).digest("hex").slice(0,16)}function Q$(e,t){let n=e.ageCommits??-1;return(t.ageCommits??-1)-n||e.file.localeCompare(t.file)||e.startLine-t.startLine}function dv(e){return e.functions.reduce((t,n)=>t+n.loc,0)}var e1=new Set(Zt());function t1(e,t={}){let{includeHomonyms:n=!1,limit:i}=t,r=Oa(e,t).filter(o=>o.relationship==="divergent"||n&&o.relationship==="homonym");return i?r.slice(0,i):r}function Oa(e,t={}){let{scope:n,minSimilarity:i=.3,scanLimit:r}=t,o=r1(e,{scope:n,scanLimit:r});return hv(o,{minSimilarity:i,isDelegatePair:I1(e)}).filter(s=>!s.members.some(a=>Wo(e,a.file,a.startLine,"twin")))}function hv(e,t={}){let n=t.minSimilarity??.3,i=t.isDelegatePair,r=e.filter(c=>!Rv(c.leaf)&&!g1(c.leaf)&&V(c.file)!=="test"&&!at(c.symbol)&&!bv(c.symbol)&&!Sv(c.symbol,c.leaf)),{recordsByLeaf:o,recordOrder:s}=$("twin-drift.group-by-leaf",()=>n1(r),()=>({records:r.length})),a=$("twin-drift.cluster-leaf-names",()=>yv([...o.keys()]),()=>({leaves:o.size}));return $("twin-drift.compare-clusters",()=>{let c=[];for(let u of a){let d=i1(u,o,s);if(d.length<2||new Set(d.map(v=>v.file)).size<2)continue;let m=null,f=!1,p=!1,g=new Set;for(let v=0;v<d.length;v+=1)for(let y=v+1;y<d.length;y+=1){let E=d[v],w=d[y];if(E.file===w.file||!S1(E,w)||i?.(E,w,d)||i?.(w,E,d))continue;if(f=!0,g.add(E.symbol),g.add(w.symbol),E.normalizedBody===w.normalizedBody){p=!0;continue}let b=d1(E.tokens,w.tokens);(!m||b>m.similarity)&&(m={a:E,b:w,similarity:b})}if(!f)continue;let h=d.filter(v=>g.has(v.symbol)).sort((v,y)=>v.file.localeCompare(y.file)||v.startLine-y.startLine).map(u1);if(!m){c.push({leaf:gv(u),relationship:p?"identical":"homonym",maxDivergence:0,members:h});continue}let S=m.similarity>=n?"divergent":"homonym";c.push({leaf:gv(u),relationship:S,maxDivergence:Math.round((1-m.similarity)*1e3)/1e3,members:h,...S==="divergent"?{firstDivergentTokens:m1(m.a.tokens,m.b.tokens)}:{}})}return c},()=>({clusters:a.length,records:r.length})).sort((c,u)=>u.members.length-c.members.length||u.maxDivergence-c.maxDivergence||c.leaf.localeCompare(u.leaf))}function n1(e){let t=new Map,n=new Map;for(let[i,r]of e.entries()){let o=t.get(r.leaf)??[];o.push(r),t.set(r.leaf,o),n.set(r,i)}return{recordsByLeaf:t,recordOrder:n}}function i1(e,t,n){let i=[...e].flatMap(r=>t.get(r)??[]);return e.size>1&&i.sort((r,o)=>(n.get(r)??0)-(n.get(o)??0)),i}function r1(e,t){let n=$("twin-drift.load-definitions",()=>ze(e,{scope:t.scope}).filter(o=>o1(o)&&!e.isIgnored(o.relativePath)).filter(o=>!Ki(o.relativePath)));$("twin-drift.sort-definitions",()=>n.sort((o,s)=>o.relativePath.localeCompare(s.relativePath)||o.startLine-s.startLine),()=>({definitions:n.length}));let i=Ae(n,t.scanLimit),r=$("twin-drift.select-candidates",()=>s1(i),()=>({scanned:i.length}));return $("twin-drift.build-records",()=>{let o=[];for(let s of r){let a=a1(e,s);a&&o.push(a)}return o},()=>({candidates:r.length,scanned:i.length}))}function o1(e){return e.isFunctionLike?e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&e1.has(e.kind):!0:!1}function s1(e){let t=e.filter(o=>o.leaf&&!Rv(o.leaf)&&!at(o.symbol)&&!bv(o.symbol)&&!Sv(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 i=yv([...n.keys()]),r=new Set;for(let o of i){let s=[...o].flatMap(a=>n.get(a)??[]);if(!(s.length<2)&&!(new Set(s.map(a=>a.relativePath)).size<2)&&!s.every(a=>V(a.relativePath)==="test"))for(let a of s)r.add(a)}return e.filter(o=>r.has(o))}function a1(e,t){if(!t.leaf)return null;let n=Vt(e,t);if(!n||!it(t.symbol)&&!l1(n,t.leaf))return null;let i=hn(mn(n)),r=i.replace(/\s+/g,"");if(!r||r.length<8)return null;let o=i.match(c1)??[];return o.length===0?null:{leaf:t.leaf,symbol:t.symbol,shortName:k(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:de(t),normalizedBody:r,tokens:o,isThinForwarder:Cv(i)}}function l1(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 c1=/[A-Za-z_$][A-Za-z0-9_$]*|\d+(?:\.\d+)?|[^\sA-Za-z0-9_$]/g;function u1(e){return{symbol:e.symbol,shortName:e.shortName,file:e.file,startLine:e.startLine,endLine:e.endLine,loc:e.loc}}function d1(e,t){let n=new Set(e),i=new Set(t);if(n.size===0&&i.size===0)return 1;if(n.size===0||i.size===0)return 0;let r=0;for(let s of n)i.has(s)&&(r+=1);let o=n.size+i.size-r;return o===0?0:r/o}function m1(e,t){let n=Math.min(e.length,t.length),i=0;for(;i<n&&e[i]===t[i];)i+=1;let r=e.slice(i,i+6).join(" "),o=t.slice(i,i+6).join(" ");return!r&&!o?"(bodies differ only in trailing length)":`A: ${r||"(end)"} | B: ${o||"(end)"}`}function yv(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 l=s;for(;t.get(l)!==a;){let c=t.get(l);t.set(l,a),l=c}return a},i=(s,a)=>{let l=n(s),c=n(a);l!==c&&t.set(l,c)},r=new Map;for(let s of e){let a=s.slice(0,2).toLowerCase(),l=r.get(a)??[];l.push(s),r.set(a,l)}for(let s of r.values())for(let a=0;a<s.length;a+=1)for(let l=a+1;l<s.length;l+=1)f1(s[a],s[l])&&i(s[a],s[l]);let o=new Map;for(let s of e){let a=n(s),l=o.get(a)??new Set;l.add(s),o.set(a,l)}return[...o.values()]}function f1(e,t){return e===t||e.toLowerCase()===t.toLowerCase()?!0:e.length<8||t.length<8||Math.abs(e.length-t.length)>2||p1(e.toLowerCase(),t.toLowerCase())/Math.max(e.length,t.length)<.8?!1:v1(e.toLowerCase(),t.toLowerCase(),2)}function p1(e,t){let n=Math.min(e.length,t.length),i=0;for(;i<n&&e[i]===t[i];)i+=1;return i}function g1(e){return/^[A-Z][A-Z0-9_]*$/.test(e)||/^__[^_].*__$/.test(e)||h1.has(e.toLowerCase())}var h1=new Set(["main","row"]),y1=new Set(["app","component","components","feature","features","impl","index","lib","route","routes","shared","src","tsx","typescript","ui"]);function bv(e){return e.startsWith("rust-analyzer ")&&/\/(?:tests?|benches?)\//.test(e)}var b1=new Set(["default","new","reset"]);function Sv(e,t){return e.startsWith("rust-analyzer ")&&b1.has(t.toLowerCase())}function S1(e,t){if(e.leaf.toLowerCase()!==t.leaf.toLowerCase()||e.leaf.length>4)return!0;let n=pv(e);return[...pv(t)].some(i=>n.has(i))}function pv(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&&!y1.has(n)))}function v1(e,t,n){if(Math.abs(e.length-t.length)>n)return!1;let i=Array.from({length:t.length+1},(r,o)=>o);for(let r=1;r<=e.length;r+=1){let o=[r],s=o[0];for(let a=1;a<=t.length;a+=1){let l=e[r-1]===t[a-1]?0:1,c=Math.min(i[a]+1,o[a-1]+1,i[a-1]+l);o.push(c),s=Math.min(s,c)}if(s>n)return!1;i=o}return i[t.length]<=n}function vv(e){return Cv(hn(mn(e)))}function Cv(e){let t=e.trim();if(!t||C1.test(t))return!1;let n=E1(t);return n.length===0||n.length>2?!1:R1(n[n.length-1])}var C1=/\b(?:if|else|for|while|switch|try|catch|do)\b/,x1=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^[\]]*\])*\((?:[^()]|\([^()]*\))*\)$/;function R1(e){let t=e.trim().replace(/^return\s+/,"").replace(/^await\s+/,"").replace(/;\s*$/,"").trim();return x1.test(t)}function E1(e){let t=[],n=0,i="";for(let r of e){if(r==="("||r==="["||r==="{"?n+=1:(r===")"||r==="]"||r==="}")&&(n=Math.max(0,n-1)),r===";"&&n===0){t.push(i),i="";continue}i+=r}return i.trim()&&t.push(i),t.map(r=>r.trim()).filter(r=>r.length>0)}var w1=3;function I1(e){let t=new Map;return(n,i,r)=>{if(!n.isThinForwarder)return!1;let o=`${n.symbol}\0${i.symbol}`,s=t.get(o);if(s!==void 0)return s;let a=xv(e,n,i,r,w1,new Set);return t.set(o,a),a}}function xv(e,t,n,i,r,o){if(r<=0||o.has(t.symbol)||(o.add(t.symbol),(Jt(e,t.file)??[]).filter(l=>l.line>=t.startLine&&l.line<=t.endLine&&l.calleeLeaf===n.leaf).length===0))return!1;let a=new Set(Ce(e,t.file).filter(l=>l.sourcePath&&(l.kind!=="namespace"||l.usedMembers.includes(n.leaf))).map(l=>l.sourcePath));if([...a].some(l=>Pt(l,n.file)))return!0;for(let l of i)if(!(l.symbol===t.symbol||l.symbol===n.symbol||!l.isThinForwarder)&&[...a].some(c=>Pt(c,l.file))&&xv(e,l,n,i,r-1,o))return!0;return!1}function Rv(e){return e.startsWith("<")&&e.endsWith(">")}function gv(e){return[...e].sort()[0]}import{dirname as H1,isAbsolute as U1,relative as z1,resolve as G1}from"path";import{basename as Ev,extname as wv}from"path";function $a(e,t,n,i,r,o){let s=new Set;D1(e,t,n,i)&&s.add(r);for(let a of o)a.value&&L1(s,a.label,a.value);return[...s].slice(0,6)}function L1(e,t,n){let i=P1(n);t.endsWith("name")&&T1(i)&&e.add(`${t} has type-guard boundary shape`);for(let r of i){let o=F1.get(r);o&&e.add(`${t} has ${o} term: ${r}`)}}function D1(e,t,n,i){if(n<=0)return!1;let r=ie(e,t);if(r.length===0)return!1;for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(r[o]??"").trim();if(s!==""){if(Ko(s)===i)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function P1(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 T1(e){return e.some(t=>M1.has(t))&&e.some(t=>A1.has(t))}var F1=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"]]),M1=new Set(["can","has","is","should"]),A1=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function Do(e,t){let{scope:n,maxLoc:i=15,limit:r=30,scanLimit:o}=t??{},s=new U(e);return Ot({candidates:()=>j1(e,s,n,i),orderCandidates:Xs,scanLimit:o,profile:{name:"passthrough-candidates"},prepare:a=>s.calleeEvidenceMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,l)=>l.incompleteSymbolIds.has(a.symbolId)||l.unavailableSymbolIds.has(a.symbolId)?null:N1(e,a,l.rows.get(a.symbolId)??[]),orderResults:(a,l)=>a.loc-l.loc||a.file.localeCompare(l.file),limit:r})}function N1(e,t,n){let i=$1(n);if(i.size!==1||!dm(e,t.relativePath,t.startLine,t.endLine))return null;let[,r]=[...i.entries()][0],o=k1(e,t,r),s=B1(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:k(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:de(t),forwardsTo:r.symbol,forwardsToShort:k(r.symbol),forwardsToFile:r.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:_1(a,o,s)}}function k1(e,t,n){return $a(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:k(t.symbol)},{label:"callee name",value:k(n.symbol)},{label:"passthrough module",value:Ev(t.relativePath,wv(t.relativePath))},{label:"callee module",value:Ev(n.file,wv(n.file))}])}function _1(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 i=t.filter(O1);return i.length>0?`Review the public API before inlining; public-surface evidence: ${i.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 B1(e,t){return Ct(e,t)?En(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:Ue(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function O1(e){return e.includes("public surface")}function $1(e){let t=e.some(i=>ke(i.symbol))?e.filter(i=>ke(i.symbol)):e,n=new Map;for(let i of t)n.has(i.symbol)||n.set(i.symbol,i);return n}function j1(e,t,n,i){return t.productionCallableDefinitions({scope:n,minLoc:3,maxLoc:i,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0}).filter(r=>!Vo(e,r))}var K1=new Set(Zt());function q1(e,t){return`tests/generated/twin-ab/${Iv(e)}-vs-${Iv(t)}.test.ts`}function Iv(e){return(e.split(/[/#]/).pop()||e).replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"symbol"}function W1(e,t,n,i){let{refA:r,refB:o,outFile:s}=typeof t=="string"?{refA:t,refB:n,outFile:i}:t;if(typeof r!="string"||typeof o!="string"||typeof s!="string")throw new TypeError("twinAb requires refA, refB, and outFile.");if(!U1(s))throw new TypeError("twinAb outFile must be an absolute path.");let a=Lv(e,r);if(!a.ok)return a;let l=Lv(e,o);if(!l.ok)return l;let c=a.symbol.paramCount===null||l.symbol.paramCount===null?null:a.symbol.paramCount===l.symbol.paramCount,u=J1(a.symbol,l.symbol,e.config.projectRoot,s,c);return{ok:!0,a:a.symbol,b:l.symbol,signatureCompatible:c,testSource:u}}function Lv(e,t){let i=rt(e,t).match;if(!i)return{ok:!1,reason:`${t} does not resolve to an indexed symbol.`};let o=e.get("SELECT kind FROM global_symbols WHERE id = ?",i.symbolId)?.kind??null;if(!(o!==null?K1.has(o):ke(i.symbol)))return{ok:!1,reason:`${t} resolves to ${k(i.symbol)}${o!==null?` with SCIP kind ${Rr(o)}`:""} \u2014 twin-ab compares call outputs, so both referents must be functions or methods.`};if(!Ct(e,i))return{ok:!1,reason:`${t} (${k(i.symbol)} at ${i.relativePath}:${i.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 = ?",i.symbolId),l=_i(Bi(a?.documentation??null));return{ok:!0,symbol:{ref:t,symbol:i.symbol,shortName:re(i.symbol)||k(i.symbol),file:i.relativePath,startLine:i.startLine,signature:l,paramCount:l?V1(l):null}}}function V1(e){let t=e.indexOf("(");if(t===-1)return null;let n=0,i=-1;for(let a=t;a<e.length;a+=1){let l=e[a];if(l==="(")n+=1;else if(l===")"&&(n-=1,n===0)){i=a;break}}if(i===-1)return null;let r=e.slice(t+1,i).trim();if(!r)return 0;let o=1,s=0;for(let a of r)a==="("||a==="["||a==="{"?s+=1:a===")"||a==="]"||a==="}"?s=Math.max(0,s-1):a===","&&s===0&&(o+=1);return o}function Dv(e,t,n){let i=H1(t),r=G1(e,n),s=z1(i,r).replace(/\\/g,"/").replace(/\.tsx?$/,".js");return s.startsWith(".")?s:`./${s}`}function J1(e,t,n,i,r){let o=Dv(n,i,e.file),s=Dv(n,i,t.file),a=r===null?"Signature comparison: unknown (one or both signatures unavailable in the index) \u2014 check by hand.":r?"Signature comparison: param counts match.":"Signature comparison: param counts DIFFER \u2014 twins may not be directly comparable; check by hand.";return`/**
|
|
376
|
+
* Generated by 'codebaseiq twin-ab'. Cleanup integrity scenario.
|
|
377
|
+
* ("cross-examine same-concept twins"): where one concept is computed in
|
|
378
|
+
* more than one place, feed both the same input and require the same
|
|
379
|
+
* answer. Disagreement between twins means at least one is wrong \u2014
|
|
380
|
+
* determine which before consolidating.
|
|
381
|
+
*
|
|
382
|
+
* Twin A: ${e.shortName} (${e.file}:${e.startLine+1})
|
|
383
|
+
* ${e.signature??"(signature unavailable)"}
|
|
384
|
+
* Twin B: ${t.shortName} (${t.file}:${t.startLine+1})
|
|
385
|
+
* ${t.signature??"(signature unavailable)"}
|
|
386
|
+
* ${a}
|
|
387
|
+
*
|
|
388
|
+
* Fill in the TODO input table below with inputs both twins should agree
|
|
389
|
+
* on, then run this file with vitest.
|
|
390
|
+
*/
|
|
391
|
+
import { describe, expect, it } from 'vitest';
|
|
392
|
+
import { ${e.shortName} as twinA } from '${o}';
|
|
393
|
+
import { ${t.shortName} as twinB } from '${s}';
|
|
394
|
+
|
|
395
|
+
// TODO: fill in shared inputs both twins should agree on \u2014 one arg array per call.
|
|
396
|
+
const inputs: any[][] = [
|
|
397
|
+
// [/* arg1, arg2, ... */],
|
|
398
|
+
];
|
|
399
|
+
|
|
400
|
+
// Cast to a variadic signature so the input table can hold any arg shape \u2014
|
|
401
|
+
// the real twins have fixed, non-rest parameter lists, and TS rejects
|
|
402
|
+
// spreading a generic args array into those (TS2556) even when the array
|
|
403
|
+
// itself is 'any'; casting the callee's signature, not the args, satisfies
|
|
404
|
+
// the checker without weakening the twins' real exported types elsewhere.
|
|
405
|
+
const callA = twinA as (...callArgs: any[]) => any;
|
|
406
|
+
const callB = twinB as (...callArgs: any[]) => any;
|
|
407
|
+
|
|
408
|
+
describe.skipIf(inputs.length === 0)('twin-ab: ${e.shortName} vs ${t.shortName}', () => {
|
|
409
|
+
it.each(inputs)('agrees on input %#', (...args) => {
|
|
410
|
+
expect(callA(...args)).toEqual(callB(...args));
|
|
411
|
+
});
|
|
412
|
+
});
|
|
413
|
+
`}var Pv={caller:3,"entry-surface":2,rooted:1},Y1=/not\s*yet\s*implement|not\s*implement|unimplement|\bnyi\b|\btodo\b|\bstub\b|not\s*supported|coming\s*soon/i,X1=/^throw\s+new\s+[\w.]*Error\s*\(([\s\S]*)\)\s*;?$/,Z1=/^return(\s+(null|undefined|false|0|''|""|``|\[\]|\{\}))?\s*;?$/,Q1=/\/\/\s*TODO\b|\/\*\s*TODO\b/i,ej=/(?:=>|\))\s*(?::\s*[^{;=]+)?\s*\{\s*\}\s*;?\s*$/;function tj(e,t={}){let{scope:n,limit:i=30,scanLimit:r,semantic:o=!0}=t,s=new U(e),a=Ae(s.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),r),l=[];for(let f of a){let p=ij(e,f);p&&l.push(p)}if(l.length===0)return[];let c=aj(e,l,a),u=l.filter(f=>!c.has(f.def.symbol));if(u.length===0)return[];let d=un(e,s).forDefinitions(u.map(f=>f.def),{semantic:o}),m=[];for(let f of u){let p=d.get(f.def.symbolId);if(p?.semanticIncomplete||p?.semanticUnavailable)continue;let g=p?.realConsumers.length??0,h=nj(e,f.def,g);h&&m.push({symbol:f.def.symbol,shortName:k(f.def.symbol),file:f.def.relativePath,startLine:f.def.startLine,endLine:f.def.endLine,loc:de(f.def),stubKind:f.stubKind,reachability:h,callerFanIn:g,stubText:f.stubText})}return m.sort((f,p)=>Pv[p.reachability]-Pv[f.reachability]||p.callerFanIn-f.callerFanIn||f.file.localeCompare(p.file)||f.startLine-p.startLine),i?m.slice(0,i):m}function nj(e,t,n){return n>0?"caller":Ue(e,t.symbol,t.relativePath)?"rooted":Ye(e,t.relativePath)?"entry-surface":null}function ij(e,t){let n=Vt(e,t);if(!n)return null;let i=mn(n),r=i.trim();if(r==="")return!sj(n)||!Ct(e,t)?null:{def:t,stubKind:"empty-body",stubText:"(empty body)"};let o=yr(i),s=hn(i),a=rj(o,s);if(a.length!==1)return null;let l=a[0];return oj(l)?{def:t,stubKind:"throw-stub",stubText:l.trim()}:Q1.test(i)&&Z1.test(l.trim())?{def:t,stubKind:"todo-return-default",stubText:r}:null}function rj(e,t){let n=[],i=0,r="";for(let o=0;o<t.length;o+=1){let s=t[o];if(s==="("||s==="["||s==="{"?i+=1:(s===")"||s==="]"||s==="}")&&(i=Math.max(0,i-1)),s===";"&&i===0){n.push(r),r="";continue}r+=e[o]??""}return r.trim()&&n.push(r),n.map(o=>o.trim()).filter(o=>o.length>0)}function oj(e){let t=X1.exec(e.trim());return t?Y1.test(t[1]??""):!1}function sj(e){return ej.test(e.trimEnd())}function aj(e,t,n){let i=new Set,r=new Set(t.map(a=>a.def.parentTypeName).filter(a=>a!==null));if(r.size===0)return i;let o=cj(e,r),s=new Map;for(let a of n){if(!a.parentTypeName)continue;let l=s.get(a.leaf)??new Set;l.add(a.parentTypeName),s.set(a.leaf,l)}for(let a of t){let l=a.def.parentTypeName;if(!l)continue;let c=o.get(l);if(!c||c.size===0)continue;let u=s.get(a.def.leaf)??new Set;[...c].every(m=>u.has(m))&&i.add(a.def.symbol)}return i}var lj=/\bclass\s+([A-Za-z_$][\w$]*)\s+extends\s+([A-Za-z_$][\w$]*)/g;function cj(e,t){let n=new Map;for(let i of he(e,{includeIgnored:!1})){let r=se(e,i);if(r)for(let o of r.matchAll(lj)){let s=o[1],a=o[2];if(!s||!a||!t.has(a))continue;let l=n.get(a)??new Set;l.add(s),n.set(a,l)}}return n}var uj=/^(?:validate|verify|check|assert)(?:[A-Z].*)?$/,dj=/^(?:is|has)(?:[A-Z].*)?$/,mj=/[{,]\s*(?:ok|success|valid|isValid)\s*:\s*false\b/,ed=/\breturn\b/g,fj=/\bfunction\b|=>|\)\s*(?::\s*[^{;=]+)?\s*\{/,pj=/\.(?:addIssue|push)\s*\(/;function gj(e,t={}){let{scope:n,limit:i=30,scanLimit:r}=t,o=new U(e),s=Ae(o.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),r),a=[];for(let l of s){let c=yj(e,l);c&&a.push({symbol:l.symbol,shortName:k(l.symbol),file:l.relativePath,startLine:l.startLine,endLine:l.endLine,loc:de(l),...c})}return a.sort((l,c)=>l.file.localeCompare(c.file)||l.startLine-c.startLine||l.loc-c.loc),i?a.slice(0,i):a}function hj(e){return uj.test(e)?"imperative":dj.test(e)?"predicate":null}function yj(e,t){let n=hj(t.leaf);if(!n||ir(e,t))return null;let i=Vt(e,t);if(!i||!fj.test(i))return null;let r=ee(e,t.relativePath)?.callables.find(s=>s.startLine===t.startLine&&s.endLine===t.endLine);if(n==="predicate"&&r?.paramCount===0)return null;if(vv(i)){let s=vj(e,t);return!s||Mv(s.body,Fv(s.snippet))||Tv(s.body)?null:{nameKind:n,resolvedVia:"one-hop-delegate",delegateTarget:s.shortName}}let o=mn(i);return Mv(o,Fv(i))||Tv(o)?null:{nameKind:n,resolvedVia:"direct"}}var bj=new Set(["if","for","while","switch","catch","function"]);function Tv(e){let t=yr(e);for(let n of t.matchAll(/\b([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/g))if(!bj.has(n[1]))return!0;return!1}function Fv(e){let t=e.indexOf("=>");return t===-1?!1:!/^\s*\{/.test(e.slice(t+2))}function Mv(e,t){let n=yr(e);if(/\bthrow\b/.test(n)||/\.reject\s*\(/.test(n)||mj.test(n)||pj.test(n))return!0;let i=Sj(n);if(t&&i.length===0){let r=n.trim();return r!==""&&r!=="true"}for(let r of i)if(r!==""&&r!=="true")return!0;return!1}function Sj(e){let t=[];ed.lastIndex=0;let n;for(;n=ed.exec(e);){let i=n.index+n[0].length,r=0,o=e.length;for(let s=i;s<e.length;s+=1){let a=e[s];if(a==="("||a==="["||a==="{")r+=1;else if(a===")"||a==="]"||a==="}"){if(r===0){o=s;break}r-=1}else if(a===";"&&r===0){o=s;break}}t.push(e.slice(i,o).trim()),ed.lastIndex=o}return t}function vj(e,t){let n=ai(e,t,{callableOnly:!0,limit:3,semanticEvidence:pe});if(n.semanticIncomplete||n.semanticUnavailable)return null;let i=n.rows,r=[...new Set(i.map(c=>c.symbol))].filter(c=>c!==t.symbol);if(r.length!==1)return null;let s=rt(e,r[0]).match;if(!s)return null;let a=J(e,s.relativePath).find(c=>c.symbolId===s.symbolId);if(!a)return null;let l=Vt(e,a);return l?{body:mn(l),snippet:l,shortName:k(a.symbol)}:null}var Cj=60;function xj(e,t={}){let{scope:n,limit:i=30,scanLimit:r,rotDays:o=Cj}=t,s=Ae(Mi(e,{extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs"]}).filter(u=>V(u)==="test").filter(u=>!n||u.includes(n)).filter(u=>!e.isIgnored(u)).sort(),r),a=[],l=[],c=[];for(let u of s){let d=se(e,u);if(!d)continue;let m=lm(d),f=wj(d);for(let g of Pj(m,f))f.add(g);let p=Rj(m);for(let g of p){if(g.skip){l.push(_j(e,u,g,o));continue}if(g.kind==="describe")continue;let h=Nv(d,g.argsStart),S=m.slice(g.argsStart,g.callEnd),v=d.slice(g.argsStart,g.callEnd);kv(S,f)||a.push({file:u,startLine:Po(d,g.callStart),endLine:Po(d,g.callEnd),title:h,severity:/\bawait\b/.test(S)?"low":"high"});let y=Aj(S,v);y&&c.push({file:u,startLine:Po(d,g.callStart),endLine:Po(d,g.callEnd),title:h,echoedValue:y})}}return{assertionFree:i?a.slice(0,i):a,skipped:i?l.slice(0,i):l,mockEcho:i?c.slice(0,i):c}}var td=/(?<!\.)\b(?:x(it|test|describe)|(it|test|describe)(?:\.\s*(skip|only|todo|each\s*\([^)]*\)))?)\s*\(/g;function Rj(e){let t=[];td.lastIndex=0;let n;for(;n=td.exec(e);){let i=n[1],r=i??n[2];if(!r)continue;let o=n[3]?.split(/\s*\(/)[0],s=n.index,a=n.index+n[0].length-1,l=To(e,a);td.lastIndex=a+1,o!=="each"&&t.push({kind:r,skip:i!==void 0||o==="skip"||o==="todo",skipKind:o==="todo"?"todo":"skip",callStart:s,argsStart:a+1,callEnd:l+1})}return t}function To(e,t){let n=0;for(let i=t;i<e.length;i+=1){let r=e[i];if(r==="(")n+=1;else if(r===")"&&(n-=1,n===0))return i}return e.length-1}function Po(e,t){let n=0;for(let i=0;i<t&&i<e.length;i+=1)e[i]===`
|
|
414
|
+
`&&(n+=1);return n}function Nv(e,t){let n=e.slice(t,t+400),i=/^\s*(['"`])((?:\\.|(?!\1)[\s\S])*)\1/.exec(n);return i?i[2]:"(anonymous)"}var Ej=new Set(["vitest","chai","jest","@jest/globals","assert","node:assert","node:assert/strict","assert/strict","uvu/assert","expect","chai-as-promised"]),Av=/import\s+(?:\*\s+as\s+(\w+)|\{([^}]*)\}|(\w+))\s+from\s+['"]([^'"]+)['"]/g;function wj(e){let t=new Set(["expect","assert"]);Av.lastIndex=0;let n;for(;n=Av.exec(e);){let[,i,r,o,s]=n;if(!(!s||!Ej.has(s))&&(i&&t.add(i),o&&t.add(o),r))for(let a of r.split(",")){let l=a.trim().replace(/^type\s+/,"");if(!l)continue;let c=/^(\w+)\s+as\s+(\w+)$/.exec(l);t.add(c?c[2]:l)}}return t}function kv(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 i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\b${i}\\s*(?:<[^<>]*>)?\\s*[.(]`).test(e))return!0}return!1}var Ij=/\bfunction\s+(\w+)\s*\(/g,Lj=/\b(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/g,Dj=60;function Pj(e,t){let n=new Set;for(let i of[Ij,Lj]){i.lastIndex=0;let r;for(;r=i.exec(e);){let o=r[1],s=r.index+r[0].length-1,a=To(e,s),l=e.indexOf("{",a+1);if(l===-1||l-a>Dj)continue;let c=Tj(e,l),u=e.slice(l+1,c);kv(u,t)&&n.add(o)}}return n}function Tj(e,t){let n=0;for(let i=t;i<e.length;i+=1){let r=e[i];if(r==="{")n+=1;else if(r==="}"&&(n-=1,n===0))return i}return e.length-1}var Fj=/\bmock(?:ReturnValue|ResolvedValue)(?:Once)?\s*\(/g,nd=/\bexpect\s*\(/g,Mj=/^\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(/,_v=/^(?:-?\d+(?:\.\d+)?|(['"`]).+\1)$/;function Aj(e,t){let n=Nj(e,t,Fj);if(n.length===0)return null;let i=kj(e,t);for(let r of i)if(n.includes(r))return r;return null}function Nj(e,t,n){let i=[];n.lastIndex=0;let r;for(;r=n.exec(e);){let o=r.index+r[0].length-1,s=To(e,o),a=t.slice(o+1,s).trim();_v.test(a)&&i.push(a),n.lastIndex=s+1}return i}function kj(e,t){let n=[];nd.lastIndex=0;let i;for(;i=nd.exec(e);){let r=i.index+i[0].length-1,o=To(e,r),s=e.slice(o+1),a=Mj.exec(s);if(nd.lastIndex=o+1,!a)continue;let l=o+1+a[0].length-1,c=To(e,l),u=t.slice(l+1,c).trim();_v.test(u)&&n.push(u)}return n}function _j(e,t,n,i){let r=se(e,t),o=Nv(r,n.argsStart),s=Po(r,n.callStart),a=Bj(e.config.projectRoot,t,s),l=a===null?"unknown":a>=i?"rot":"workflow";return{file:t,startLine:s,title:o,skipKind:n.skipKind,blockKind:n.kind,ageDays:a,rot:l}}function Bj(e,t,n){let i=n+1;try{let r=dn(e,["blame","-L",`${i},${i}`,"--porcelain","--",t]),o=/^author-time (\d+)$/m.exec(r);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 Oj=.7,Bv=.62,Ov=.45;function $j(e,t={}){let{windowCommits:n=100,limit:i=30,scope:r,scanLimit:o}=t,s=Wt(e,{historyMode:t.historyMode}).fileAddRecords();if(!s)return{available:!1,windowCommits:n,findings:[]};if(i<=0)return{available:!0,windowCommits:n,findings:[]};let a=Vj(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let c=jj(e,{limit:i,minSimilarity:t.minSimilarity,scanLimit:o,scope:r,semantic:t.semantic,focusFiles:Number.isFinite(i)?void 0:a}).map(d=>Jj(d,s,n)).filter(d=>d!==null);c.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=c.slice(0,i).map(Yj);return{available:!0,windowCommits:n,findings:u,rootCauseGroups:Xj(u)}}function jj(e,t){let n=Qj(t.limit),i=[...Hj(e,{scope:t.scope,minSimilarity:t.minSimilarity??Oj,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],r=Jo(e,{scope:t.scope});return r.react&&i.push(...Uj(e,{scope:t.scope,minSimilarity:t.minSimilarity??Bv,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...zj(e,{scope:t.scope,minSimilarity:t.minSimilarity??Ov,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r.vue&&i.push(...qj(e,{scope:t.scope,minSimilarity:t.minSimilarity??Bv,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...Wj(e,{scope:t.scope,minSimilarity:t.minSimilarity??Ov,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i}function Hj(e,t){return bo(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles}).filter(n=>!at(n.symbolA)&&!at(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 Uj(e,t){return Ha(e,t,{query:So,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 Ha(e,t,n){return n.query(e,t).filter(i=>i.fileA!==i.fileB).filter(i=>n.acceptPair?.(i)??!0).map(i=>({domain:n.domain,basis:n.basis,symbolA:n.symbolA(i),fileA:i.fileA,symbolB:n.symbolB(i),fileB:i.fileB,similarity:i.similarity,sharedEvidence:eH(...n.evidenceBuckets(i)),sharedCallees:[]}))}function zj(e,t){return Ha(e,t,{query:vo,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,acceptPair:Kj,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 Gj=new Set(["useCallback","useEffect","useLayoutEffect","useMemo","useMutation","useQueries","useQuery","useQueryClient","useReducer","useRef","useState"]);function Kj(e){return e.sharedHooks.some(t=>!Gj.has(t))||e.sharedState.length>0||e.sharedHandlers.length>0||e.sharedHandlerVerbs.length>=2}function qj(e,t){return Ha(e,t,{query:Co,domain:"vue-component",basis:"vue-template",symbolA:n=>ja(n.fileA),symbolB:n=>ja(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function Wj(e,t){return Ha(e,t,{query:xo,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>ja(n.fileA),symbolB:n=>ja(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 Vj(e,t){let n=new Set;for(let[i,r]of e)r.commitsAgo<=t&&n.add(i);return n}function Jj(e,t,n){let i=t.get(e.fileA)?.commitsAgo??null,r=t.get(e.fileB)?.commitsAgo??null,o=i!==null&&i<=n,s=r!==null&&r<=n;if(!o&&!s)return null;if(o&&s){let a=(i??0)<=(r??0);return{kind:"twin",domain:e.domain,basis:e.basis,echoSymbol:a?e.symbolA:e.symbolB,echoFile:a?e.fileA:e.fileB,echoAgeCommits:(a?i:r)??0,establishedSymbol:a?e.symbolB:e.symbolA,establishedFile:a?e.fileB:e.fileA,establishedAgeCommits:a?r:i,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?i:r)??0,establishedSymbol:o?e.symbolB:e.symbolA,establishedFile:o?e.fileB:e.fileA,establishedAgeCommits:o?r:i,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}function Yj(e){let t=$v(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function $v(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 Xj(e){let t=new Map;for(let[n,i]of e.entries()){let r=i.rootCauseKey??$v(i),o=i.groupKey??`recent-duplicate:${r}`,s=t.get(o);s||(s={groupKey:o,rootCauseKey:r,kind:i.kind,domain:i.domain,basis:i.basis,count:0,maxSimilarity:i.similarity,findingIndexes:[],echoFiles:new Set,establishedFile:i.kind==="echo"?i.establishedFile:void 0,establishedSymbol:i.kind==="echo"?i.establishedSymbol:void 0,relatedFiles:new Set,sharedEvidence:new Set,recommendation:Zj(i)},t.set(o,s)),s.count+=1,s.maxSimilarity=Math.max(s.maxSimilarity,i.similarity),s.findingIndexes.push(n),s.echoFiles.add(i.echoFile),s.relatedFiles.add(i.echoFile),s.relatedFiles.add(i.establishedFile);for(let a of i.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,i)=>i.count-n.count||i.maxSimilarity-n.maxSimilarity||n.groupKey.localeCompare(i.groupKey))}function Zj(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 Qj(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function eH(...e){let t=[],n=new Set;for(let[i,r]of e)for(let o of r){let s=`${i}:${o}`;n.has(s)||(n.add(s),t.push(s))}return t}function ja(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var tH=Fe("suppression-inventory",{clearGroups:["whole-project"]});function Ua(e){return tH.get(e,()=>nH(e))}function nH(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,twin:0,uncategorized:0},n=new Map,i=0;for(let r of Mi(e)){let o=se(e,r);if(!(!o||!o.includes("codebaseiq")))for(let s of o.split(/\r?\n/)){let a=Ko(s);if(a===null)continue;i+=1,n.set(r,(n.get(r)??0)+1);let l=jv(a);t[l]+=1}}for(let r of e.config.suppressions??[])r.expiresAt&&Date.parse(r.expiresAt)<=Date.now()||(i+=1,r.file&&n.set(r.file,(n.get(r.file)??0)+1),t[jv(r.check)]+=1);return{total:i,byCategory:t,byFile:n}}function jv(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 id(e,t,n={}){let i=fe(e,t);if(!i)return null;let r=new U(e),o=iH(e,i),s=i.endLine-i.startLine+1,a=r.calleeEvidenceMap([i],{additive:!0,semantic:n.semantic}),l=a.rows.get(i.symbolId)??[],c=new Set(l.map(p=>p.symbol)),u=a.incompleteSymbolIds.has(i.symbolId),d=a.unavailableSymbolIds.has(i.symbolId),m=n.semantic===!1?"disabled":u&&d?"incomplete-and-unavailable":u?"incomplete":d?"unavailable":"complete",f=!u&&!d;return{symbol:i.symbol,shortName:k(i.symbol),relativePath:i.relativePath,startLine:i.startLine,endLine:i.endLine,loc:s,branches:o.branches,estimateBasis:o.estimateBasis,cyclomaticEstimate:o.branches+1,calleeCount:f?c.size:null,fanIn:oH(e,i.symbolId),fanOut:f?sH(l,i.relativePath):null,coverage:{semanticEvidence:m}}}function iH(e,t){let n=ae(e,t.relativePath);if(n){let i=Gv(n.rootNode,t.startLine,t.endLine);if(i)return{branches:aH(i),estimateBasis:"ast"}}return{branches:qv(zv(e,t.relativePath,t.startLine,t.endLine),Uv(e,t.relativePath)),estimateBasis:"regex-fallback"}}function Hv(e,t){let n=new Map,i=new Map;for(let r of t){let o=i.get(r.relativePath)??[];o.push(r),i.set(r.relativePath,o)}for(let[r,o]of i){let s=ae(e,r),a=s===null?[]:o.filter(c=>s.rootNode.startPosition.row<=c.startLine&&s.rootNode.endPosition.row>=c.endLine),l=new Set(a.map(c=>c.symbolId));if(s&&a.length>0){for(let c of a)n.set(c.symbolId,{branches:0,estimateBasis:"ast"});lH(s.rootNode,a,n)}for(let c of o)l.has(c.symbolId)||n.set(c.symbolId,rH(e,c))}return n}function rH(e,t){return{branches:qv(zv(e,t.relativePath,t.startLine,t.endLine),Uv(e,t.relativePath)),estimateBasis:"regex-fallback"}}function Uv(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function zv(e,t,n,i){try{return nt(e.config.projectRoot,t,{inputKind:"indexed source file"}).split(`
|
|
415
|
+
`).slice(n,i+1).join(`
|
|
416
|
+
`)}catch(r){if(!St(r))throw r;return""}}function oH(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
|
|
417
|
+
FROM mentions m
|
|
418
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
419
|
+
JOIN (
|
|
420
|
+
SELECT m2.symbol_id, c2.document_id
|
|
421
|
+
FROM mentions m2
|
|
422
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
423
|
+
WHERE m2.role = 1
|
|
424
|
+
GROUP BY m2.symbol_id
|
|
425
|
+
) sym_def ON sym_def.symbol_id = m.symbol_id
|
|
426
|
+
WHERE m.symbol_id = ?
|
|
427
|
+
AND m.role != 1
|
|
428
|
+
AND sym_def.document_id != c.document_id`,t)?.c??0}function sH(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function aH(e){let t=0;return rd(e,n=>{t+=Kv(n)}),t}function lH(e,t,n){let i=[...t].sort((r,o)=>r.startLine-o.startLine||o.endLine-r.endLine);rd(e,r=>{let o=Kv(r);if(o===0)return;let s=r.startPosition.row,a=r.endPosition.row;for(let l of i){if(l.startLine>s)break;if(l.endLine<a)continue;let c=n.get(l.symbolId);c&&(c.branches+=o)}})}function rd(e,t){t(e);for(let n of e.namedChildren)rd(n,t)}function Gv(e,t,n){if(e.startPosition.row>t||e.endPosition.row<n)return null;for(let i of e.namedChildren){let r=Gv(i,t,n);if(r)return r}return e}var cH=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 Kv(e){return cH.has(e.type)?1:e.type==="binary_expression"&&e.parent?.type!=="binary_expression"&&(e.text.includes("&&")||e.text.includes("||"))?uH(e.text):0}function uH(e){return(e.match(/&&|\|\|/g)??[]).length}function qv(e,t){let n=hn(e),i=0,r=[/\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 r){let s=n.match(o);s&&(i+=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&&(i+=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&&(i+=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&&(i+=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&&(i+=a.length)}}return i}function Wv(e,t,n={}){let i=fe(e,t);if(!i)return null;let r=[{file:i.relativePath,line:i.startLine}],o=On(e,i,{semantic:n.semantic,semanticEvidence:pe}).map(l=>({file:l.file,line:l.line,enclosingSymbol:l.enclosingSymbol??"(top-level)",enclosingShort:l.enclosingSymbol?k(l.enclosingSymbol):"(top-level)"})),{outgoingCalls:s,incomingCalls:a}=dH(e,i,o,{semantic:n.semantic!==!1});return{symbol:i.symbol,shortName:k(i.symbol),relativePath:i.relativePath,definitionSites:r.filter(l=>!e.isIgnored(l.file)),referenceSites:o,outgoingCalls:s.filter(l=>!e.isIgnored(l.file)).map(l=>({symbol:l.symbol,shortName:k(l.symbol),file:l.file})),incomingCalls:a.filter(l=>!e.isIgnored(l.file)).map(l=>({symbol:l.symbol,shortName:l.symbol===l.file?"(top-level)":k(l.symbol),file:l.file}))}}function od(e,t,n={}){let i=Wv(e,t,n);return i?{symbol:i.symbol,shortName:i.shortName,relativePath:i.relativePath,definitionSites:i.definitionSites,usageSites:i.referenceSites,producers:i.outgoingCalls,consumers:i.incomingCalls}:null}function dH(e,t,n,i){let r=Yi(fs(e,t,{limit:30,semantic:i.semantic,semanticEvidence:pe}).map(a=>({symbol:a.symbol,file:a.file}))),o=Yi(ps(e,t,{limit:30,semantic:i.semantic,semanticEvidence:pe})),s=o.length>0?o:Yi(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{outgoingCalls:r,incomingCalls:s}}function Vv(e,t,n={}){let{direction:i="backward",maxDepth:r=3}=n,o=fe(e,t);return o?i==="backward"?mH(e,o,r,{semantic:n.semantic!==!1}):fH(e,o,{semantic:n.semantic!==!1}):null}function za(e,t,n={}){return Vv(e,t,n)}function mH(e,t,n,i){let r=[],o=new Set([t.symbol]),s=[t];for(let a=1;a<=n&&s.length!==0;a++){let l=[];for(let c of s){let u=fs(e,c,{semantic:i.semantic,semanticEvidence:pe});for(let d of u){if(o.has(d.symbol))continue;o.add(d.symbol),r.push({symbol:d.symbol,shortName:k(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=ri(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&l.push(m)}}s=l}return{symbol:t.symbol,shortName:k(t.symbol),direction:"backward",connectedSymbols:r}}function fH(e,t,n){let i=new Set,r=[],o=new U(e);for(let s of On(e,t,{semantic:n.semantic,semanticEvidence:pe})){if(r.length>=30)break;let a=s.enclosingSymbol??Ge(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let l=ri(e,a);!l||e.isIgnored(l.relativePath)||i.has(l.symbol)||(i.add(l.symbol),r.push({symbol:l.symbol,shortName:k(l.symbol),file:l.relativePath,relationship:`references target at ${s.file}:${s.line+1}`}))}return r.sort((s,a)=>s.file.localeCompare(a.file)),{symbol:t.symbol,shortName:k(t.symbol),direction:"forward",connectedSymbols:r}}function Jv(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 tC=6,Ka=10,ad=3,ld=8,pH=.7,Yv=24,sd=200,nC=12,Xv=80,Zv=600;function gH(e,t,n={}){let i=n.impactDepth??3,r=n.sliceDepth??3,o=n.semantic,s=wH(t)?yH(e,t):null,a=s?s.primary?.symbol??null:t,l=a!==null,c=l?qe("trace",a,()=>Dc(e,a,{semantic:o,referenceContext:nC}),T=>({definitions:T.definitions.length,references:T.referencedBy.length})):{definitions:[],referencedBy:[],claimSupport:null},u=l?qe("call-graph",a,()=>Vr(e,a,{semantic:o}),T=>({callers:T?.callers.length??0,callees:T?.callees.length??0})):null,d=l?qe("complexity",a,()=>id(e,a,{semantic:o}),T=>({callees:T?.calleeCount??0})):null,m=l?qe("dataflow",a,()=>od(e,a,{semantic:o}),T=>({references:T?.usageSites.length??0,producers:T?.producers.length??0,consumers:T?.consumers.length??0})):null,f=l?qe("backward-slice",a,()=>za(e,a,{direction:"backward",maxDepth:r,semantic:o}),T=>({maxDepth:r,connectedSymbols:T?.connectedSymbols.length??0})):null,p=l?qe("forward-slice",a,()=>za(e,a,{direction:"forward",maxDepth:r,semantic:o}),T=>({maxDepth:r,connectedSymbols:T?.connectedSymbols.length??0})):null,g=l?qe("affected",a,()=>Tu(e,a,{maxDepth:i,scope:n.scope}),T=>({maxDepth:i,affectedSymbols:T.rows.length,coverage:T.coverage.status})):null,h=g?.rows??[],S=g?.coverage??null,v=l?qe("reuse-candidates",a,()=>yo(e,a,{minSimilarity:.4,limit:5,semantic:o,sourceCandidateMode:"target-pruned"}),T=>({candidates:T.length,direct:T.filter(A=>A.actionTier==="direct").length})):[],y=l?fe(e,a)?.symbol??null:null,E=l?qe("affected-consumer-reuse",a,()=>SH(c,y,T=>yo(e,T,{minSimilarity:.4,limit:Ka,semantic:o,sourceCandidateMode:"target-pruned"}),{consumerLimit:tC,perConsumerSearchLimit:Ka,perConsumerCandidateLimit:ad,candidateLimit:ld}),T=>({totalConsumers:T.coverage.totalConsumers,analyzedConsumers:T.coverage.analyzedConsumers,candidates:T.candidates.length})):RH(),w=qe("change-surface",t,()=>Fu(e,t,{semantic:o}),T=>({symbols:T?.symbols.length??0,externalConsumers:T?.totalExternalConsumers??0})),b=qe("system",t,()=>su(e,t),T=>({files:T.files.length,symbols:T.symbols.length})),R=b.files.length===1,C=qe("deps",t,()=>R?b.dependsOn.map(T=>({relativePath:T,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):Jr(e,t),T=>({files:T.length,reusedSystem:R})),L=qe("rdeps",t,()=>R?b.dependedOnBy.map(T=>({relativePath:T,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):Yr(e,t),T=>({files:T.length,reusedSystem:R})),I=qe("surface",t,()=>au(e,t),T=>({consumers:T.length})),x={symbol:c.definitions.length>0||c.referencedBy.length>0||u!==null||d!==null||m!==null||f!==null||p!==null||h.length>0,file:w!==null||C.length>0||L.length>0,module:b.files.length>0||b.symbols.length>0||I.length>0},P=[];s&&!s.primary&&s.callableCount>1&&P.push(`File target has ${s.callableCount} callable symbols; use one callable name for compiler-resolved flow.`);let _=[...new Set(c.referencedBy.map(T=>T.relativePath))];_.length>0&&_.every(T=>V(T)==="test")&&P.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."),!x.symbol&&!x.file&&!x.module&&P.push("No symbol, file, or module matched target."),S&&S.status!=="accounted"&&P.push(`Possible-impact coverage is ${S.status}: ${S.reasons.join(" ")}`);let D=w?.file??c.definitions[0]?.relativePath??null;return{target:t,...s?.primary?{primaryCallable:{symbol:s.primary.symbol,shortName:re(s.primary.symbol),file:s.primary.relativePath}}:{},matched:x,history:qe("history",D??t,()=>EH(e,D,n.gitHead)),trace:hH(c),callGraph:u,complexity:d,dataflow:m,backwardSlice:f,forwardSlice:p,affected:h,affectedCoverage:S,changeSurface:w,deps:C,rdeps:L,system:b,surface:I,reuseCandidates:v,affectedConsumerReuse:E,sourcePacket:bH(e,y,c,E,v),warnings:P}}function hH(e){return{definitions:e.definitions,referencedBy:e.referencedBy.map(t=>({relativePath:t.relativePath,line:t.line,enclosingSymbol:t.enclosingSymbol,enclosingShort:t.enclosingShort}))}}function yH(e,t){let n=bn(e,t);if(n.length!==1)return{primary:null,callableCount:0};let i=J(e,n[0]).filter(s=>s.isFunctionLike),r=i.filter(s=>s.enclosingSymbol===null),o=r.length>0?r:i;return{primary:o.length===1?o[0]:null,callableCount:o.length}}function bH(e,t,n,i,r){let o=[...t?[{definition:Qv(e,t),role:"target"}]:[],...[...i.candidates.map(d=>d.candidate),...r].map(d=>({definition:Qv(e,d.symbolB),role:"reuse-candidate"}))],s=new Map;for(let d of Jv(o)){if(s.has(d.definition.symbol))continue;let m=d.role==="target"?sd:Xv,f=d.definition.endLine<=d.definition.startLine?jn(e,d.definition.relativePath,d.definition.startLine,m):null,p=f?.unitType?f.source:Vt(e,d.definition);if(!p)continue;let g=p.split(`
|
|
429
|
+
`),h=Math.min(g.length,m),S=f?.unitType?f.startLine:d.definition.startLine;s.set(d.definition.symbol,{role:d.role,symbol:d.definition.symbol,shortName:re(d.definition.symbol),file:d.definition.relativePath,startLine:S,endLine:S+h-1,source:g.slice(0,h).join(`
|
|
430
|
+
`),omittedLines:(f?.unitType?f.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}`,f=a.get(m);if(f){f.focusLines=[...new Set([...f.focusLines??[],d.line])].sort((p,g)=>p-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 l=[...[...s.values()].filter(d=>d.role==="target"),...a.values(),...[...s.values()].filter(d=>d.role==="reuse-candidate")],c=[],u=Zv;for(let d of l){if(c.length>=Yv||u<=0)break;let m=d.source.split(`
|
|
431
|
+
`),f=Math.min(m.length,u);c.push({...d,endLine:d.startLine+f-1,source:m.slice(0,f).join(`
|
|
432
|
+
`),omittedLines:d.omittedLines+Math.max(0,m.length-f),...d.focusLines?{focusLines:d.focusLines.filter(p=>p<=d.startLine+f-1)}:{}}),u-=f}return{slices:c,candidateSlices:l.length,omittedSlices:Math.max(0,l.length-c.length),maxSlices:Yv,maxLinesPerSlice:sd,maxTotalLines:Zv,targetLineLimit:sd,consumerContextLines:nC,reuseLineLimit:Xv}}function Qv(e,t){let n=ri(e,t);return n?J(e,n.relativePath).find(i=>i.symbol===t)??null:null}function SH(e,t,n,i={}){let r=Ga(i.consumerLimit,tC),o=Ga(i.perConsumerSearchLimit,Ka),s=Ga(i.perConsumerCandidateLimit,ad),a=Ga(i.candidateLimit,ld),l=vH(e),c=l.slice(0,r),u=new Set(l.map(f=>f.symbol));t&&u.add(t);let d=new Map;for(let f of c){let p=n(f.symbol).slice(0,o),g=0;for(let h of p){let S=CH(h,f.symbol);if(!S||u.has(S.symbolB))continue;let v=d.get(S.symbolB);if(v?(v.consumers.some(y=>y.symbol===f.symbol)||v.consumers.push(f),S.similarity>v.candidate.similarity&&(v.candidate=S)):d.set(S.symbolB,{candidate:S,consumers:[f]}),g+=1,g>=s)break}}let m=[...d.values()].filter(f=>f.candidate.actionTier==="direct"||f.candidate.similarity>=pH||f.consumers.length>1).sort(xH).slice(0,a);return{candidates:m,coverage:{totalConsumers:l.length,analyzedConsumers:c.length,omittedConsumers:Math.max(0,l.length-c.length),perConsumerSearchLimit:o,perConsumerCandidateLimit:s,candidateLimit:a,returnedCandidates:m.length}}}function vH(e){let t=new Map;for(let n of e.referencedBy){if(!n.enclosingSymbol)continue;let i=t.get(n.enclosingSymbol);if(i){i.referenceCount+=1;continue}t.set(n.enclosingSymbol,{symbol:n.enclosingSymbol,shortName:re(n.enclosingSymbol)||n.enclosingShort,file:n.relativePath,referenceCount:1})}return[...t.values()].sort((n,i)=>i.referenceCount-n.referenceCount||n.symbol.localeCompare(i.symbol))}function CH(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 xH(e,t){let n=eC(t.candidate.actionTier)-eC(e.candidate.actionTier);if(n!==0)return n;let i=t.consumers.length-e.consumers.length;if(i!==0)return i;let r=t.candidate.similarity-e.candidate.similarity;return r!==0?r:e.candidate.symbolB.localeCompare(t.candidate.symbolB)}function eC(e){return e==="direct"?1:0}function Ga(e,t){return typeof e=="number"&&Number.isFinite(e)?Math.max(1,Math.floor(e)):t}function RH(){return{candidates:[],coverage:{totalConsumers:0,analyzedConsumers:0,omittedConsumers:0,perConsumerSearchLimit:Ka,perConsumerCandidateLimit:ad,candidateLimit:ld,returnedCandidates:0}}}function qe(e,t,n,i=()=>({})){let r;return $(`context.${e}`,()=>(r=n(),r),()=>({target:t,...i(r)}))}function EH(e,t,n){let i={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return i;let r=Wt(e,n?{head:n}:{}),o=qe("history.churn",t,()=>r.fileChurn(),l=>({files:l?.size??0}));if(!o)return i;let s=qe("history.co-change",t,()=>wo(e,t,{limit:5,...n?{head:n}:{}}),l=>({commits:l.commitsAnalyzed,partners:l.findings.length})),a=qe("history.suppressions",t,()=>Ua(e).byFile.get(t)??0,l=>({suppressions:l}));return{available:!0,file:t,churn:o.get(t)??{changes:0,fixChanges:0,lastChangedAt:0},coChangePartners:s.findings.map(l=>({file:l.fileA===t?l.fileB:l.fileA,together:l.together,confidence:l.confidence,subjectContext:l.subjectContext})),suppressionsInFile:a}}function wH(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}var Oe={dead:{minLoc:3,skipBarrels:!0,deadCodeOnly:!0},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 IH}from"fs";import{isAbsolute as LH,join as DH}from"path";var PH=".codebaseiq-baseline.json";function cd(e){if(e.startsWith("similar:")){let t=e.slice(8).split("|");return t.length!==2?e:`similar:${t.map(k).sort().join("|")}`}if(e.startsWith("duplicate-bodies:")){let t=e.slice(17),n=t.indexOf(":");if(n<0)return e;let i=t.slice(0,n),r=t.slice(n+1).split("|");return r.length<2?e:`duplicate-bodies:${i}:${r.map(k).sort().join("|")}`}return e}function ud(e,t){return t&&LH(t)?t:DH(e.config.projectRoot,t??PH)}function iC(e,t,n={}){let i=ud(e,n.path);if(!IH(i))throw new Error(`No baseline found at ${i}. Create one with: codebaseiq health --write-baseline`);let o=(JSON.parse(gr(i,"health baseline")).findings??[]).map(cd),s=new Set(n.accept?o.filter(n.accept):o),a=new Set(t);return{baselinePath:i,baselineCount:s.size,current:[...t],newFindings:t.filter(l=>!s.has(l)),fixedFindings:[...s].filter(l=>!a.has(l))}}import Fo from"path";function Ao(e,t){let{scope:n,minDeviation:i=5,limit:r=50}=t??{},o=t?.semantic!==!1,s=t?.includePatternDeviations===!0,l=new U(e).fileDependencyGraph(n),c=fo(e,{scope:n}),u=NH([...TH(e,l,{scope:n,semantic:o}),...MH(c.forbiddenEdges),...s?AH(l,i):[]]);return t?.includeArchitecture===!0&&(u.architecture=c),r<=0||u.results.length<=r?u:{...u,results:u.results.slice(0,r),totalResults:u.results.length}}function TH(e,t,n){let i=BH(e,n.scope),r=[],o=new Set;for(let[a,l]of t){if(Mo(a))continue;let c=i.get(a)??new Set;for(let u of l)Mo(u)||c.has(u)||FH(e,a,u,n)||(r.push({file:a,dep:u}),o.add(a))}o.size>0&&jH(e,i,{paths:[...o]});let s=[];for(let{file:a,dep:l}of r)(i.get(a)??new Set).has(l)||s.push({file:a,kind:"unused-import",description:`Depends on ${l} but references none of its symbols`,dep:l,actionTier:"direct",evidenceReasons:[`dependency edge exists from ${a} to ${l}`,"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 FH(e,t,n,i){return zH(e,t,n)||GH(e,t,n)||HH(n)||qH(e,t,n)||KH(n)?!0:i.semantic&&UH(e,t,n)}function MH(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(i=>`${i.fromFile} imports ${i.toFile}`)],recommendation:"Move the dependency behind an allowed boundary, reverse the dependency through an owned interface, or deliberately update the project architecture rule."}]:[]})}function AH(e,t){let n=[];for(let[i,r]of kH(e)){let o=r.filter(a=>!Mo(a));if(o.length<t)continue;let s=_H(e,o);for(let a of o)for(let l of e.get(a)??[])Mo(l)||(s.get(l)??0)===1&&Fo.dirname(l)!==i&&Fo.dirname(l)!==Fo.dirname(i)&&n.push({file:a,kind:"pattern-deviation",description:`Only file in ${i}/ that depends on ${l}`,dep:l,actionTier:"signal",evidenceReasons:[`${o.length} sibling file(s) in ${i}/ were compared`,`${a} is the only non-skipped sibling depending on ${l}`],recommendation:"Review sibling ownership before changing this import; unique dependency shape can be intentional specialization."})}return n}function NH(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 kH(e){let t=new Map;for(let n of e.keys()){let i=Fo.dirname(n),r=t.get(i);r||(r=[],t.set(i,r)),r.push(n)}return t}function _H(e,t){let n=new Map;for(let i of t)for(let r of e.get(i)??[])Mo(r)||n.set(r,(n.get(r)??0)+1);return n}function BH(e,t){let n=new Map;return OH(e,n,t),n}function OH(e,t,n){for(let i of $H(e,n))rC(e,t,i.from_file,i.to_file)}function $H(e,t){let n=t?"AND d1.relative_path LIKE ?":"",i=t?[`%${t}%`]:[];return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
|
|
433
|
+
FROM mentions m
|
|
434
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
435
|
+
JOIN documents d1 ON c.document_id = d1.id
|
|
436
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
437
|
+
JOIN (
|
|
438
|
+
SELECT m2.symbol_id, c2.document_id
|
|
439
|
+
FROM mentions m2
|
|
440
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
441
|
+
WHERE m2.role = 1
|
|
442
|
+
GROUP BY m2.symbol_id
|
|
443
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
444
|
+
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
445
|
+
WHERE d1.id != d2.id
|
|
446
|
+
AND m.role != 1
|
|
447
|
+
${e.pathExclusionsFor("d1","d2")}
|
|
448
|
+
${n}`,...i)}function jH(e,t,n={}){new U(e).scanSourceReferences({paths:n.paths??he(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},r=>{r.target.relativePath!==r.sourceFile&&(e.isIgnored(r.target.relativePath)||rC(e,t,r.sourceFile,r.target.relativePath))})}function rC(e,t,n,i){if(e.isIgnored(n)||e.isIgnored(i))return;let r=t.get(n);r||(r=new Set,t.set(n,r)),r.add(i)}function HH(e){return e.includes("types")||e.endsWith(".d.ts")}function UH(e,t,n){let i=$r(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.some(r=>r.isUsed)}function zH(e,t,n){let i=Ce(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.some(r=>r.used)}function GH(e,t,n){let i=Ce(e,t).filter(r=>r.sourcePath===n);return i.length>0&&i.every(r=>r.isTypeOnly===!0)}function KH(e){return e.endsWith(".vue")}function qH(e,t,n){let i=Ce(e,t).filter(r=>r.sourcePath===n);return i.length===0?!1:i.every(r=>r.kind==="side-effect"||r.kind==="namespace"&&r.usedMembers.length===0&&!r.used)}function Mo(e){let t=V(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||WH(Fo.basename(e)))}function WH(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 No(e,t){let{scope:n,minLoc:i=3,maxLoc:r=80,limit:o=30,includeLowConfidence:s=!1,scanLimit:a}=t??{},l=t?.semantic!==!1,c=new U(e),u=c.scopedDefinitions(n),d=oU(c,n),m={high:0,medium:1,low:2};return Ot({candidates:()=>VH(e,c,u,{minLoc:i,maxLoc:r}),orderCandidates:(f,p)=>de(p)-de(f)||f.relativePath.localeCompare(p.relativePath),scanLimit:a,profile:{name:"stale-abstractions"},prepare:f=>{let p=YH(f),g=JH(e,c,f,p,{semantic:l}),h=f.filter(S=>{if(g.incompleteSymbolIds.has(S.symbolId)||g.unavailableSymbolIds.has(S.symbolId)||c.hasSuppressionComment(S))return!1;let v=qa(e,S,g.consumerFileMap,p);return v.realConsumers.length<=1&&!v.transitivelyReachable&&sC(S,v.realConsumers.length,d)});return{...g,singletonBackedClassIds:QH(e,c,u,h,{semantic:l}),candidateIndex:p}},evaluate:(f,p)=>{if(p.incompleteSymbolIds.has(f.symbolId)||p.unavailableSymbolIds.has(f.symbolId)||c.hasSuppressionComment(f)||p.singletonBackedClassIds.has(f.symbolId))return null;let g=qa(e,f,p.consumerFileMap,p.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!sC(g.definition,g.realConsumers.length,d))return null;let h=XH(e,g);return!s&&h.confidence==="low"?null:h},orderResults:(f,p)=>m[f.confidence]-m[p.confidence]||p.loc-f.loc||f.file.localeCompare(p.file)||f.startLine-p.startLine,limit:o})}function VH(e,t,n,i){return n.filter(r=>r.isTypeLike&&de(r)>=i.minLoc).filter(r=>de(r)<=i.maxLoc).filter(r=>!e.isIgnored(r.relativePath)).filter(r=>!r.relativePath.endsWith(".d.ts")).filter(r=>V(r.relativePath)!=="test").filter(r=>!Ue(e,r.symbol,r.relativePath)).filter(r=>!sU(r.symbol))}function oC(e,t,n,i){return Qn(un(e,t).forDefinitions(n,{semantic:i.semantic,sourceFallback:i.sourceFallback}))}function JH(e,t,n,i,r){let o=oC(e,t,n,{semantic:!1,sourceFallback:!1}),s=n.filter(m=>{let f=qa(e,m,o,i);return f.realConsumers.length<=1&&!(f.realConsumers.length>0&&dd(m.relativePath))}),a=un(e,t).forDefinitions(s,{semantic:r.semantic,sourceFallback:!1}),l=new Set([...a.values()].filter(m=>m.semanticIncomplete).map(m=>m.definition.symbolId)),c=new Set([...a.values()].filter(m=>m.semanticUnavailable).map(m=>m.definition.symbolId)),u=r.semantic&&s.length>0?pi(o,Qn(a)):o,d=s.filter(m=>qa(e,m,u,i).realConsumers.length<=1);return{consumerFileMap:pi(u,oC(e,t,d,{semantic:!1,sourceFallback:!0})),incompleteSymbolIds:l,unavailableSymbolIds:c}}function YH(e){let t=new Map;for(let n of e){let i=t.get(n.relativePath);i||(i=new Map,t.set(n.relativePath,i));let r=re(n.symbol);r&&i.set(r,n)}return t}function qa(e,t,n,i){let o=[...n.get(t.symbolId)??new Set].filter(u=>u!==t.relativePath&&!e.isIgnored(u)),{realConsumers:s,barrelConsumers:a,importOnlyConsumers:l}=Da(e,t,o),c=aU(e,t,n,i);return{definition:t,realConsumers:s,barrelConsumers:a+l,transitivelyReachable:c}}function XH(e,t){let n=lC(e,t.definition.relativePath,t.definition.startLine),i=dd(t.definition.relativePath)?!0:lU(e,t.definition),{confidence:r,reason:o}=cU(t.realConsumers.length,n,i),s=ZH(t.realConsumers.length,n,i);return{symbol:t.definition.symbol,shortName:k(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:de(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:i,confidence:r,reason:o,actionTier:s.actionTier,stalenessKind:s.stalenessKind,recommendation:s.recommendation}}function ZH(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 QH(e,t,n,i,r){let o=tU(e,eU(n),i),s=o.map(u=>u.singleton);if(o.length===0)return new Set;let a=un(e,t).forDefinitions(s,{semantic:r.semantic,sourceFallback:!0}),l=Qn(a),c=new Set;for(let{singleton:u,classId:d}of o){let m=a.get(u.symbolId);(m?.semanticIncomplete||m?.semanticUnavailable||iU(e,u,l))&&c.add(d)}return c}function eU(e){let t=new Map;for(let n of e){let i=re(n.symbol);i&&t.set(aC(n.relativePath,i),n)}return t}function tU(e,t,n){let i=[];for(let r of n){let o=nU(e,t,r);o&&i.push({singleton:o,classId:r.symbolId})}return i}function nU(e,t,n){if(lC(e,n.relativePath,n.startLine)!=="class")return null;let i=re(n.symbol);if(!i)return null;let r=rU(e,n.relativePath,i);return r?t.get(aC(n.relativePath,r))??null:null}function iU(e,t,n){let i=re(t.symbol),r=n.get(t.symbolId);return!i||!r?!1:[...r].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!Eu(e,o,i))}function aC(e,t){return`${e}\0${t}`}function rU(e,t,n){let i=se(e,t);if(!i)return null;let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\bexport\\s+const\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*new\\s+${r}\\s*\\(`);return i.match(o)?.[1]??null}function oU(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function sU(e){let t=Ni(e);if("kind"in t)return!1;let n=t.descriptors;if(n.length<2)return!1;let i=n[n.length-1],r=n[n.length-2];return i?.suffix==="type"&&r?.suffix==="type"}function dd(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 sC(e,t,n){return!(dd(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function aU(e,t,n,i){let r=mm(e,t.relativePath),o=re(t.symbol);if(!o)return!1;let s=i.get(t.relativePath);if(!s)return!1;let a=[...r.get(o)??[]],l=new Set;for(;a.length>0;){let c=a.pop();if(l.has(c))continue;l.add(c);let u=s.get(c);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 r.get(c)??[])a.push(m)}return!1}function lC(e,t,n){let i=se(e,t);if(!i)return"other";let r=i.split(`
|
|
449
|
+
`),o=Math.max(0,n-2),s=Math.min(r.length-1,n+2);for(let a=o;a<=s;a++){let c=(r[a]??"").replace(/^\s*\/\/.*$/g,"");if(/\b(?:export\s+)?(?:abstract\s+)?class\s+\w/.test(c))return"class";if(/\b(?:export\s+)?interface\s+\w/.test(c))return"interface";if(/\b(?:export\s+)?type\s+\w/.test(c))return"type";if(/\b(?:export\s+)?(?:const\s+)?enum\s+\w/.test(c))return"enum"}return"other"}function lU(e,t){let n=se(e,t.relativePath);if(!n)return!1;let i=re(t.symbol);if(!i)return!1;let r=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${r}\\b`),s=n.split(`
|
|
450
|
+
`);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function cU(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 mr,extname as Wa}from"path";function ko(e,t){let{scope:n,maxLoc:i=15,limit:r=30,scanLimit:o}=t??{},s=new U(e),a=gU(s.fileDependencyGraph(n));return Ot({candidates:()=>mU(e,s,n,i),orderCandidates:Xs,scanLimit:o,profile:{name:"wrapper-candidates"},prepare:l=>({...uU(e,s,l,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(l,c)=>dU(e,s,l,c),orderResults:(l,c)=>c.callerFanIn-l.callerFanIn||c.loc-l.loc,limit:r})}function uU(e,t,n,i){let r=un(e,t),o=Qn(r.forDefinitions(n,{semantic:!1,sourceFallback:!1})),s=[];i.semantic&&$("wrapper.semantic-candidates",()=>{s=n.filter(h=>md(e,t,h,o).length<=1)},()=>({symbols:n.length,semanticCandidates:s.length}));let a=r.forDefinitions(s,{semantic:!0,sourceFallback:!1}),l=Qn(a),c=new Set([...a.values()].filter(h=>h.semanticIncomplete).map(h=>h.definition.symbolId)),u=new Set([...a.values()].filter(h=>h.semanticUnavailable).map(h=>h.definition.symbolId)),d=l.size===0?o:pi(o,l),m=new Map(n.map(h=>[h.symbolId,h])),f=new Map;for(let h of n){let S=md(e,t,h,d);if(S.length>1||(f.set(h.symbolId,h),S.length!==1))continue;let v=S[0],y=cC(e,h.symbolId,v);if(!y)continue;let E=uC(t,e,v,h.symbol,y);E?.isFunctionLike&&m.has(E.symbolId)&&f.set(E.symbolId,m.get(E.symbolId))}let p=[...f.values()];return{callerFileMap:p.length===0?d:pi(d,Qn(r.forDefinitions(p,{semantic:!1,sourceFallback:!0}))),incompleteSymbolIds:c,unavailableSymbolIds:u}}function dU(e,t,n,i){if(i.incompleteSymbolIds.has(n.symbolId)||i.unavailableSymbolIds.has(n.symbolId))return null;let r=md(e,t,n,i.callerFileMap);if(r.length!==1)return null;let o=r[0],s=cC(e,n.symbolId,o);if(!s)return null;let a=uC(t,e,o,n.symbol,s);if(a&&ki(a.symbol))return null;let{fanIn:l,source:c}=fU(i.callerFileMap,i.reverseFanIn,o,a);if(c==="function"?l<=3:l<=5)return null;let u=yU(e,n,o,a);return{symbol:n.symbol,shortName:k(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:de(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?k(a.symbol):mr(o),callerFanIn:l,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function mU(e,t,n,i){return t.productionCallableDefinitions({scope:n,minLoc:2,maxLoc:i,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0}).filter(r=>!Vo(e,r))}function md(e,t,n,i){let r=mr(n.relativePath,Wa(n.relativePath)),o=[...i.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>mr(s,Wa(s))!==r).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return Da(e,n,o).realConsumers}function cC(e,t,n){return e.get(`SELECT c.start_line, c.end_line
|
|
451
|
+
FROM mentions m
|
|
452
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
453
|
+
JOIN documents d ON c.document_id = d.id
|
|
454
|
+
WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
|
|
455
|
+
LIMIT 1`,t,n)}function uC(e,t,n,i,r){let o=e.definitionsForFile(n),s=pU(t,n,i,r.start_line,r.end_line);return Ge(o,s)}function fU(e,t,n,i){if(i?.isFunctionLike){let r=[...e.get(i.symbolId)??[]].filter(o=>o!==i.relativePath);if(r.length>0)return{fanIn:r.length,source:"function"}}return{fanIn:hU(t,n),source:"file"}}function pU(e,t,n,i,r){let o=re(n);if(!o)return i;let s=Oi(e,t).get(o);if(!s||s.length===0)return i;for(let a of s)if(a>=i&&a<=r)return a;return i}function gU(e){let t=new Map;for(let[n,i]of e){t.has(n)||t.set(n,t.get(n)??0);for(let r of i)t.set(r,(t.get(r)??0)+1)}return t}function hU(e,t){let n=e.get(t)??0;if(n>0)return n;let i=mr(t,Wa(t)),r=0;for(let[o,s]of e)o!==t&&mr(o,Wa(o))===i&&s>r&&(r=s);return r}function yU(e,t,n,i){return $a(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:k(t.symbol)},{label:"caller name",value:i?.symbol?k(i.symbol):mr(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var bU=25e3,SU=2500,vU=2500;function CU(e){let t=mi(e);return t.symbols>=bU||t.documents>=SU?vU:void 0}function fd(e,t={}){let{scope:n}=t,i=CU(e),r=[],o=wi(e,{scope:n,...Oe.dead,scanLimit:i});for(let s of o.symbols)Ye(e,s.relativePath)||Ue(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&r.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of po(e,{scope:n,...Oe.isolated,scanLimit:i}))Ye(e,s.relativePath)||Ue(e,s.symbol,s.relativePath)||r.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of mo(e,{scope:n}))s.kind==="real"&&r.push(`cycle:${xU(s.path)}`);for(let s of bo(e,{scope:n,...Oe.similar,scanLimit:i}))r.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of Lo(e,{scope:n,...Oe.duplicateBodies,scanLimit:i}))r.push(`duplicate-bodies:${s.hash}:${s.functions.map(a=>a.symbol).sort().join("|")}`);for(let s of Ro(e,{scope:n,...Oe.extract,scanLimit:i}))r.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of ko(e,{scope:n,...Oe.wrappers,scanLimit:i}))r.push(`wrapper:${s.file}:${s.shortName}`);for(let s of Do(e,{scope:n,...Oe.passthroughs,scanLimit:i}))r.push(`passthrough:${s.file}:${s.shortName}`);for(let s of No(e,{scope:n,...Oe.stale,scanLimit:i}))r.push(`stale:${s.file}:${s.shortName}`);for(let s of Ao(e,{scope:n,...Oe.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY}).results)s.kind!=="architecture-violation"&&r.push(`drift:${s.kind}:${s.file}:${s.dep}`);return r.push(...fu(fo(e,{scope:n}))),[...new Set(r.map(cd))].sort()}function xU(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 RU(e,t={}){let n=fd(e,{scope:t.scope}),i=ud(e,t.path);return tm(i,{version:1,findings:n},{spacing:2,trailingNewline:!0}),{path:i,findingCount:n.length}}function EU(e,t={}){return iC(e,fd(e,{scope:t.scope}),{path:t.path})}function wU(e,t={}){let{scope:n,limit:i=30,scanLimit:r}=t,o=new U(e);return Ot({candidates:()=>o.productionCallableDefinitions({scope:n,files:t.files,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}),filterCandidate:s=>IU(s.relativePath),scanLimit:r,profile:{name:"unused-params"},evaluate:s=>{let a=ee(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 l=Oi(e,s.relativePath),c=[];for(let u=a.params.length-1;u>=0;u--){let d=a.params[u];if(d.name===""||d.name.startsWith("_")||LU(l.get(d.name),a.paramsEndLine,a.endLine))break;c.unshift(d.name)}return c.length===0?null:{symbol:s.symbol,shortName:k(s.symbol),file:s.relativePath,startLine:s.startLine,endLine:s.endLine,paramCount:a.paramCount,unusedTrailing:c}},orderResults:(s,a)=>a.unusedTrailing.length-s.unusedTrailing.length||s.file.localeCompare(a.file)||s.startLine-a.startLine,limit:i})}function IU(e){let t=ye(e);return t==="typescript"||t==="tsx"||t==="javascript"}function LU(e,t,n){return e?e.some(i=>i>t&&i<=n):!1}var DU=new Set(Zt());function pd(e,t){let{scope:n,minLoc:i=10,limit:r=30,scanLimit:o}=t??{},s=new U(e),a=t?.semantic!==!1,l=dC(a,new Set,new Set);return{rows:Ot({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:i,requireFunctionLikeSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,filterCandidate:PU,profile:{name:"complexity-hotspots"},prepare:u=>{let d=FU(e,u);(a?kt(e):null)?.materializeReferences(u,{prefetchCallees:!0});let f=Qt(e,u,{semantic:a,semanticEvidence:pe}),p=s.calleeEvidenceMap(u,{semantic:a}),g=new Set([...f.incompleteSymbolIds,...p.incompleteSymbolIds]),h=new Set([...f.unavailableSymbolIds,...p.unavailableSymbolIds]);l=dC(a,g,h);let S=new Map(u.map(v=>[v.symbolId,v]));return{callerMap:new Map([...f.rows].map(([v,y])=>[v,new Set(y.filter(E=>E.file!==S.get(v)?.relativePath).map(E=>E.file))])),calleeMap:p.rows,incompleteSymbolIds:g,unavailableSymbolIds:h,languageByFile:d,clojureCallableIds:MU(e,u,d),branchEstimates:Hv(e,u)}},evaluate:(u,d)=>d.incompleteSymbolIds.has(u.symbolId)||d.unavailableSymbolIds.has(u.symbolId)?null:TU(u,d,i),orderResults:(u,d)=>d.score-u.score||d.loc-u.loc,limit:r}),coverage:l}}function dC(e,t,n){let i=new Set([...t,...n]).size,r=e?t.size>0&&n.size>0?"incomplete-and-unavailable":t.size>0?"incomplete":n.size>0?"unavailable":"complete":"disabled";return{semanticEvidence:{enabled:e,status:r,incompleteSymbolCount:t.size,unavailableSymbolCount:n.size,excludedSymbolCount:i}}}function PU(e){return e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&DU.has(e.kind):!0}function TU(e,t,n){if(t.languageByFile.get(e.relativePath)==="clojure"&&!t.clojureCallableIds.has(e.symbolId))return null;let i=e.endLine-e.startLine+1;if(i<n)return null;let r=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 f=`${m.symbol}|${m.file}`;s.add(f),m.file!==e.relativePath&&a.add(f)}let l=a.size,c=s.size,u=t.branchEstimates.get(e.symbolId)??{branches:0,estimateBasis:"regex-fallback"},d=u.branches+1;return{symbol:e.symbol,shortName:k(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:i,fanIn:r,fanOut:l,calleeCount:c,branches:u.branches,estimateBasis:u.estimateBasis,score:Math.round(i/50*(r/5)*Math.max(l/5,1)*Math.max(d/5,1)*100)/100}}function FU(e,t){let n=[...new Set(t.map(o=>o.relativePath))];if(n.length===0)return new Map;let i=n.map(()=>"?").join(", "),r=e.all(`SELECT relative_path, language
|
|
456
|
+
FROM documents
|
|
457
|
+
WHERE relative_path IN (${i})`,...n);return new Map(r.map(o=>[o.relative_path,o.language?.toLowerCase()??null]))}function MU(e,t,n){let i=new Set,r=new Map;for(let o of t){if(n.get(o.relativePath)!=="clojure")continue;let s=r.get(o.relativePath);s||(s=new Set((ee(e,o.relativePath)?.callables??[]).map(a=>`${a.name}:${a.startLine}`)),r.set(o.relativePath,s)),s.has(`${o.leaf}:${o.startLine}`)&&i.add(o.symbolId)}return i}import{readdirSync as AU}from"fs";import{basename as NU,join as mC}from"path";function kU(e,t,n={}){let i=new Set(e),r=new Set(t),o=[...r].filter(a=>!i.has(a)).sort(),s=n.allowExtra?[]:[...i].filter(a=>!r.has(a)).sort();return{missing:o,extra:s}}function _U(e,t){let n=BU(e,t.file,t.keys);if(!n.ok)return{name:t.name,file:t.file,status:"unavailable",missing:[],extra:[],unavailableReason:n.reason};let i=zU(e.config.projectRoot,t.mustEqual),r=kU(n.keys,i,{allowExtra:t.allowExtra??!1}),o=r.missing.length>0||r.extra.length>0?"violated":"ok";return{name:t.name,file:t.file,status:o,missing:r.missing,extra:r.extra}}function pC(e,t){return t.map(n=>_U(e,n))}function BU(e,t,n){return n.type==="markdown-list"?UU(e,t,n.marker):OU(e,t,n)}function OU(e,t,n){if(!se(e,t))return{ok:!1,reason:`file not found: ${t}`};let r=ye(t);if(!r)return{ok:!1,reason:`unsupported file type for ${n.type} extraction: ${t}`};let o=ae(e,t);if(!o)return{ok:!1,reason:`tree-sitter parser unavailable for ${r} (${t}) \u2014 contract skipped, not silently passed`,disclosedUnavailable:{language:r,reason:"parser-unavailable"}};let s=n.type==="object-literal-keys"?$U(o,n.identifier):HU(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 gC(e){let t=e.childForFieldName("value");return t?t.type==="as_expression"||t.type==="satisfies_expression"?t.namedChild(0):t:null}function $U(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let r=gC(n);if(r?.type==="object")return jU(r)}return null}function jU(e){let t=new Set;for(let n of e.namedChildren)if(n.type==="pair"){let i=n.childForFieldName("key");i&&t.add(hC(i.text))}else n.type==="shorthand_property_identifier"&&t.add(n.text);return[...t].sort()}function HU(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let r=gC(n);if(r?.type!=="array")continue;let o=new Set;for(let s of r.namedChildren)s.type==="string"&&o.add(hC(s.text));return[...o].sort()}return null}function hC(e){return e.length>=2&&(e[0]==="'"&&e.endsWith("'")||e[0]==='"'&&e.endsWith('"'))?e.slice(1,-1):e}function UU(e,t,n){let i=se(e,t);if(!i)return{ok:!1,reason:`file not found: ${t}`};let r=yC(i,n);return r===null?{ok:!1,reason:`no <!-- BEGIN GENERATED ${n} --> ... <!-- END GENERATED ${n} --> block in ${t}`}:{ok:!0,keys:bC(r)}}function yC(e,t){let n=He(t),r=new RegExp(`<!--\\s*BEGIN GENERATED ${n}\\s*-->([\\s\\S]*?)<!--\\s*END GENERATED ${n}\\s*-->`).exec(e);return r?r[1]:null}function bC(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 zU(e,t){switch(t.type){case"top-level-dirs":return fC(mC(e,t.path));case"file-glob":return[...new Set(Ra(e,t.pattern).map(n=>NU(n)))].sort();case"registered-commands":return GU(e);case"builtin-skills":return fC(mC(e,"skills"))}}function fC(e){let t;try{t=AU(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort()}function GU(e){let t;try{t=nt(e,"docs/COMMAND_REFERENCE.md",{maxBytes:8*1024*1024,inputKind:"generated command reference"})}catch(i){if(!St(i))throw i;return[]}let n=yC(t,"COMMAND REFERENCE");return n?bC(n):[]}function Mn(e){return e.scoreCount??e.count}function CC(e){let t=JU(e),{breakdown:n,pressure:i}=YU(e),r=vC(n,"risk"),o=vC(n,"hygiene"),s=KU(e),a=[...e.warnings];e.complexity.coverage.semanticEvidence.excludedSymbolCount>0&&a.push(`Complexity scoring excluded ${e.complexity.coverage.semanticEvidence.excludedSymbolCount} symbol(s) with incomplete or unavailable compiler evidence.`);let l=e.evidenceCoverage.filter(c=>c.semanticEvidence.status!=="complete"&&c.semanticEvidence.status!=="disabled");return l.length>0&&a.push(`Compiler-resolved evidence was incomplete or unavailable in health phase(s): ${l.map(c=>c.phase).join(", ")}.`),{score:Math.min(r,o),riskScore:r,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:Mn(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:Mn(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:Mn(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:qU(e),validation:VU(e),suppressions:e.suppressions,actions:t,pressure:i,topComplexity:e.complexity.top,coverage:s,warnings:a.length>0?a:void 0}}function KU(e){let t=e.complexity.coverage.semanticEvidence.status;return{status:e.evidenceCoverage.some(i=>i.semanticEvidence.status!=="complete"&&i.semanticEvidence.status!=="disabled")?"incomplete":t==="disabled"?"semantic-disabled":t==="complete"?"complete":"incomplete",complexity:e.complexity.coverage,phases:e.evidenceCoverage}}function qU(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:WU(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 WU(e){let t=e.gitEvidence?.fileStats;return t?e.complexity.top.map(n=>{let i=n.file?t[n.file]?.changes??0:0;return{...n,changes:i,weighted:fn(n.score*Math.log2(1+i))}}).sort((n,i)=>i.weighted-n.weighted):null}function VU(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??[]},i=new Set(Object.values(n).flat()),r=0,o=0,s=0;for(let[u,d]of Object.entries(t))i.has(u)?r+=d.fixChanges:(o+=d.fixChanges,s+=1);let a=i.size>0?fn(r/i.size):0,l=s>0?fn(o/s):0,c={};for(let[u,d]of Object.entries(n)){let m=new Set(d);if(m.size===0)continue;let f=0;for(let g of m)f+=t[g]?.fixChanges??0;let p=fn(f/m.size);c[u]={flaggedFiles:m.size,fixDensity:p,lift:l>0?fn(p/l):null}}return{flaggedFiles:i.size,flaggedFixDensity:a,baselineFixDensity:l,ratio:i.size>0&&l>0?fn(a/l):null,byCategory:c,validationBasis:{method:"subject-regex",commitsScanned:e.gitEvidence?.commitsScanned??0}}}function fn(e){return Math.round(e*100)/100}function xC(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function Va(e,t="existing shared infrastructure discount"){let n=Mn(e);return Math.abs(n-e.count)<.01?"":` (${xC(n)} score-weighted after ${t})`}function _o(e,t){let n=Mn(e),i=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?i:`${i} (${xC(n)} score-weighted)`}function JU(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",evidence:"graph-fact",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",description:`${e.isolated.count} symbols completely disconnected from the codebase graph`,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",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",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${Va(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${Va(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",description:`${e.wrappers.count} single-consumer symbols${Va(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",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 r=[];e.stale.unused>0&&r.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&r.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",evidence:"heuristic",description:`${r.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 r=[];e.drift.unusedImports>0&&r.push(`${e.drift.unusedImports} unused imports`),e.drift.architectureViolations>0&&r.push(`${e.drift.architectureViolations} declared architecture violations`),t.push({category:"Structural drift",evidence:"heuristic",description:`${r.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 \`codebaseiq 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 r=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`+Va({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:e.gitEvidence.hiddenCoupling.scoreCount},"broad/stale-history discount")+(r?` (e.g. ${r.fileA} \u2194 ${r.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},i={low:3,medium:2,high:1};return t.sort((r,o)=>{let s=n[r.impact]*i[r.effort];return n[o.impact]*i[o.effort]-s}),t}var SC={"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 vC(e,t){let n=e.filter(i=>i.kind===t).reduce((i,r)=>i+r.points,0);return Math.max(0,Math.min(100,100-n))}function YU(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),i=[],r=[],o=(R,C,L)=>{C>0&&i.push({axis:R,points:C,detail:L,kind:SC[R]??"hygiene"})},s=(R,C,L,I,x,P,_)=>{let D=Math.max(I,1);if(L<=D)return;let T=L/D,A=Math.min(x,Math.ceil(Math.log2(T)*P));if(A<=0)return;let W=SC[R]??"hygiene";r.push({axis:R,category:C,kind:W,count:L,threshold:fn(D),ratio:fn(T),extraPenalty:A}),o(R,A,`${L} ${_} exceed pressure threshold ${fn(D)} (${fn(T)}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 l=e.isolated.count/n;o("isolated",Math.min(10,Math.round(l*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 c=e.similarCount/n*1e3;o("similar",Math.min(10,Math.round(c)),`${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 f=Mn(e.reactHookCandidates),p=f/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(p)),_o(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 S=Mn(e.vueComposableCandidates),v=S/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(v)),_o(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 E=Mn(e.wrappers);o("wrappers",Math.min(3,E),_o(e.wrappers,"wrapper candidate(s)"));let w=Mn(e.passthroughs);o("passthroughs",Math.min(3,w),_o(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 b=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(b*50)),`${e.drift.direct} direct drift finding(s); ${e.drift.signal} signal drift finding(s)`),o("complexity",Math.min(5,e.complexity.extremeCount*2),`${e.complexity.extremeCount} extreme complexity hotspot(s)`),e.gitEvidence){let R=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(R/10)),_o({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:R},"co-changing pair(s) without a structural link"))}if(s("cycles-pressure","Circular dependencies",e.realCycleCount,3,10,3,"cycle(s)"),s("complexity-pressure","Extreme complexity",e.complexity.extremeCount,3,5,2,"extreme complexity hotspot(s)"),e.gitEvidence){let R=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",R,50,10,4,"score-weighted co-changing pair(s)")}return s("similar-pressure","Similar functions",e.similarCount,Math.max(50,n*.01),8,4,"similar function pair(s)"),s("duplicate-bodies-pressure","Duplicate function bodies",e.duplicateBodies.count,Math.max(20,n*.005),8,4,"exact duplicate small-body group(s)"),s("twin-drift-pressure","Drifted twin implementations",e.twinDrift.count,Math.max(20,n*.005),8,4,"drifted twin implementation group(s)"),s("react-component-duplicates-pressure","Duplicated React components",e.reactComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated React component pair(s)"),s("react-hook-candidates-pressure","Duplicated React hook behavior",f,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",S,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",E,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",w,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:i,pressure:r}}import{getHeapStatistics as XU}from"v8";var ZU=64*1024*1024;function gd(){let e=globalThis.gc;if(!e)return;let t=XU();t.heap_size_limit-t.used_heap_size<ZU||e()}var QU=50,ez=25e3,tz=2500,RC=2500,EC=50,nz=10,Ja=["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"],iz={overview:(e,t,n,i)=>({phase:"overview",statsResult:i,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:lz(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:cz(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:uz(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:dz(e,t,n)}),"duplicate-bodies":(e,t,n)=>({phase:"duplicate-bodies",duplicateBodies:fz(e,t,n)}),"twin-drift":(e,t,n)=>({phase:"twin-drift",twinDrift:pz(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:gz(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:hz(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:yz(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:bz(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:Sz(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:vz(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:mz(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:Cz(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:xz(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:Rz(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:Lz(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:Dz(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:Ez(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:wz(e,n)}),"coverage-contracts":(e,t,n)=>({phase:"coverage-contracts",coverageContracts:Iz(e,n)})};function hd(e,t,n={}){return rz(e,[t],n)[0]}function rz(e,t,n={}){return oz(e,n.full!==!1,(i,r)=>{let o={...r,releaseCachesBetweenPhases:!1};return t.map(s=>az(e,s,n.scope,o,i))})}function oz(e,t,n){let i=mi(e),r=Pz(i,t);try{return n(i,r)}finally{uu(e,{semanticProvider:!0}),gd()}}function yd(e){return CC(sz(e))}function sz(e){let t=je(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,evidenceCoverage:e.map(i=>({phase:i.phase,semanticEvidence:i.evidenceCoverage})),dead:je(e,"dead").dead,isolated:je(e,"isolated").isolated,realCycleCount:je(e,"cycles").realCycleCount,similarCount:je(e,"similar").similarCount,duplicateBodies:je(e,"duplicate-bodies").duplicateBodies,twinDrift:je(e,"twin-drift").twinDrift,reactComponentDuplicates:je(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:je(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:je(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:je(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:je(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:je(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:je(e,"extract-candidates").extractCount,wrappers:je(e,"wrapper-candidates").wrappers,passthroughs:je(e,"passthrough-candidates").passthroughs,stale:je(e,"stale-abstractions").stale,drift:je(e,"drift").drift,complexity:je(e,"complexity-hotspots").complexity,gitEvidence:wC(e,"git-evidence")?.gitEvidence??null,suppressions:wC(e,"suppressions")?.suppressions??null,coverageContracts:je(e,"coverage-contracts").coverageContracts}}function wC(e,t){return e.find(n=>n.phase===t)}function je(e,t){let n=e.find(i=>i.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function az(e,t,n,i,r){pp(e);let o=iz[t](e,n,i,r),s=gp(e),a=s.incompleteSymbolIds.size,l=s.unavailableSymbolIds.size,c=i.semantic?a>0&&l>0?"incomplete-and-unavailable":a>0?"incomplete":l>0?"unavailable":"complete":"disabled";return{...o,evidenceCoverage:{enabled:i.semantic,status:c,incompleteSymbolCount:a,unavailableSymbolCount:l}}}function lz(e,t,n){return $e(e,n,"dead",()=>{let i=wi(e,{scope:t,...Oe.dead,scanLimit:n.candidateScanLimit,semantic:n.semantic});return Ya(Mz(e,i.symbols))})}function cz(e,t,n){return $e(e,n,"isolated",()=>{let i=po(e,{scope:t,...Oe.isolated,scanLimit:n.candidateScanLimit,semantic:n.semantic});return Ya(Az(e,i))})}function uz(e,t,n){return $e(e,n,"cycles",()=>mo(e,{scope:t}).filter(r=>r.kind==="real").length)}function dz(e,t,n){let i=$e(e,n,"similar",()=>vu(e,{scope:t,...Oe.similar,scanLimit:n.candidateScanLimit,semantic:n.semantic}));return Math.min(i,n.candidateResultLimit)}function mz(e,t,n){return $e(e,n,"extract-candidates",()=>Ro(e,{scope:t,...Oe.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}).length)}function fz(e,t,n){return $e(e,n,"duplicate-bodies",()=>{let i=Lo(e,{scope:t,...Oe.duplicateBodies,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),r=new Set,o=0;for(let s of i)for(let a of s.functions.slice(1))r.add(a.file),o+=a.loc;return{count:i.length,loc:o,files:[...r]}})}function pz(e,t,n){return $e(e,n,"twin-drift",()=>{let i=Oa(e,{scope:t,...Oe.twinDrift,scanLimit:n.candidateScanLimit}).filter(s=>s.relationship==="divergent"||s.relationship==="identical"),r=new Set,o=0;for(let s of i)for(let a of s.members)r.add(a.file),o+=a.loc;return{count:i.length,loc:o,files:[...r].sort()}})}function gz(e,t,n){return $e(e,n,"react-component-duplicates",()=>{let i=So(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return bd(i)})}function hz(e,t,n){return $e(e,n,"react-hook-candidates",()=>{let i=vo(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return DC(i,kz)})}function yz(e,t,n){return $e(e,n,"react-large-component-pressure",()=>{let i=Cu(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Nz(i)})}function bz(e,t,n){return $e(e,n,"vue-component-duplicates",()=>{let i=Co(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return bd(i)})}function Sz(e,t,n){return $e(e,n,"vue-composable-candidates",()=>{let i=xo(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return DC(i,_z)})}function vz(e,t,n){return $e(e,n,"vue-large-view-pressure",()=>{let i=xu(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return Ya(i)})}function Cz(e,t,n){return $e(e,n,"wrapper-candidates",()=>{let i=ko(e,{scope:t,...Oe.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return LC(i,Bz)})}function xz(e,t,n){return $e(e,n,"passthrough-candidates",()=>{let i=Do(e,{scope:t,...Oe.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return LC(i,Oz)})}function Rz(e,t,n){return $e(e,n,"stale-abstractions",()=>{let i=No(e,{scope:t,...Oe.stale,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}),r=i.filter(o=>o.consumers===0).length;return{count:i.length,loc:i.reduce((o,s)=>o+s.loc,0),files:[...new Set(i.map(o=>o.file))],unused:r,singleUse:i.length-r}})}function Ez(e,t){return $e(e,t,"git-evidence",()=>{let n=Wt(e,{historyMode:t.gitHistoryMode}),i=n.fileChurn();if(!i)return null;let r=n.commitHistory(),o=wo(e,void 0,{limit:t.candidateResultLimit,historyMode:t.gitHistoryMode}),s={};for(let[a,l]of i)s[a]={changes:l.changes,fixChanges:l.fixChanges};return{amplification:n.changeAmplification(),hiddenCoupling:{pairCount:o.findings.length,scoreCount:Sd(o.findings.reduce((a,l)=>a+IC(l),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:IC(a),subjectContext:a.subjectContext}))},fileStats:s,commitsScanned:r?.commits.length??0}})}function wz(e,t){return $e(e,t,"suppressions",()=>{let n=Ua(e);return{total:n.total,byCategory:{...n.byCategory}}})}function Iz(e,t){return $e(e,t,"coverage-contracts",()=>{let n=e.config.coverageContracts??[],r=pC(e,n).filter(o=>o.status!=="ok");return{count:r.length,loc:0,files:[...new Set(r.map(o=>o.file))].sort()}})}function Lz(e,t,n){return $e(e,n,"drift",()=>{let i=Ao(e,{scope:t,...Oe.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY,semantic:n.semantic}),r=i.results.filter(a=>a.kind!=="pattern-deviation"),o=r.filter(a=>a.actionTier==="direct").length,s=r.length-o;return{count:r.length,unusedImports:i.unusedImports,architectureViolations:i.architectureViolations,layerViolations:i.layerViolations,direct:o,signal:s}})}function Dz(e,t,n){return $e(e,n,"complexity-hotspots",()=>{let i=pd(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return{top:i.rows.slice(0,5).map(r=>({symbol:r.shortName,score:r.score,file:r.file})),extremeCount:i.rows.filter(r=>r.score>QU).length,coverage:i.coverage}})}function Pz(e,t){let n=e.symbols>=ez||e.documents>=tz,i=t?Number.POSITIVE_INFINITY:EC,r=t?Number.POSITIVE_INFINITY:nz;return!n||t?{candidateScanLimit:void 0,candidateResultLimit:i,complexityResultLimit:r,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:RC,candidateResultLimit:i,complexityResultLimit:r,semantic:!1,gitHistoryMode:"bounded",releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${RC} symbols and reported their top ${EC} findings. Enable full mode for unbounded candidate counts.`]}}function Tz(e,t){t.releaseCachesBetweenPhases&&(uu(e),gd())}function $e(e,t,n,i){Fz(n);try{return i()}finally{Tz(e,t)}}function Fz(e){process.env.CODEBASEIQ_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function Mz(e,t){return t.filter(n=>!Ye(e,n.relativePath)&&!Ue(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function Az(e,t){return t.filter(n=>!Ye(e,n.relativePath)&&!Ue(e,n.symbol,n.relativePath))}function Ya(e){let t=new Set;for(let n of e){let i=n.relativePath??n.file;i&&t.add(i)}return{count:e.length,loc:e.reduce((n,i)=>n+i.loc,0),files:[...t]}}function LC(e,t){return{...Ya(e),scoreCount:Sd(e.reduce((i,r)=>i+t(r),0))}}function Nz(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,i)=>n+i,0),files:[...t.keys()]}}function bd(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,i)=>n+i,0),files:[...t.keys()]}}function DC(e,t){return{...bd(e),scoreCount:Sd(e.reduce((i,r)=>i+t(r),0))}}function kz(e){let t=e.sharedHooks.length>0,n=PC({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:TC(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function _z(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=PC({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:TC(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function PC(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!MC.has(FC(t))).length+Math.min(e.functions.length,3)}function TC(e,t,n){let i=[...e,...t,...n].map(FC);return i.length>0&&i.every(r=>MC.has(r))}function FC(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function Bz(e){return e.actionTier==="signal"?.25:1}function Oz(e){return e.actionTier==="signal"?.25:1}function IC(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 Sd(e){return Math.round(e*100)/100}var MC=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 $z(e,t,n,i={}){let r=Su(e,t,n,i);return r?{symbolA:r.symbolA,symbolB:r.symbolB,similarity:r.similarity,sharedCallees:r.sharedEvidence,uniqueToA:r.uniqueToA,uniqueToB:r.uniqueToB,consolidationStrategy:r.consolidationStrategy}:null}function jz(e,t,n={}){let i=co(e,t,{families:["dataflow"],...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.maxEdges!==void 0?{maxEdges:n.maxEdges}:{}});return{kind:"value-flow",targets:i.targets,edges:i.edges,coverage:{status:i.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:i.coverage}}}var Hz=/:\d+(?:-\d+)?$/u;function Uz(e,t,n={}){let i=n.direction??"backward",r=n.maxDepth??3;if(!Number.isSafeInteger(r)||r<0)throw new RangeError(`Dependence-slice depth must be a non-negative safe integer; received ${r}.`);let o=Hz.test(t),s=co(e,o?{locations:[t]}:{symbols:[t]},{families:["execution","runtime","dataflow","ownership"],maxDepth:r+1,maxEdges:n.maxEdges??200}),a=new Set(s.targets.flatMap(d=>d.nodeIds)),l=new Set(a),c=new Map;AC(s.edges,l,c,0);for(let d=1;d<=r;d+=1){let m=[];for(let f of s.edges)if(i==="backward"?l.has(f.to.id):l.has(f.from.id)){let p=i==="backward"?f.from.id:f.to.id;if(l.has(p))continue;m.push(p),c.set(f.id,d)}if(m.length===0)break;for(let f of m)l.add(f);AC(s.edges,l,c,d)}let u=s.edges.filter(d=>l.has(d.from.id)&&l.has(d.to.id)).filter(d=>c.has(d.id)||d.family==="ownership").map(d=>({...d,traversalDepth:c.get(d.id)??0,supporting:d.family!=="dataflow"&&!zz(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:i,criterion:t,targets:s.targets,nodeIds:[...l].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 AC(e,t,n,i){let r=!0;for(;r;){r=!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,i),r=!0)}}function zz(e){return e.semanticFamily==="control"&&e.sourceKind==="control-dependence"}function Gz(e,t={}){let{scope:n,limit:i}=t,r=new U(e),o=Qz([...Kz(e,n),...Vz(e,r,n)]);return eG(o),i?o.slice(0,i):o}function Kz(e,t){let n=[];for(let i of qz(e,t)){if(e.isIgnored(i.barrel_path)||e.isIgnored(i.original_path)||yc(e,i.barrel_path)||se(e,i.barrel_path)&&Yo(e,i.barrel_path).length===0)continue;let r=Wz(e,i),o=r?.barrel_consumers??0,s=r?.direct_consumers??0;o!==0||s!==0||n.push({barrelFile:i.barrel_path,symbol:i.symbol,shortName:k(i.symbol),originalFile:i.original_path,barrelConsumers:o,directConsumers:s,...kC(e,i.barrel_path)})}return n}function qz(e,t){let n=t?"AND barrel_d.relative_path LIKE ?":"",i=t?[`%${t}%`]:[];return e.all(`WITH barrel_refs AS MATERIALIZED (
|
|
458
|
+
SELECT DISTINCT
|
|
459
|
+
barrel_d.id AS barrel_doc_id,
|
|
460
|
+
barrel_d.relative_path AS barrel_path,
|
|
461
|
+
m.symbol_id
|
|
462
|
+
FROM documents barrel_d
|
|
463
|
+
JOIN chunks c ON c.document_id = barrel_d.id
|
|
464
|
+
JOIN mentions m ON m.chunk_id = c.id
|
|
465
|
+
WHERE m.role != 1
|
|
466
|
+
AND (barrel_d.relative_path LIKE '%/index.ts'
|
|
467
|
+
OR barrel_d.relative_path LIKE '%/index.js'
|
|
468
|
+
OR barrel_d.relative_path = 'index.ts'
|
|
469
|
+
OR barrel_d.relative_path = 'index.js')
|
|
470
|
+
${e.pathExclusionsFor("barrel_d")}
|
|
471
|
+
${n}
|
|
472
|
+
),
|
|
473
|
+
sym_def AS MATERIALIZED (
|
|
474
|
+
SELECT m2.symbol_id, c2.document_id
|
|
475
|
+
FROM barrel_refs br
|
|
476
|
+
-- Keep the bounded barrel-symbol set on the outer side. An ordinary
|
|
477
|
+
-- JOIN lets SQLite scan every definition mention before applying the
|
|
478
|
+
-- barrel-symbol bloom filter on large indexes.
|
|
479
|
+
CROSS JOIN mentions m2 ON m2.symbol_id = br.symbol_id
|
|
480
|
+
AND m2.role = 1
|
|
481
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
482
|
+
GROUP BY m2.symbol_id
|
|
483
|
+
)
|
|
484
|
+
SELECT DISTINCT
|
|
485
|
+
br.barrel_doc_id,
|
|
486
|
+
br.barrel_path,
|
|
487
|
+
gs.id AS symbol_id,
|
|
488
|
+
gs.symbol AS symbol,
|
|
489
|
+
orig_d.id AS original_doc_id,
|
|
490
|
+
orig_d.relative_path AS original_path
|
|
491
|
+
FROM barrel_refs br
|
|
492
|
+
JOIN global_symbols gs ON br.symbol_id = gs.id
|
|
493
|
+
JOIN sym_def ON sym_def.symbol_id = gs.id
|
|
494
|
+
JOIN documents orig_d ON sym_def.document_id = orig_d.id
|
|
495
|
+
WHERE orig_d.id != br.barrel_doc_id
|
|
496
|
+
${e.pathExclusionsFor("orig_d")}
|
|
497
|
+
${e.symbolNoiseFor("gs")}
|
|
498
|
+
-- Only function-level symbols (ending with ().), not module-level
|
|
499
|
+
AND gs.symbol LIKE '%().'
|
|
500
|
+
ORDER BY br.barrel_path, gs.symbol`,...i)}function Wz(e,t){return e.get(`SELECT
|
|
501
|
+
SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
|
|
502
|
+
SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
|
|
503
|
+
FROM (
|
|
504
|
+
SELECT
|
|
505
|
+
consumer_d.id AS consumer_doc_id,
|
|
506
|
+
MAX(CASE WHEN EXISTS (
|
|
507
|
+
SELECT 1
|
|
508
|
+
FROM mentions barrel_m
|
|
509
|
+
JOIN chunks barrel_c ON barrel_m.chunk_id = barrel_c.id
|
|
510
|
+
WHERE barrel_c.document_id = consumer_d.id
|
|
511
|
+
AND barrel_m.role != 1
|
|
512
|
+
AND barrel_m.symbol_id IN (
|
|
513
|
+
SELECT m2.symbol_id
|
|
514
|
+
FROM mentions m2
|
|
515
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
516
|
+
WHERE c2.document_id = ?
|
|
517
|
+
AND m2.role != 1
|
|
518
|
+
)
|
|
519
|
+
) THEN 1 ELSE 0 END) AS uses_barrel
|
|
520
|
+
FROM mentions ref_m
|
|
521
|
+
JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
|
|
522
|
+
JOIN documents consumer_d ON ref_c.document_id = consumer_d.id
|
|
523
|
+
WHERE ref_m.symbol_id = ?
|
|
524
|
+
AND ref_m.role != 1
|
|
525
|
+
AND consumer_d.id != ?
|
|
526
|
+
AND consumer_d.id != ?
|
|
527
|
+
${e.pathExclusionsFor("consumer_d")}
|
|
528
|
+
GROUP BY consumer_d.id
|
|
529
|
+
)`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function Vz(e,t,n){let i=[],r=Zz(e);for(let o of Jz(e,n))_C(r,o,o)>0||i.push(...Yz(e,t,o,r));return i}function Jz(e,t){return he(e,{scope:t,includeIgnored:!1}).filter(n=>Yo(e,n).length>0||br(e,n).length>0)}function Yz(e,t,n,i){let r=Yo(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>NC(e,t,n,s.sourcePath,i,[Xz(s.specifier)])),o=br(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>NC(e,t,n,s.sourcePath,i,s.kind==="named"&&s.names.length>0?s.names:[s.kind==="star"?`* from ${s.sourcePath}`:`* namespace from ${s.sourcePath}`]));return[...r,...o]}function NC(e,t,n,i,r,o){let s=t.definitionsForFile(i);return o.map(a=>{let l=s.find(c=>c.leaf===a);return{barrelFile:n,symbol:l?.symbol??`source-reexport:${n}:${a}`,shortName:l?k(l.symbol):a,originalFile:i,barrelConsumers:0,directConsumers:_C(r,i,n),...kC(e,n)}})}function Xz(e){return e.split("::").at(-1)?.split("/").at(-1)?.replace(/\.[^.]+$/,"")??e}function kC(e,t){return En(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 Zz(e){let t=new Map;for(let n of he(e,{includeIgnored:!1}))for(let i of Ce(e,n)){if(!i.sourcePath)continue;let r=t.get(i.sourcePath)??new Set;r.add(n),t.set(i.sourcePath,r)}return t}function _C(e,t,n){let i=e.get(t);return i?i.size-(i.has(n)?1:0):0}function Qz(e){let t=new Set,n=[];for(let i of e){let r=`${i.barrelFile}|${i.symbol}|${i.originalFile}`;t.has(r)||(t.add(r),n.push(i))}return n}function eG(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function tG(e,t={}){let{samples:n=50,scope:i,maxDisagreements:r=5}=t,o=new U(e),s=nG(o.productionCallableDefinitions({scope:i,minLoc:2,requireFunctionLikeSymbol:!0}),n),a=iG(e,s);if(s.length===0||!a)return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let l={references:BC(),callees:BC()},c=[],u=0,d=a==="semantic"?ks(e,s):{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set},m=a==="semantic"?_s(e,s):{rows:new Map,incompleteSymbolIds:new Set,unavailableSymbolIds:new Set},f=a==="source"?sG(e,o,s):null;for(let p of s){let g=Xa(p,a==="semantic"?(d.rows.get(p.symbolId)??[]).map(R=>R.file):[...f?.referencesBySymbolId.get(p.symbolId)??[]]),h=Xa(p,a==="semantic"?(m.rows.get(p.symbolId)??[]).map(R=>R.file):[...f?.calleesBySymbolId.get(p.symbolId)??[]]),S=a!=="semantic"||!d.incompleteSymbolIds.has(p.symbolId)&&!d.unavailableSymbolIds.has(p.symbolId),v=a!=="semantic"||!m.incompleteSymbolIds.has(p.symbolId)&&!m.unavailableSymbolIds.has(p.symbolId);S&&v&&(u+=1);let y=Xa(p,On(e,p,{semanticEvidence:pe}).map(R=>R.file)),E=Xa(p,(o.calleeMap([p],{semantic:!1}).get(p.symbolId)??[]).map(R=>R.file)),w=vd(a,"references"),b=vd(a,"callees");S?OC(l.references,p,"references",y,g,w,c):l.references.skippedOracleUnavailable+=1,v?OC(l.callees,p,"callees",E,h,b,c):l.callees.skippedOracleUnavailable+=1}return c.sort((p,g)=>g.cheapOnly.length+g.oracleOnly.length-(p.cheapOnly.length+p.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?xd(u/s.length):0,oracleKind:a,scores:["references","callees"].map(p=>oG(p,l[p],a)),topDisagreements:c.slice(0,r)}}function BC(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0,skippedOraclePartial:0,skippedOracleUnavailable:0}}function nG(e,t){let n=[...e].sort((o,s)=>o.symbolId-s.symbolId);if(n.length<=t)return n;let i=n.length/t,r=[];for(let o=0;o<t;o++)r.push(n[Math.floor(o*i)]);return r}function iG(e,t){let n=t[0];if(!n)return null;if(Cd(e,n))return"source";try{if(kt(e).capability("semantic-references",n.relativePath).available)return"semantic"}catch{}return t.some(i=>Cd(e,i))?"source":null}function Xa(e,t){let n=new Set;for(let i of t)i!==e.relativePath&&n.add(i);return n}function OC(e,t,n,i,r,o,s){if(!o&&r.size===0){e.skippedOraclePartial+=1;return}e.comparedSymbols+=1,e.cheapTotal+=i.size,e.oracleTotal+=r.size;let a=[],l=[];for(let c of i)r.has(c)?e.agreed+=1:a.push(c);for(let c of r)i.has(c)||l.push(c);(a.length>0||l.length>0)&&s.push({symbol:k(t.symbol),question:n,cheapOnly:a,oracleOnly:l})}var rG={references:!0,callees:!1};function oG(e,t,n){let i=t.oracleTotal>0?t.agreed/t.oracleTotal:1,r=t.cheapTotal-t.agreed,o=vd(n,e);return{question:e,comparedSymbols:t.comparedSymbols,precision:o&&t.cheapTotal>0?xd(t.agreed/t.cheapTotal):null,recall:xd(i),unverified:r,skippedOraclePartial:t.skippedOraclePartial,skippedOracleUnavailable:t.skippedOracleUnavailable}}function vd(e,t){return e==="semantic"?rG[t]:!1}function Cd(e,t){return ye(t.relativePath)==="clojure"&&ee(e,t.relativePath)!==null}function sG(e,t,n){let i=new Map,r=new Map,o=n.filter(l=>Cd(e,l)),s=new Map;for(let l of o){let c=s.get(l.leaf)??[];c.push(l),s.set(l.leaf,c)}for(let l of t.sourceFiles()){if(ye(l)!=="clojure")continue;let c=ee(e,l);if(c)for(let u of c.fileIdentifiers)for(let d of s.get(u)??[])$C(i,d.symbolId,l)}let a=new Map;for(let l of t.scopedDefinitions()){if(ye(l.relativePath)!=="clojure")continue;let c=a.get(l.leaf)??[];c.push(l),a.set(l.leaf,c)}for(let l of o){let c=ee(e,l.relativePath);if(c){for(let u of c.callSites)if(!(u.line<l.startLine||u.line>l.endLine))for(let d of a.get(u.calleeLeaf)??[])$C(r,l.symbolId,d.relativePath)}}return{referencesBySymbolId:i,calleesBySymbolId:r}}function $C(e,t,n){let i=e.get(t);if(i){i.add(n);return}e.set(t,new Set([n]))}function xd(e){return Math.round(e*1e3)/1e3}var aG=new Set(Zt());function lG(e,t={}){let{scope:n,minLoc:i=1,limit:r,scanLimit:o,maxShapeFrequency:s=12}=t,a=t.semantic!==!1,l=dG(e,cG(e,{scope:n,minLoc:i,scanLimit:o}),{semantic:a,maxShapeFrequency:s}),c=fG(l);return r?c.slice(0,r):c}function cG(e,t){let n=ze(e,{scope:t.scope}).filter(i=>uG(i)&&!e.isIgnored(i.relativePath)).filter(i=>de(i)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((i,r)=>de(r)-de(i)||i.relativePath.localeCompare(r.relativePath)),Ae(n,t.scanLimit)}function uG(e){return!e.isFunctionLike||at(e.symbol)?!1:e.kind===null||aG.has(e.kind)}function dG(e,t,n){let i=[];for(let s of t){let a=gG(e,s,n);a&&i.push({signature:a,definition:s,fn:mG(s)})}let r=new Map;for(let s of i)r.set(s.signature,(r.get(s.signature)??0)+1);let o=new Map;for(let s of i){let a=pG(s.fn.loc),l=(r.get(s.signature)??0)>n.maxShapeFrequency,c=l?Qu(e,s.definition):null;if(l&&!c)continue;let u=l?`${s.signature}\0body\0${c}`:`${s.signature}\0band\0${a}`,d=o.get(u)??{signature:s.signature,locBand:a,exactBody:l,functions:[]};d.functions.push(s.fn),o.set(u,d)}return[...o.values()]}function mG(e){return{symbol:e.symbol,shortName:k(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:de(e)}}function fG(e){let t=[];for(let n of e)n.functions.length>=2&&t.push(n);return t.sort((n,i)=>{let r=i.functions.length-n.functions.length;if(r!==0)return r;let o=n.functions.reduce((a,l)=>a+l.loc,0);return i.functions.reduce((a,l)=>a+l.loc,0)-o}),t}function pG(e){return e<=5?"<=5":e<=20?"6-20":">20"}function gG(e,t,n){if(n.semantic){let o=Rp(e,t);if(o)return o}let i=hG(t.documentation),r=i?SG(i):null;return r||vG(yG(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function hG(e){return _i(Bi(e))}function yG(e,t,n,i,r){let o=se(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=xG(s,n,i,r);for(let l of a){let c=Math.min(s.length-1,Math.max(l,l+4)),u="";for(let d=l;d<=c;d+=1){let m=s[d]?.trim();if(m&&(u=u?`${u} ${m}`:m,bG(u)))return u}if(u&&u.includes("("))return u}return null}function bG(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||cm(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function SG(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 vG(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),i=n.indexOf("(");if(i===-1)return null;let r=n.slice(0,i),s=new RegExp(`\\b${He(t)}\\b`,"i").exec(r);s&&typeof s.index=="number"&&(r=r.slice(0,s.index)),r=r.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=CG(n.slice(i)).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 l=`${r?`${r} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return l.length>=3?l:null}function CG(e){let t=0,n=0,i=0,r=0,o=null,s=!1;for(let a=0;a<e.length;a+=1){let l=e[a];if(o){if(s){s=!1;continue}if(l==="\\"){s=!0;continue}l===o&&(o=null);continue}if(l==='"'||l==="'"||l==="`"){o=l;continue}if(l==="(")t+=1;else if(l===")")t=Math.max(0,t-1);else if(l==="[")i+=1;else if(l==="]")i=Math.max(0,i-1);else if(l==="<")r+=1;else if(l===">")r=Math.max(0,r-1);else if(l==="{"){if(t===0&&i===0&&r===0)return e.slice(0,a);n+=1}else if(l==="}")n=Math.max(0,n-1);else if(l==="="&&e[a+1]===">"&&t===0&&n===0&&i===0&&r===0)return e.slice(0,a)}return e}function xG(e,t,n,i){let r=He(i),o=new RegExp(`\\b${r}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${r}\\b`,"i"),a=[],l=new Set,c=Math.max(0,Math.min(t,e.length-1)),u=Math.max(c,Math.min(e.length-1,Math.max(n,t+4)));for(let d=c;d<=u;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!l.has(d)&&(l.add(d),a.push(d))}for(let d=0;d<e.length;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!l.has(d)&&(l.add(d),a.push(d))}return a}function jC(e){return e+1}function EG(e,t){return`${jC(e)}-${jC(t)}`}function bie(e,t,n){return`${Nt(e)}:${EG(t,n)}`}function Sie(e,t=180){let n=Nt(e).replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var Rd={empty(e){console.log(Nt(e))},list(e,t){for(let n of e)console.log(Nt(t(n)))},groupedByFile(e,t,n=i=>i.relativePath){let i="";for(let r of e){let o=n(r);o!==i&&(i&&console.log(""),console.log(Nt(o)),i=o),console.log(Nt(t(r)))}},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 ${Nt(n.title)} \u2550\u2550\u2550`),n.explanation!==void 0&&console.log(Nt(n.explanation));for(let i of n.rows)console.log(Nt(i))}},table(e,t,n){console.log(` ${e.map(Nt).join(" ")}`);let i=n??e.map(r=>r.length);console.log(` ${i.map(r=>"\u2500".repeat(r)).join(" ")}`);for(let r of t)console.log(Nt(r))}};import{availableParallelism as WG}from"os";import{fileURLToPath as Md}from"url";import{spawnSync as Zie}from"child_process";import{execFileSync as xie}from"child_process";import{createHash as Eie}from"crypto";import{lstatSync as Iie,readlinkSync as Lie,readdirSync as Die,realpathSync as Pie,statSync as Tie}from"fs";import{dirname as Mie,isAbsolute as Aie,join as Nie,posix as kie,relative as _ie,resolve as Bie,sep as Oie}from"path";var jie=512*1024*1024;function HC(e){return _m({version:e.version,...e.base?{base:e.base}:{},files:[...e.files].sort((t,n)=>t.path.localeCompare(n.path))})}function Ed(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 wG="codebaseiq:collaboration-domain",IG="codebaseiq:workspace-instance",LG="codebaseiq:index-generation",DG="codebaseiq:repository-content",UC="codebaseiq:index-inputs",PG="codebaseiq:index-inputs";function Di(e){let t=e.snapshot,n=e.observedSourceKinds?new Set(e.observedSourceKinds):void 0,i=e.gitContext??t?.gitContext??(n?.has("live-workspace")?ll(e.projectRoot):void 0),r=e.collaborationDomainId??e.db?.config.collaborationDomainId,o=r?si(wG,1,r):void 0,s=i?si(IG,1,i.worktreeId):void 0,a=t?si(DG,1,HC(t.repositoryContent)):void 0,l=t?si(UC,t.indexInputs.version,Ed(t.indexInputs)):void 0,c=e.db&&t?FG(e.db.generation.metadataRaw):void 0,u=e.db?{generation:si(LG,1,e.db.generation.identity),...c?{inputs:c}:{},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"}]:[]],f=[...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"}),f.push({source:"process",kind:"not-established"})),{schemaVersion:Vm,observedAt:(e.observedAt??(t?new Date(t.capturedAt):new Date)).toISOString(),facts:{...o?{collaborationDomain:o}:{},...s?{workspaceInstance:s}:{},...a?{wholeContent:a}:{},...l?{relevantInputs:[{subject:PG,identity:l}]}:{},...u?{index:u}:{}},observedSources:m,stabilityProofs:f,...i?{diagnostics:{clean:i.clean,...i.headCommit?{headCommit:i.headCommit}:{},...i.treeOid?{treeOid:i.treeOid}:{}}}:{}}}function TG(e){return Di({projectRoot:e.projectRoot,db:e.db,...e.gitContext?{gitContext:e.gitContext}:{},...e.observedAt?{observedAt:e.observedAt}:{},observedSourceKinds:["index-generation"]})}function Jie(){let e=cs();if(!e)return Di({projectRoot:Xm(),observedSourceKinds:["process"]});let t=e.config.projectRoot,n=ll(t);return TG({projectRoot:t,db:e,...n?{gitContext:n}:{}})}function FG(e){if(!e)return;let t=Ho(e);if(t.kind!=="legacy"&&t.kind!=="supported")return;let n=Vd(t.metadata.fingerprint);return n&&Number.isSafeInteger(n.version)&&n.version>0?si(UC,n.version,Ed(n)):void 0}var Id="codebaseiq-isolated-analysis",Ld=1;function MG(e){let t=[...e??[]];return t.includes("--json")?t:["--json",...t]}var fr=class extends Error{constructor(n,i,r=!0){super(`${n} timed out after ${i}ms.`);this.label=n;this.timeoutMs=i;this.reaped=r;this.name="IsolatedProcessTimeoutError"}label;timeoutMs;reaped;timedOut=!0};function sre(e,t){let n=cs(),i={protocol:Id,schemaVersion:Ld,producer:{name:"codebaseiq",version:ii},command:e,result:t,...n?{observationReceipt:Di({projectRoot:n.config.projectRoot,db:n,observedSourceKinds:["index-generation"]})}:{}};Sl(JSON.stringify(i))}function zC(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}function Za(e){let t=e.timeoutMs??Kd.analysis,n=e.maxBuffer??10*1024*1024;return Wd({command:process.execPath,args:[...process.execArgv,e.cliPath,e.command,...MG(e.args)],cwd:process.cwd(),env:e.env??process.env,label:e.label,timeoutMs:t,maxStdoutBytes:n,maxStderrBytes:n,signal:e.signal}).catch(i=>{throw i instanceof qd&&i.kind==="timeout"?new fr(e.label,t,i.reaped):i}).then(i=>{let r=i.stderr.trim();if(i.status!==0)throw new Error(`${e.label} failed${r?`:
|
|
530
|
+
${r}`:""}`);return AG(i.stdout,e)})}function AG(e,t){let n;try{n=JSON.parse(e)}catch(r){throw new Error(`${t.label} returned invalid JSON: ${r instanceof Error?r.message:r}`,{cause:r})}if(!sl(n))throw new Error(`${t.label} returned a non-object isolated-analysis message.`);if(n.protocol!==Id)throw new Error(`${t.label} returned protocol ${wd(n.protocol)}; expected ${Id}.`);if(n.schemaVersion!==Ld)throw new Error(`${t.label} returned unsupported isolated-analysis schemaVersion ${wd(n.schemaVersion)}; expected ${Ld}.`);if(!NG(n.producer))throw new Error(`${t.label} did not identify a codebaseiq producer version.`);if(n.command!==t.command)throw new Error(`${t.label} returned result for command ${wd(n.command)}; expected ${t.command}.`);if(!Object.hasOwn(n,"result"))throw new Error(`${t.label} omitted the isolated-analysis result.`);let i=n.observationReceipt;if(i!==void 0&&(!Jm(i)||i.schemaVersion!==2))throw new Error(`${t.label} returned an invalid observation receipt.`);return{result:n.result,...i?{observationReceipt:i}:{}}}function NG(e){return sl(e)&&e.name==="codebaseiq"&&typeof e.version=="string"&&e.version.length>0}function wd(e){return typeof e=="string"?JSON.stringify(e):String(e)}async function Dd(e,t,n){let i=new Array(e.length),r=new AbortController,o=0,s,a=!1;async function l(){for(;!r.signal.aborted&&o<e.length;){let c=o++;try{i[c]=await n(e[c],r.signal)}catch(u){throw a||(a=!0,s=u,r.abort(u)),u}}}if(await Promise.allSettled(Array.from({length:Math.min(t,e.length)},()=>l())),a)throw s;return i}function GC(e,t){let n=new Set,i=[];for(let r of e){if(n.has(r))continue;let o=t.find(a=>a.has(r));if(!o){n.add(r),i.push([r]);continue}let s=e.filter(a=>o.has(a));s.forEach(a=>n.add(a)),i.push(s)}return i}import{spawnSync as kG}from"child_process";import{existsSync as _G,mkdirSync as BG,renameSync as OG,writeFileSync as $G}from"fs";import{dirname as qC,join as jG}from"path";var Qa=6,HG="health-report-cache.json";function Pd(e,t,n,i=qG()){let r=gn(e);return r?{version:Qa,projectFingerprint:r,cliVersion:n,scope:t.scope??null,full:t.full===!0,phaseTimeoutMs:t.phaseTimeoutMs??null,gitHead:i.gitHead(e.config.projectRoot)}:null}function WC(e,t,n=XC()){let i=JC(e),r=YC(t),o=!1;return $("health.report-cache.read",()=>{if(!n.existsSync(i))return null;try{let s=JSON.parse(n.readFile(i));return!UG(s)||s.keyHash!==r?null:(o=!0,s.report)}catch{return null}},()=>({available:!0,hit:o,keyHash:r}))}function VC(e,t,n,i=XC()){let r=JC(e),o={version:Qa,keyHash:YC(t),key:t,writtenAt:i.nowIso(),report:n};i.mkdirSync(qC(r),{recursive:!0});let s=`${r}.${process.pid}.${Date.now()}.tmp`;i.writeFileSync(s,JSON.stringify(o)),i.renameSync(s,r)}function JC(e){return jG(qC(e.config.dbPath),HG)}function YC(e){return jt(JSON.stringify(e))}function UG(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===Qa&&typeof t.keyHash=="string"&&zG(t.key)&&typeof t.writtenAt=="string"&&GG(t.report)}function zG(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===Qa&&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 GG(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)&&KG(t.coverage)}function KG(e){if(!e||typeof e!="object")return!1;let t=e;if(t.status!=="complete"&&t.status!=="incomplete"&&t.status!=="semantic-disabled")return!1;let n=t.complexity?.semanticEvidence;return KC(n)&&typeof n.excludedSymbolCount=="number"&&Array.isArray(t.phases)&&t.phases.every(i=>!!i&&typeof i=="object"&&typeof i.phase=="string"&&KC(i.semanticEvidence))}function KC(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.enabled=="boolean"&&(t.status==="complete"||t.status==="incomplete"||t.status==="unavailable"||t.status==="incomplete-and-unavailable"||t.status==="disabled")&&typeof t.incompleteSymbolCount=="number"&&typeof t.unavailableSymbolCount=="number"}function qG(){return{gitHead(e){let t=kG("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:3e4,killSignal:"SIGKILL",windowsHide:!0});return t.status===0?t.stdout.trim():null}}}function XC(){return{existsSync:_G,mkdirSync:BG,readFile:e=>gr(e,"health report cache"),renameSync:OG,writeFileSync:$G,nowIso:()=>new Date().toISOString()}}var ex="__health-phase",VG="__diff-impact-batch",JG=10,YG=4,XG=8,ZG=25e3,QG=2500,Td=2500,eK=4,tK=12,ZC=3e4,tx=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),nx=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]),nK=new Set([...nx,"suppressions"]),iK=new Set(["similar","extract-candidates"]),tl=3,QC=hr({kind:"health-semantic-prewarm",invalidation:Je("health-semantic-prewarm"),serialize:e=>JSON.stringify(e),deserialize:rK});function rK(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return n.version!==tl||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:tl,definitions:n.definitions,referenceCacheWrites:n.referenceCacheWrites,referenceIncomplete:n.referenceIncomplete,calleeRows:n.calleeRows,warmedAt:n.warmedAt}}catch{return null}}function Mre(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
|
|
531
|
+
`)}function oK(e){let t=mi(e);return t.symbols>=ZG||t.documents>=QG}function Are(e,t,n,i={}){if(!oK(e))return{semantic:!0};if(n)return i.quiet||console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0};if(!i.quiet){let r=t==="inspect"?"Use --full only when every omitted semantic candidate can change the decision; it does not override source or behavior materialization ceilings.":`Run "codebaseiq ${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 ${Td}. `+r)}return{scanLimit:Td,semantic:!1,analysisBudget:{scanLimit:Td,semanticEnrichment:!1,reason:"large index default budget; pass --full for unbounded semantic analysis"}}}var sK={env:process.env,projectFingerprint:gn,semanticEngineFingerprint:uK,readMarker:(e,t,n)=>QC.read(e,t,n),writeMarker:(e,t,n,i)=>QC.write(e,t,n,i),candidateDefinitions:(e,t)=>new U(e).scopedDefinitions(t.scope).filter(n=>Ke(n.relativePath)!==null),materializeReferences:(e,t,n)=>kt(e).materializeReferences(t,n),materializeCallees:rc};function aK(e,t,n=sK){if(t.full!==!0)return ti("default-mode");if((n.env??process.env).CODEBASEIQ_HEALTH_SEMANTIC_PREWARM==="0")return ti("disabled");let i=ti("error");return $("health.semantic-prewarm",()=>{try{i=lK(e,t,n)}catch(r){i=ti("error",{error:r instanceof Error?r.message:String(r)})}return i},()=>dK(i))}function lK(e,t,n){let i=n.projectFingerprint(e);if(!i)return ti("missing-project-fingerprint");let r=cK(t,n.semanticEngineFingerprint(e)),o=n.readMarker(e,r,i);if(o&&o.referenceIncomplete===0)return ti("cache-hit");let s=[];if(s=$("health.semantic-prewarm.candidate-definitions",()=>(s=n.candidateDefinitions(e,t),s),()=>({definitions:s.length})),s.length===0)return ti("no-semantic-definitions");let a=0,l=$("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(l.cacheHits+l.cacheWrites+l.inMemoryHits===0&&l.misses+l.unkeyed>0)return ti("provider-unavailable",{definitions:s.length,referenceMisses:l.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 l.incomplete>0?{status:"partial",reason:"incomplete-references",definitions:s.length,referenceCacheHits:l.cacheHits,referenceCacheWrites:l.cacheWrites,referenceMisses:l.misses,referenceIncomplete:l.incomplete,calleeRows:d.size}:($("health.semantic-prewarm.marker-write",()=>n.writeMarker(e,r,i,{version:tl,definitions:s.length,referenceCacheWrites:l.cacheWrites,referenceIncomplete:l.incomplete,calleeRows:d.size,warmedAt:Date.now()})),{status:"warmed",reason:"cache-miss",definitions:s.length,referenceCacheHits:l.cacheHits,referenceCacheWrites:l.cacheWrites,referenceMisses:l.misses,referenceIncomplete:l.incomplete,calleeRows:d.size})}function cK(e,t){return JSON.stringify({version:tl,cliVersion:ii,semanticEngineFingerprint:t,scope:e.scope??null})}function uK(e){return jt(JSON.stringify({kind:"health-semantic-prewarm-engine",rust:oi(e.config.projectRoot)}))}function ti(e,t={}){return{status:"skipped",reason:e,definitions:0,referenceCacheHits:0,referenceCacheWrites:0,referenceMisses:0,referenceIncomplete:0,calleeRows:0,...t}}function dK(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 el(e){return vl(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 nl(e,t,n){let i=e[0];if(!i)throw new Error("An evidence-bound analysis requires at least one index observation anchor.");let r=i.generationDigest,o=e.every(a=>a.generationDigest===r),s=t.every(a=>a?.facts.index?.generation.digest===r);return Di({projectRoot:i.database.config.projectRoot,...o&&s?{db:i.database}:{},observedSourceKinds:n})}async function Nre(e){return(await mK(e)).result}async function mK(e){let t=bK(e),n={...e,phaseTimeoutMs:t??null},i=el(g=>{let h=Pd(g,n,ii);if(!h)return null;let S=WC(g,h);return S||null});if(i.value)return{result:i.value,observationReceipt:nl([i.anchor],[],["index-generation","live-workspace"])};let r=el(g=>({applicability:fK(g,e),overview:hd(g,"overview",e)})),{applicability:o,overview:s}=r.value,a=[i.anchor,r.anchor],l=new Map;l.set("overview",s);let c=Ja.filter(g=>g==="overview"?!1:pK(g,o)?!0:(l.set(g,Pi(g)),!1)),u=gK(c);if(e.full){let g=el(h=>aK(h,e));a.push(g.anchor)}let d=await Dd(u,SK(u.length),(g,h)=>hK(g,e,t,h)),m=d.flatMap(g=>g.result),f=[];if(m.forEach(g=>{g.healthPhaseMeta&&f.push(`Health phase "${g.phase}" deferred: ${g.healthPhaseMeta.reason}. Run health --full for exhaustive analysis.`),l.set(g.phase,g)}),f.length>0){let g=l.get("overview");l.set("overview",{...g,warnings:[...g.warnings,...f]})}let p=yd(Ja.map(g=>l.get(g)));return vl(g=>{let h=Pd(g,n,ii);h&&VC(g,h,p)}),{result:p,observationReceipt:nl(a,d.map(g=>g.observationReceipt),["index-generation","live-workspace"])}}function fK(e,t){return Jo(e,{scope:t.scope})}function pK(e,t){return tx.has(e)?t.react:nx.has(e)?t.vue:!0}function gK(e){return GC(e,[tx,nK,iK])}function Pi(e){let t={enabled:!0,status:"complete",incompleteSymbolCount:0,unavailableSymbolCount:0};switch(e){case"react-component-duplicates":return{phase:e,reactComponentDuplicates:{count:0,loc:0,files:[]},evidenceCoverage:t};case"react-hook-candidates":return{phase:e,reactHookCandidates:{count:0,loc:0,files:[]},evidenceCoverage:t};case"react-large-component-pressure":return{phase:e,reactLargeComponentPressure:{count:0,loc:0,files:[]},evidenceCoverage:t};case"vue-component-duplicates":return{phase:e,vueComponentDuplicates:{count:0,loc:0,files:[]},evidenceCoverage:t};case"vue-composable-candidates":return{phase:e,vueComposableCandidates:{count:0,loc:0,files:[]},evidenceCoverage:t};case"vue-large-view-pressure":return{phase:e,vueLargeViewPressure:{count:0,loc:0,files:[]},evidenceCoverage:t};default:throw new Error(`Health phase "${e}" cannot be synthesized.`)}}function hK(e,t,n,i){if(e.length===1)return yK(e[0],t,n,i).then(a=>({result:[a.result],...a.observationReceipt?{observationReceipt:a.observationReceipt}:{}}));let r=e.join(","),o=process.argv[1]??Md(import.meta.url),s=[r];return t.scope&&s.push("--scope",t.scope),t.full&&s.push("--full"),Za({cliPath:o,command:ex,args:s,label:`Health phases "${r}"`,timeoutMs:n,signal:i}).catch(a=>{if(t.full||!(a instanceof fr))throw a;return{result:e.map(l=>ix(l,a.timeoutMs,`timed out after ${a.timeoutMs}ms`))}})}function yK(e,t,n,i){let r=process.argv[1]??Md(import.meta.url),o=[e];return t.scope&&o.push("--scope",t.scope),t.full&&o.push("--full"),Za({cliPath:r,command:ex,args:o,label:`Health phase "${e}"`,timeoutMs:n,signal:i}).catch(s=>{if(t.full||!(s instanceof fr))throw s;return{result:ix(e,s.timeoutMs,`timed out after ${s.timeoutMs}ms`)}})}function bK(e,t=process.env){if(e.full)return;let n=t.CODEBASEIQ_HEALTH_PHASE_TIMEOUT_MS;if(!n)return ZC;let i=parseInt(n,10);return!Number.isFinite(i)||i<0?ZC:i===0?void 0:i}function ix(e,t,n){let i={evidenceCoverage:{enabled:!0,status:"unavailable",incompleteSymbolCount:0,unavailableSymbolCount:0},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:[]},...i};case"isolated":return{phase:e,isolated:{count:0,loc:0,files:[]},...i};case"cycles":return{phase:e,realCycleCount:0,...i};case"similar":return{phase:e,similarCount:0,...i};case"duplicate-bodies":return{phase:e,duplicateBodies:{count:0,loc:0,files:[]},...i};case"twin-drift":return{phase:e,twinDrift:{count:0,loc:0,files:[]},...i};case"react-component-duplicates":return{...Pi(e),...i};case"react-hook-candidates":return{...Pi(e),...i};case"react-large-component-pressure":return{...Pi(e),...i};case"vue-component-duplicates":return{...Pi(e),...i};case"vue-composable-candidates":return{...Pi(e),...i};case"vue-large-view-pressure":return{...Pi(e),...i};case"extract-candidates":return{phase:e,extractCount:0,...i};case"wrapper-candidates":return{phase:e,wrappers:{count:0,loc:0,files:[]},...i};case"passthrough-candidates":return{phase:e,passthroughs:{count:0,loc:0,files:[]},...i};case"stale-abstractions":return{phase:e,stale:{count:0,loc:0,files:[],unused:0,singleUse:0},...i};case"drift":return{phase:e,drift:{count:0,unusedImports:0,architectureViolations:0,layerViolations:0,direct:0,signal:0},...i};case"complexity-hotspots":return{phase:e,complexity:{top:[],extremeCount:0,coverage:{semanticEvidence:{enabled:!0,status:"unavailable",incompleteSymbolCount:0,unavailableSymbolCount:0,excludedSymbolCount:0}}},...i};case"git-evidence":return{phase:e,gitEvidence:null,...i};case"suppressions":return{phase:e,suppressions:{total:0,byCategory:{}},...i};case"coverage-contracts":return{phase:e,coverageContracts:{count:0,loc:0,files:[]},...i}}}var SK=rx({envKey:"CODEBASEIQ_HEALTH_CONCURRENCY",defaultMinimum:eK,defaultMaximum:tK});function kre(e){if(console.log(`
|
|
532
|
+
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)
|
|
533
|
+
`),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${Zm(e.overview.indexSizeBytes)}
|
|
534
|
+
`),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: ${Fd(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: ${Fd(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: ${Fd(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(`
|
|
535
|
+
Prioritized Actions (highest impact + lowest effort first):`);for(let n=0;n<e.actions.length;n++){let i=e.actions[n],r=i.locRecoverable>0?` (~${i.locRecoverable} LOC involved)`:"";console.log(` ${n+1}. [${i.effort} effort / ${i.impact} impact] ${i.description}${r}`)}}if(e.topComplexity.length>0){console.log(`
|
|
536
|
+
Top Complexity Hotspots:`);for(let n of e.topComplexity)console.log(` ${n.score.toFixed(1).padStart(6)} ${n.symbol}`)}if(xK(e),CK(e),e.scoreBreakdown.length>0){console.log(`
|
|
537
|
+
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?`
|
|
538
|
+
No findings from completed analyses. Review warnings before interpreting this result as clean.`:`
|
|
539
|
+
No issues found. Codebase is clean.`)}function Fd(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${vK(t)} score-weighted)`}function vK(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function CK(e){if(e.pressure.length!==0){console.log(`
|
|
540
|
+
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 xK(e){let t=e.axes;if(console.log(`
|
|
541
|
+
Axes:`),console.log(` Zero-reference candidates: ${t.deletable.loc} LOC across ${t.deletable.symbols} symbols`),t.changeAmplification){let i=t.changeAmplification;console.log(` Change amplification: ${i.medianFilesPerCommit} files/commit median, ${i.p90FilesPerCommit} p90 (${i.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 i of t.hiddenCoupling.top.slice(0,3))console.log(` ${i.fileA} <-> ${i.fileB} (${i.together}x together, ${Math.round(i.confidence*100)}%)`)}if(t.churnWeightedComplexity&&t.churnWeightedComplexity.length>0){let i=t.churnWeightedComplexity[0];i.weighted>0&&console.log(` Churn x complexity: hottest is ${i.symbol} (${i.changes} changes, weighted ${i.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 i=e.validation,r=i.ratio===null?"n/a":`${i.ratio}x`;console.log(` Validation: flagged files fix-density ${i.flaggedFixDensity} vs baseline ${i.baselineFixDensity} (${r})`),console.log(` fix-commit signal: subject-keyword heuristic over ${i.validationBasis.commitsScanned} commits`)}}async function _re(e){let t=el(o=>{let s=ur(o,{base:e.base});return s.note?{kind:"complete",result:Ta(o,{base:e.base})}:s.changedFiles.length===0?{kind:"complete",result:Ta(o,{base:e.base})}:{kind:"batched",plan:s}}),n=t.value;if(n.kind==="complete")return{result:n.result,observationReceipt:nl([t.anchor],[],["index-generation","live-workspace"])};let i=zC(n.plan.changedFiles,JG),r=await Dd(i,RK(i.length),(o,s)=>LK(o,e,s));return{result:Fa(n.plan.changedFiles,r.map(o=>o.result)),observationReceipt:nl([t.anchor],r.map(o=>o.observationReceipt),["index-generation","live-workspace"])}}var RK=rx({envKey:"CODEBASEIQ_DIFF_IMPACT_CONCURRENCY",defaultMinimum:YG,defaultMaximum:XG});function rx(e){return(t,n=process.env,i=WG)=>EK(t,n,i,e)}function EK(e,t,n,i){let r=t[i.envKey],o=IK(n,i),s=r?parseInt(r,10):o,a=!Number.isFinite(s)||s<1?Math.min(o,e):Math.min(s,e),l=wK(t);return l===null?a:Math.min(l,a)}function wK(e){let t=e.CODEBASEIQ_MAX_CONCURRENCY;if(!t)return null;let n=parseInt(t,10);return Number.isFinite(n)&&n>=1?n:null}function IK(e,t){let n=e(),i=Number.isFinite(n)?Math.max(t.defaultMinimum,n-1):0;return Math.min(t.defaultMaximum,Math.max(t.defaultMinimum,i))}function LK(e,t,n){let i=process.argv[1]??Md(import.meta.url),r=[];return t.base&&r.push("--base",t.base),Za({cliPath:i,command:VG,args:r,env:{...process.env,CODEBASEIQ_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch",signal:n})}function Bre(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(i=>i.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(i=>i.file))];for(let i of n){let r=t.filter(o=>o.file===i).length;console.log(`note: ${r} changed line-range(s) in ${i} belong to no indexed symbol`)}}console.log(""),e.changedSymbols.length>0&&(console.log("Changed symbols:"),Rd.list(e.changedSymbols,n=>` ${n.file} ${n.shortName} (fan-in: ${n.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
|
|
542
|
+
Affected consumer files:`),Rd.list(e.affectedConsumers,n=>` ${n.file} (${n.consumedSymbols} symbol(s))`))}export{Rr as a,Zt as b,nf as c,PK as d,mi as e,iw as f,oc as g,sc as h,jr as i,ac as j,js as k,RL as l,Vr as m,Cl as n,$l as o,DR as p,Jr as q,Yr as r,Zs as s,ih as t,BD as u,sP as v,b2 as w,KY as x,mP as y,bP as z,Gt as A,dF as B,cM as C,co as D,su as E,MM as F,ob as G,wi as H,S0 as I,x0 as J,R0 as K,E0 as L,B0 as M,j0 as N,H0 as O,U0 as P,G0 as Q,K0 as R,q0 as S,Ii as T,Sb as U,fo as V,fu as W,gA as X,po as Y,SA as Z,vA as _,LA as $,MA as aa,AA as ba,NA as ca,yo as da,Su as ea,bo as fa,$N as ga,So as ha,vo as ia,Cu as ja,Co as ka,xo as la,xu as ma,Fk as na,Ro as oa,B_ as pa,Tu as qa,Fu as ra,CB as sa,ur as ta,NS as ua,tO as va,wo as wa,M$ as xa,Lo as ya,t1 as za,Do as Aa,q1 as Ba,W1 as Ca,tj as Da,gj as Ea,xj as Fa,$j as Ga,id as Ha,Wv as Ia,od as Ja,Vv as Ka,za as La,gH as Ma,Ao as Na,No as Oa,ko as Pa,RU as Qa,EU as Ra,wU as Sa,pd as Ta,Ja as Ua,hd as Va,rz as Wa,$z as Xa,jz as Ya,Uz as Za,Gz as _a,tG as $a,lG as ab,Di as bb,Jie as cb,sre as db,jC as eb,EG as fb,bie as gb,Sie as hb,Rd as ib,ex as jb,VG as kb,Mre as lb,Are as mb,Nre as nb,mK as ob,kre as pb,_re as qb,Bre as rb};
|
|
543
|
+
//# sourceMappingURL=chunk-BLKYYQ7C.js.map
|