scip-query 0.19.8 → 0.20.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 +97 -0
- package/README.md +158 -48
- package/dist/augment-vue-worker.js +1 -1
- package/dist/chunk-26QA6FAI.js +8 -0
- package/dist/{chunk-KJ2IIBZN.js → chunk-2HPVVXM5.js} +2 -2
- package/dist/chunk-2KAZEZ6M.js +2 -0
- package/dist/chunk-32LVLCLN.js +40 -0
- package/dist/{chunk-24GTWJ3N.js → chunk-3CLX5EOX.js} +2 -2
- package/dist/{chunk-QGGLL3UH.js → chunk-3G66UZBH.js} +2 -2
- package/dist/{chunk-AA4UWRNL.js → chunk-3ORVDL3H.js} +2 -2
- package/dist/chunk-4MAK2HOY.js +6 -0
- package/dist/{chunk-QIQ63BHW.js → chunk-4TURLRL5.js} +2 -2
- package/dist/chunk-4UQVNCQE.js +2 -0
- package/dist/chunk-55Q3WLZX.js +2 -0
- package/dist/{chunk-CTF2GDEX.js → chunk-5E4WNAVD.js} +2 -2
- package/dist/{chunk-ZCEJ63SP.js → chunk-5I5G2QOX.js} +2 -2
- package/dist/chunk-6LDJQXAH.js +2 -0
- package/dist/{chunk-3EDFLQ6A.js → chunk-6O5TICIZ.js} +2 -2
- package/dist/{chunk-ACAM6O5R.js → chunk-6SHPK5ZE.js} +2 -2
- package/dist/chunk-7BAVHKMJ.js +49 -0
- package/dist/chunk-7O5IKBTZ.js +16 -0
- package/dist/{chunk-WJL2L6MV.js → chunk-7PIO7NKH.js} +2 -2
- package/dist/chunk-7S5E7KWT.js +2 -0
- package/dist/{chunk-YLFORA5G.js → chunk-7SQQWSY3.js} +2 -2
- package/dist/chunk-7WPLAODU.js +5 -0
- package/dist/chunk-A73XVBCR.js +20 -0
- package/dist/chunk-AFHORGLH.js +42 -0
- package/dist/chunk-AIE7TFJW.js +9 -0
- package/dist/{chunk-TWMJ3Y3G.js → chunk-AZJQQKDD.js} +2 -2
- package/dist/{chunk-BDOIKGDI.js → chunk-B2PX5I6M.js} +2 -2
- package/dist/{chunk-DQBCO2UY.js → chunk-B7PBSLZN.js} +2 -2
- package/dist/chunk-BBW6JFHN.js +2 -0
- package/dist/{chunk-YTVWB7YJ.js → chunk-BDCC2NPY.js} +2 -2
- package/dist/{chunk-O23I56NA.js → chunk-BNXCIFVY.js} +2 -2
- package/dist/{chunk-MLFZP76A.js → chunk-BPAPWKP6.js} +2 -2
- package/dist/chunk-BS2NMXQZ.js +4 -0
- package/dist/chunk-C3KV2II6.js +2 -0
- package/dist/chunk-C43RDDP4.js +20 -0
- package/dist/{chunk-K2WO7XY7.js → chunk-CJST5ETY.js} +2 -2
- package/dist/chunk-DAFAHMNB.js +42 -0
- package/dist/{chunk-KKME5ZAI.js → chunk-DQGFVPUV.js} +2 -2
- package/dist/chunk-DQLPXMH6.js +8 -0
- package/dist/chunk-EKZTZXHZ.js +117 -0
- package/dist/{chunk-FJ5UDTQF.js → chunk-EN3O7VJA.js} +2 -2
- package/dist/{chunk-HZYDQPNY.js → chunk-EW2NTSFA.js} +2 -2
- package/dist/chunk-F3Z4OUDS.js +8 -0
- package/dist/chunk-FJH2NW7J.js +66 -0
- package/dist/{chunk-MSBDMFER.js → chunk-FKSELJQF.js} +2 -2
- package/dist/chunk-FTFP6O3L.js +11 -0
- package/dist/chunk-FYLK2DEJ.js +2 -0
- package/dist/{chunk-WUW7YUAH.js → chunk-GH74ASD6.js} +2 -2
- package/dist/{chunk-464PLI5O.js → chunk-GMXWZP2B.js} +2 -2
- package/dist/chunk-GOUBFH5O.js +3 -0
- package/dist/{chunk-FIJCV235.js → chunk-HLF2TX6R.js} +2 -2
- package/dist/{chunk-WWKWUPSU.js → chunk-HX4GQPZP.js} +2 -2
- package/dist/chunk-HX7M4BDI.js +30 -0
- package/dist/chunk-HZ72SESS.js +128 -0
- package/dist/{chunk-SERUIGV5.js → chunk-IB2N4FIY.js} +2 -2
- package/dist/chunk-ILMHV3KM.js +2 -0
- package/dist/chunk-IZYYAFN5.js +2 -0
- package/dist/{chunk-GNC4JVAN.js → chunk-JAYYFEQY.js} +2 -2
- package/dist/{chunk-QJIVBYEK.js → chunk-JDOEX4E6.js} +2 -2
- package/dist/chunk-JFGGXWQF.js +947 -0
- package/dist/chunk-JN4NMBEX.js +8 -0
- package/dist/{chunk-6M7RONVB.js → chunk-JVYA47YU.js} +2 -2
- package/dist/{chunk-7KYNAMMH.js → chunk-JW56N3KI.js} +2 -2
- package/dist/{chunk-OUBAF226.js → chunk-JZ2OXNWB.js} +2 -2
- package/dist/chunk-KMKTIO2G.js +8 -0
- package/dist/chunk-L5GJNV2T.js +8 -0
- package/dist/{chunk-MNSTUIDD.js → chunk-L7AW2QB5.js} +2 -2
- package/dist/chunk-L7JDSCDF.js +4 -0
- package/dist/chunk-LU47HG23.js +14 -0
- package/dist/chunk-LVY7NPF7.js +2 -0
- package/dist/chunk-LY4WC4AD.js +74 -0
- package/dist/{chunk-7FT5Y65S.js → chunk-MKCDWWGV.js} +2 -2
- package/dist/chunk-MNE7YG56.js +2 -0
- package/dist/{chunk-7QHY3H7P.js → chunk-MRXBEXSY.js} +2 -2
- package/dist/chunk-MV7OWDUX.js +2 -0
- package/dist/{chunk-ZJ5CBXK3.js → chunk-N5W4YZMK.js} +2 -2
- package/dist/chunk-NGEXCJJW.js +11 -0
- package/dist/{chunk-7SWJEWJF.js → chunk-NIW6JDC5.js} +2 -2
- package/dist/{chunk-O3O4XXO6.js → chunk-O64IZ6UX.js} +2 -2
- package/dist/{chunk-3ZSJ3PWF.js → chunk-PBUQFCNB.js} +2 -2
- package/dist/{chunk-7RAG65VK.js → chunk-POAVPHH7.js} +2 -2
- package/dist/{chunk-A3QXWFBK.js → chunk-PQCI4SQX.js} +2 -2
- package/dist/{chunk-4BV4QAZJ.js → chunk-PXY7F6Y4.js} +2 -2
- package/dist/chunk-RDO52JGY.js +2 -0
- package/dist/chunk-RJT3TUUZ.js +2 -0
- package/dist/{chunk-S4S2WOIX.js → chunk-RUJURYSV.js} +2 -2
- package/dist/{chunk-JAY7YWS3.js → chunk-RVLDN63O.js} +2 -2
- package/dist/chunk-RXOXSKY3.js +2 -0
- package/dist/chunk-S7OYBOCK.js +2 -0
- package/dist/chunk-SMNXQT5Z.js +3 -0
- package/dist/{chunk-NE3TZUCI.js → chunk-SRAFT254.js} +2 -2
- package/dist/{chunk-ELLMY7XJ.js → chunk-SXP2MBJH.js} +2 -2
- package/dist/chunk-T7YQSHPQ.js +3 -0
- package/dist/{chunk-WY45BHKQ.js → chunk-TFRAYKN6.js} +2 -2
- package/dist/{chunk-2SNGN6U4.js → chunk-UJCOIXDY.js} +2 -2
- package/dist/{chunk-MZZBAITE.js → chunk-UJPRPGCO.js} +2 -2
- package/dist/chunk-W4ETQAXM.js +2 -0
- package/dist/chunk-WCCFZ7V7.js +113 -0
- package/dist/chunk-WUPW3UN3.js +3 -0
- package/dist/{chunk-7LSVMFX7.js → chunk-WXZLAAWK.js} +2 -2
- package/dist/{chunk-5ML2BNRH.js → chunk-X54AGLVX.js} +2 -2
- package/dist/chunk-XKWKXZKW.js +20 -0
- package/dist/{chunk-5YLUDDAF.js → chunk-XSRF6Q77.js} +2 -2
- package/dist/chunk-Y2MVPNKY.js +5 -0
- package/dist/{chunk-JHF3E4YM.js → chunk-YKUU5AIC.js} +2 -2
- package/dist/{chunk-E3HYEQO7.js → chunk-YLCJLTPL.js} +2 -2
- package/dist/{chunk-7VCOXZH3.js → chunk-YTQVETEO.js} +2 -2
- package/dist/chunk-Z4N3MZYA.js +38 -0
- package/dist/chunk-ZHXX42OH.js +18 -0
- package/dist/chunk-ZJOOT3BG.js +2 -0
- package/dist/{chunk-P3UO3EH3.js → chunk-ZK26BAQL.js} +2 -2
- package/dist/{chunk-33KUO7CG.js → chunk-ZTETIQ35.js} +2 -2
- package/dist/cli.js +3 -8
- package/dist/command-descriptors-DSS46KXI.js +642 -0
- package/dist/{config-types-B6MEoRNy.d.ts → config-types-jVM3D7MA.d.ts} +68 -2
- package/dist/{db-DYLKr9Wn.d.ts → db-B5PM5yNk.d.ts} +20 -2
- package/dist/{diff-gate-types-C9BoYwYD.d.ts → diff-gate-types-B0QYpDv1.d.ts} +2 -1
- package/dist/direct-navigation-6YHV6IB5.js +3 -0
- package/dist/{health-DgxIDXJC.d.ts → health-Do5TKSJI.d.ts} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/postinstall.js +1 -1
- package/dist/queries/affected.d.ts +2 -2
- package/dist/queries/affected.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 +22 -3
- 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 +2 -2
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.d.ts +3 -3
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.d.ts +3 -3
- package/dist/queries/complexity.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/deps.d.ts +2 -2
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-gate.d.ts +40 -7
- package/dist/queries/diff-gate.js +1 -1
- package/dist/queries/diff-impact.d.ts +84 -6
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.d.ts +3 -3
- 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 +3 -3
- package/dist/queries/duplicate-bodies.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 +12 -3
- 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 +8 -6
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +141 -10
- 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 +34 -3
- 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 +3 -3
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/plan-context.d.ts +3 -3
- 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/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/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.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 +14 -3
- 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/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 +21 -21
- package/dist/reindex.d.ts +3 -3
- package/dist/reindex.js +33 -33
- package/dist/runtime.d.ts +5 -3
- 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-Cc6c00-a.d.ts → scip-cli-BnEwZRLJ.d.ts} +1 -1
- package/dist/{symbol-types-BgWU6lhL.d.ts → symbol-types-BIQwfoAx.d.ts} +7 -1
- package/dist/typescript-mailbox-worker.js +2 -0
- package/dist/watch-server.js +2 -42
- package/docs/AGENT_GUIDE.md +13 -6
- package/docs/CLI_JSON_OUTPUT.md +110 -22
- package/docs/COMMAND_REFERENCE.md +88 -88
- package/docs/COMMITTED_RECORD_COMPATIBILITY.md +55 -18
- package/docs/DURABILITY.md +88 -38
- package/docs/INDEX_GENERATIONS.md +65 -19
- package/docs/MAILBOX_LIFECYCLE.md +28 -1
- package/docs/REINDEX_METADATA_COMPATIBILITY.md +18 -8
- package/docs/SECURITY_MODEL.md +31 -14
- package/docs/TELEMETRY_RETENTION.md +11 -4
- package/docs/WATCH_REFRESH_REQUESTS.md +34 -21
- package/docs/WINDOWS_SIDECAR_RELEASE.md +9 -4
- package/docs/analyzer-inventory.md +31 -22
- package/docs/analyzer-validation-ledger.md +8 -0
- package/docs/schemas/outcome-event-record.schema.json +57 -1
- package/docs/schemas/project-config.schema.json +82 -1
- package/docs/schemas/suppression-record.schema.json +84 -3
- package/package.json +5 -5
- package/skills/_shared/SKILL.md +2 -2
- package/skills/_shared/references/agent-contract-catalog.md +1 -1
- package/skills/_shared/references/detector-precision-and-diffgate.md +1 -1
- package/skills/scip-audit/SKILL.md +6 -6
- package/skills/scip-audit/references/claims.md +1 -1
- package/skills/scip-audit/references/cleanup.md +19 -20
- package/skills/scip-audit/references/directory.md +4 -4
- package/skills/scip-audit/references/frontend.md +10 -10
- package/skills/scip-audit/references/twin-drift.md +2 -2
- package/skills/scip-diagnose/references/debug.md +8 -8
- package/skills/scip-diagnose/references/root-cause.md +3 -3
- package/skills/scip-diagnose/references/triage.md +10 -10
- package/skills/scip-explore/SKILL.md +3 -3
- package/skills/scip-improve/SKILL.md +10 -10
- package/skills/scip-improve/references/cleanup-batches.md +3 -3
- package/skills/scip-improve/references/directory-moves.md +3 -3
- package/skills/scip-improve/references/doc-reconcile.md +1 -1
- package/skills/scip-improve/references/frontend-extraction.md +2 -2
- package/skills/scip-improve/references/twin-drift.md +3 -3
- package/skills/scip-plan/SKILL.md +2 -2
- package/skills/scip-plan/references/api-impact.md +5 -5
- package/skills/scip-plan/references/conductor.md +2 -2
- package/skills/scip-plan/references/hyper-optimization.md +1 -1
- package/skills/scip-query/SKILL.md +15 -5
- package/skills/scip-setup/references/bootstrap-workflow.md +7 -8
- package/skills/scip-setup/references/language-verification.md +2 -2
- package/skills/scip-setup/references/per-repo-triage.md +1 -1
- package/skills/scip-verify/SKILL.md +10 -10
- package/skills/scip-verify/references/calibrate-detectors.md +7 -7
- package/dist/chunk-2465DLHK.js +0 -3
- package/dist/chunk-2U3OLUNJ.js +0 -61
- package/dist/chunk-33XTHFKR.js +0 -2
- package/dist/chunk-43KC6EQZ.js +0 -2
- package/dist/chunk-47BU5Z4T.js +0 -8
- package/dist/chunk-4YTUWQ6M.js +0 -18
- package/dist/chunk-64MNV6AB.js +0 -8
- package/dist/chunk-67QRR5YC.js +0 -6
- package/dist/chunk-6GXYN7YA.js +0 -40
- package/dist/chunk-A2TNXAXO.js +0 -8
- package/dist/chunk-APMMR5Y2.js +0 -2
- package/dist/chunk-AZFUMCQB.js +0 -2
- package/dist/chunk-BNXICU42.js +0 -33
- package/dist/chunk-C5Q44Q5D.js +0 -3
- package/dist/chunk-DQGSM7RZ.js +0 -20
- package/dist/chunk-E2LAW7SL.js +0 -30
- package/dist/chunk-E4NFOAD4.js +0 -6
- package/dist/chunk-E5HNT4X2.js +0 -3
- package/dist/chunk-FD3HFKXR.js +0 -5
- package/dist/chunk-GHKEJTCE.js +0 -35
- package/dist/chunk-GLZTVKAB.js +0 -16
- package/dist/chunk-HIB452NU.js +0 -949
- package/dist/chunk-IF6FP6B2.js +0 -66
- package/dist/chunk-JORHF5AL.js +0 -108
- package/dist/chunk-KSGTULOS.js +0 -9
- package/dist/chunk-KXDJAG4N.js +0 -38
- package/dist/chunk-L4S2A7BV.js +0 -2
- package/dist/chunk-LP3ARJKF.js +0 -8
- package/dist/chunk-LSOR3LQG.js +0 -3
- package/dist/chunk-NTUMF2X3.js +0 -56
- package/dist/chunk-QOXBSI6G.js +0 -20
- package/dist/chunk-QXK6UUSM.js +0 -2
- package/dist/chunk-RA3AYNWP.js +0 -112
- package/dist/chunk-RJMDJR3A.js +0 -2
- package/dist/chunk-RLH5VUMG.js +0 -2
- package/dist/chunk-SMQWE25B.js +0 -3
- package/dist/chunk-TAVELHYR.js +0 -2
- package/dist/chunk-VAXNI5NE.js +0 -146
- package/dist/chunk-VVY2G5ET.js +0 -2
- package/dist/chunk-W3DBTGL4.js +0 -11
- package/dist/chunk-WANA4KAQ.js +0 -5
- package/dist/chunk-X4FR5BZF.js +0 -9
- package/dist/chunk-X6RKPDY7.js +0 -2
- package/dist/chunk-YCPASUCX.js +0 -2
- package/dist/chunk-ZL2OGDCD.js +0 -2
- package/dist/command-descriptors-ZW5J4ZEM.js +0 -631
- package/dist/direct-navigation-42YHQPOI.js +0 -3
|
@@ -0,0 +1,947 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{createHash as PP}from"crypto";import{existsSync as kP,mkdirSync as TP}from"fs";import{dirname as Jg,join as FP}from"path";import xu from"better-sqlite3";function fu(e,t){let n=e.split("/").at(-1)??e;if(Ug.has(n)||n===".scipquery.json"||/^tsconfig(?:\..+)?\.json$/.test(n))return"config";if(/\.d\.(?:ts|mts|cts)$/.test(e.toLowerCase()))return"ambient";let r=e.includes(".")?`.${e.split(".").at(-1).toLowerCase()}`:"";return t.some(i=>(Vg[i]??[]).includes(r))?"source":"other"}function Gg(e,t,n){let r=e.split("/").at(-1)??e;if(n?.includes(e)||n?.includes(r)||Ug.has(r)||r===".scipquery.json"||/^tsconfig(?:\..+)?\.json$/.test(r))return!0;let i=e.includes(".")?`.${e.split(".").at(-1).toLowerCase()}`:"";return(Vg[t]??[]).includes(i)}function qg(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.version!="number"||!jg(t.languages)||typeof t.pnpmWorkspaces!="boolean"||typeof t.typescriptProjectMode!="string"||!jg(t.typescriptProjects)||t.clojureConfigPath!==void 0&&typeof t.clojureConfigPath!="string"||!Array.isArray(t.files)||!t.files.every(pu)?null:t}function C9(e,t){let n=new Map((e?.files??[]).map(a=>[a.path,a])),r=new Map(t.files.map(a=>[a.path,a])),i=new Set([...n.keys(),...r.keys()]),o=[];for(let a of[...i].sort()){let c=n.get(a),l=r.get(a),u=fu(a,t.languages);!c&&l?o.push({kind:"added",path:a,inputKind:u,after:l}):c&&!l?o.push({kind:"deleted",path:a,inputKind:u,before:c}):c&&l&&(c.hash!==l.hash||c.size!==l.size)&&o.push({kind:"modified",path:a,inputKind:u,before:c,after:l})}let s=new Set;return e||s.add("prior-snapshot-unavailable"),e&&e.version!==t.version&&s.add("snapshot-version-changed"),($g(e?.files??[])||$g(t.files))&&s.add("duplicate-input-path"),[...e?.files??[],...t.files].some(bP)&&s.add("unreadable-input"),{version:1,changes:o,projectIdentityChanged:e?!SP(e,t):!0,uncertainty:[...s].sort()}}function jg(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function $g(e){return new Set(e.map(t=>t.path)).size!==e.length}function pu(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.path=="string"&&typeof t.size=="number"&&Number.isFinite(t.size)&&typeof t.hash=="string"}function bP(e){return e.hash==="unreadable"||e.size<0}function SP(e,t){return Hg(e.languages,t.languages)&&e.pnpmWorkspaces===t.pnpmWorkspaces&&e.typescriptProjectMode===t.typescriptProjectMode&&Hg(e.typescriptProjects,t.typescriptProjects)&&e.clojureConfigPath===t.clojureConfigPath}function Hg(e,t){if(e.length!==t.length)return!1;let n=[...e].sort(),r=[...t].sort();return n.every((i,o)=>i===r[o])}var Ug=new Set(["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lockb","tsconfig.json","tsconfig.base.json","pyproject.toml","setup.py","setup.cfg","Cargo.toml","Cargo.lock","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","build.sbt","compile_commands.json","CMakeLists.txt","Makefile","Gemfile","Gemfile.lock","composer.json","composer.lock","pubspec.yaml","pubspec.lock","deps.edn","project.clj","bb.edn","shadow-cljs.edn"]),Vg={typescript:[".ts",".tsx",".mts",".cts"],javascript:[".js",".jsx",".mjs",".cjs"],java:[".java"],scala:[".scala"],kotlin:[".kt",".kts"],rust:[".rs"],python:[".py",".pyi"],ruby:[".rb"],go:[".go"],cpp:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"],c:[".c",".h"],csharp:[".cs"],vb:[".vb"],dart:[".dart"],php:[".php"],clojure:[".clj",".cljs",".cljc"]};function V(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function la(e){return typeof e=="string"&&Number.isFinite(Date.parse(e))}function B(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}var yo=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php","clojure"],gu=["entry-surface","generated-code","compatibility-shim","reflection-or-registration","test-fixture","intentional-twin","historical-coupling-ended","detector-counterexample"];var hu=2,vr=3;var yu=new Set(yo);function Jt(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(s){return{kind:"malformed",reason:`invalid JSON: ${EP(s)}`}}if(!V(t))return{kind:"malformed",reason:"metadata must be a JSON object"};let n=t.version;if(!Number.isInteger(n))return{kind:"malformed",reason:"version must be an integer"};if(n!==hu&&n!==vr)return{kind:"unsupported",version:n,direction:n<hu?"older":"future"};let r=RP(t,n);if(r)return{kind:"malformed",reason:r};let i=t,o={metadata:i,capabilities:xP(i)};return n===hu?{kind:"legacy",...o,metadata:i}:{kind:"supported",...o,metadata:i}}function T9(e){return e.kind==="legacy"||e.kind==="supported"?e.metadata:null}function zg(e){if(e.kind!=="legacy"&&e.kind!=="supported"||!e.capabilities.stableGenerationIdentity)return null;let t=e.metadata;return JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages,scipCompanion:t.scipCompanion,sqliteLayoutVersion:t.version===vr?t.sqliteLayoutVersion:void 0})}function xP(e){let t=e.fingerprint!==void 0,n=V(e.fingerprint),r=e.indexedLanguages!==void 0,i=e.status==="complete",o=e.version===vr?e:null;return{usableForQuery:r,usableForEvidenceCache:t,publishableGeneration:i&&n&&r,stableGenerationIdentity:i&&t&&typeof e.updatedAt=="string",languageShardReuse:!!o?.languageFingerprints,typescriptProjectShardReuse:!!o?.typescriptProjectShards}}function RP(e,t){if(e.status!=="complete"&&e.status!=="partial")return"status must be complete or partial";if(e.updatedAt!==void 0&&!la(e.updatedAt))return"updatedAt must be a valid timestamp";for(let n of["requestedLanguages","indexedLanguages"])if(e[n]!==void 0&&!CP(e[n]))return`${n} must contain unique supported languages`;return e.skipped!==void 0&&!vP(e.skipped)?"skipped must contain supported language/reason pairs":e.scipCompanion!==void 0&&e.scipCompanion!=="current"&&e.scipCompanion!=="deferred"?"scipCompanion must be current or deferred":t===vr&&e.sqliteLayoutVersion!==void 0&&(!Number.isSafeInteger(e.sqliteLayoutVersion)||e.sqliteLayoutVersion<1)?"sqliteLayoutVersion must be a positive safe integer":t===vr&&e.languageFingerprints!==void 0&&!IP(e.languageFingerprints)?"languageFingerprints must map supported languages to fingerprint objects":t===vr&&e.typescriptProjectShards!==void 0&&!wP(e.typescriptProjectShards)?"typescriptProjectShards must map project names to file fingerprints":null}function F9(e){return e.version===vr&&e.sqliteLayoutVersion===1}function CP(e){return!Array.isArray(e)||!e.every(t=>typeof t=="string"&&yu.has(t))?!1:new Set(e).size===e.length}function vP(e){return Array.isArray(e)&&e.every(t=>V(t)&&typeof t.language=="string"&&yu.has(t.language)&&typeof t.reason=="string")}function IP(e){return V(e)&&Object.entries(e).every(([t,n])=>yu.has(t)&&V(n))}function wP(e){return V(e)&&Object.values(e).every(t=>V(t)&&Array.isArray(t.files)&&t.files.every(pu))}function EP(e){return e instanceof Error?e.message:String(e)}var Wg=[];function Un(e){e.groups.length>0&&Wg.push(e)}function bu(e,t){let n=new Set(t.groups);for(let r of Wg)r.groups.some(i=>n.has(i))&&(t.file!==void 0&&r.clearFile?r.clearFile(e,t.file):r.clearAll(e))}function Kg(){let e=new WeakMap;return{cache:e,ensure(t){let n=e.get(t);return n||(n=new Map,e.set(t,n)),n}}}function $(e,t){let{cache:n,ensure:r}=Kg(),i={get(o,s,a){let c=r(o);if(c.has(s))return c.get(s);let l=a();return c.set(s,l),l},invalidate(o,s){n.get(o)?.delete(s)},invalidateAll(o){n.delete(o)},size(o){return n.get(o)?.size??0}};return Un({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}function z(e,t){let n=new WeakMap,r={get(i,o){let s=n.get(i);if(s)return s.value;let a=o();return n.set(i,{value:a}),a},invalidate(i){n.delete(i)},has(i){return n.has(i)}};return Un({name:e,groups:t.clearGroups,clearAll:i=>r.invalidate(i)}),r}var DP={clearGroups:["whole-project","source-file"]};function Vn(e){return Ir(e,DP)}function Ir(e,t){let{cache:n,ensure:r}=Kg(),i={get(o,s,a,c){let l=r(o),u=l.get(s);if(u&&u.source===a)return u.value;let d=c();return l.set(s,{source:a,value:d}),d},invalidate(o,s){n.get(o)?.delete(s)},invalidateAll(o){n.delete(o)}};return Un({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}var _P="evidence.db";var AP=["source-facts","definition-exclusions","doc-path-tokens","react-component-behavior-profiles"],Ru=new Set(AP),LP=25e4,MP=512*1024*1024,NP=6e4,OP=5e3,ua=new WeakMap,BP=$("evidence-content-hash",{clearGroups:["whole-project","source-file"]}),jP=$("evidence-project-fingerprint",{clearGroups:["whole-project"]}),pt="evidence-v1",ai="version NOT LIKE 'evidence-%'";function ke(e){return PP("sha256").update(e).digest("hex")}function he(e,t,n){return BP.get(e,t,()=>ke(n))}function We(e){return jP.get(e,"current",()=>{try{if(!e.generation.metadataRaw)return null;let t=Jt(e.generation.metadataRaw);if(t.kind!=="legacy"&&t.kind!=="supported"||!t.capabilities.usableForEvidenceCache)return null;let n=t.metadata,r=[...n.indexedLanguages??[]].sort();return ke(JSON.stringify({fingerprint:n.fingerprint,indexedLanguages:r,status:n.status}))}catch(t){return wr("project fingerprint unavailable",t),null}})}function wr(e,t){process.env.SCIP_QUERY_DEBUG&&console.error(`evidence-cache: ${e}: ${t instanceof Error?t.message:String(t)}`)}function Gt(e){if(ua.has(e))return ua.get(e)??null;let t=null;try{let n=new xu(FP(Jg(e.config.dbPath),_P));n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),n.pragma("synchronous = NORMAL"),n.exec(`
|
|
3
|
+
CREATE TABLE IF NOT EXISTS file_evidence (
|
|
4
|
+
kind TEXT NOT NULL,
|
|
5
|
+
relative_path TEXT NOT NULL,
|
|
6
|
+
content_hash TEXT NOT NULL,
|
|
7
|
+
version TEXT NOT NULL,
|
|
8
|
+
payload TEXT NOT NULL,
|
|
9
|
+
PRIMARY KEY (kind, relative_path)
|
|
10
|
+
);
|
|
11
|
+
CREATE TABLE IF NOT EXISTS project_evidence (
|
|
12
|
+
kind TEXT NOT NULL,
|
|
13
|
+
cache_key TEXT NOT NULL,
|
|
14
|
+
project_fingerprint TEXT NOT NULL,
|
|
15
|
+
version TEXT NOT NULL,
|
|
16
|
+
payload TEXT NOT NULL,
|
|
17
|
+
PRIMARY KEY (kind, cache_key)
|
|
18
|
+
);
|
|
19
|
+
CREATE TABLE IF NOT EXISTS semantic_callees (
|
|
20
|
+
relative_path TEXT NOT NULL,
|
|
21
|
+
symbol TEXT NOT NULL,
|
|
22
|
+
content_hash TEXT NOT NULL,
|
|
23
|
+
deps_digest TEXT NOT NULL,
|
|
24
|
+
version TEXT NOT NULL,
|
|
25
|
+
payload TEXT NOT NULL,
|
|
26
|
+
PRIMARY KEY (relative_path, symbol)
|
|
27
|
+
);
|
|
28
|
+
CREATE TABLE IF NOT EXISTS semantic_references (
|
|
29
|
+
relative_path TEXT NOT NULL,
|
|
30
|
+
symbol TEXT NOT NULL,
|
|
31
|
+
project_fingerprint TEXT NOT NULL,
|
|
32
|
+
version TEXT NOT NULL,
|
|
33
|
+
payload TEXT NOT NULL,
|
|
34
|
+
PRIMARY KEY (relative_path, symbol)
|
|
35
|
+
);
|
|
36
|
+
CREATE TABLE IF NOT EXISTS finding_outcome_ledger (
|
|
37
|
+
check_name TEXT NOT NULL,
|
|
38
|
+
finding_id TEXT NOT NULL,
|
|
39
|
+
first_seen INTEGER NOT NULL,
|
|
40
|
+
last_seen INTEGER NOT NULL,
|
|
41
|
+
times_shown INTEGER NOT NULL,
|
|
42
|
+
outcome TEXT NOT NULL,
|
|
43
|
+
PRIMARY KEY (check_name, finding_id)
|
|
44
|
+
);
|
|
45
|
+
CREATE TABLE IF NOT EXISTS finding_outcome_observations (
|
|
46
|
+
observation_id TEXT PRIMARY KEY,
|
|
47
|
+
fingerprint TEXT NOT NULL,
|
|
48
|
+
observed_at INTEGER NOT NULL
|
|
49
|
+
);
|
|
50
|
+
`),t={evidence:n,shared:$P(e.config.sharedEvidenceDbPath),readFileEvidence:n.prepare("SELECT payload FROM file_evidence WHERE kind = ? AND relative_path = ? AND content_hash = ? AND version = ?"),readLegacyFileEvidence:n.prepare(`SELECT payload FROM file_evidence
|
|
51
|
+
WHERE kind = ? AND relative_path = ? AND content_hash = ? AND ${ai}
|
|
52
|
+
ORDER BY version DESC
|
|
53
|
+
LIMIT 1`),writeFileEvidence:n.prepare("INSERT OR REPLACE INTO file_evidence (kind, relative_path, content_hash, version, payload) VALUES (?, ?, ?, ?, ?)"),readProjectEvidence:n.prepare("SELECT payload FROM project_evidence WHERE kind = ? AND cache_key = ? AND project_fingerprint = ? AND version = ?"),readLegacyProjectEvidence:n.prepare(`SELECT payload FROM project_evidence
|
|
54
|
+
WHERE kind = ? AND cache_key = ? AND project_fingerprint = ? AND ${ai}
|
|
55
|
+
ORDER BY version DESC
|
|
56
|
+
LIMIT 1`),writeProjectEvidence:n.prepare("INSERT OR REPLACE INTO project_evidence (kind, cache_key, project_fingerprint, version, payload) VALUES (?, ?, ?, ?, ?)"),readCallees:n.prepare(`SELECT payload FROM semantic_callees
|
|
57
|
+
WHERE relative_path = ? AND symbol = ? AND content_hash = ? AND deps_digest = ? AND version = ?`),readLegacyCallees:n.prepare(`SELECT payload FROM semantic_callees
|
|
58
|
+
WHERE relative_path = ? AND symbol = ? AND content_hash = ? AND deps_digest = ? AND ${ai}
|
|
59
|
+
ORDER BY version DESC
|
|
60
|
+
LIMIT 1`),readCalleesForFile:n.prepare(`SELECT symbol, payload FROM semantic_callees
|
|
61
|
+
WHERE relative_path = ? AND content_hash = ? AND deps_digest = ? AND version = ?`),readLegacyCalleesForFile:n.prepare(`SELECT symbol, payload FROM semantic_callees
|
|
62
|
+
WHERE relative_path = ? AND content_hash = ? AND deps_digest = ? AND ${ai}
|
|
63
|
+
ORDER BY symbol, version DESC`),writeCallees:n.prepare(`INSERT OR REPLACE INTO semantic_callees
|
|
64
|
+
(relative_path, symbol, content_hash, deps_digest, version, payload) VALUES (?, ?, ?, ?, ?, ?)`),dropStaleCallees:n.prepare("DELETE FROM semantic_callees WHERE relative_path = ? AND content_hash != ?"),readReferences:n.prepare(`SELECT payload FROM semantic_references
|
|
65
|
+
WHERE relative_path = ? AND symbol = ? AND project_fingerprint = ? AND version = ?`),readLegacyReferences:n.prepare(`SELECT payload FROM semantic_references
|
|
66
|
+
WHERE relative_path = ? AND symbol = ? AND project_fingerprint = ? AND ${ai}
|
|
67
|
+
ORDER BY version DESC
|
|
68
|
+
LIMIT 1`),readReferencesForFile:n.prepare(`SELECT symbol, payload FROM semantic_references
|
|
69
|
+
WHERE relative_path = ? AND project_fingerprint = ? AND version = ?`),readLegacyReferencesForFile:n.prepare(`SELECT symbol, payload FROM semantic_references
|
|
70
|
+
WHERE relative_path = ? AND project_fingerprint = ? AND ${ai}
|
|
71
|
+
ORDER BY symbol, version DESC`),writeReferences:n.prepare(`INSERT OR REPLACE INTO semantic_references
|
|
72
|
+
(relative_path, symbol, project_fingerprint, version, payload) VALUES (?, ?, ?, ?, ?)`),dropStaleReferences:n.prepare("DELETE FROM semantic_references WHERE relative_path = ? AND project_fingerprint != ?"),readFindingOutcomeLedger:n.prepare("SELECT check_name, finding_id, first_seen, last_seen, times_shown, outcome FROM finding_outcome_ledger"),claimFindingOutcomeObservation:n.prepare(`INSERT OR IGNORE INTO finding_outcome_observations
|
|
73
|
+
(observation_id, fingerprint, observed_at) VALUES (?, ?, ?)`),readFindingOutcomeObservation:n.prepare("SELECT fingerprint FROM finding_outcome_observations WHERE observation_id = ?"),upsertFindingOutcomeLedgerRow:n.prepare(`INSERT INTO finding_outcome_ledger
|
|
74
|
+
(check_name, finding_id, first_seen, last_seen, times_shown, outcome)
|
|
75
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
76
|
+
ON CONFLICT(check_name, finding_id) DO UPDATE SET
|
|
77
|
+
first_seen = MIN(finding_outcome_ledger.first_seen, excluded.first_seen),
|
|
78
|
+
last_seen = MAX(finding_outcome_ledger.last_seen, excluded.last_seen),
|
|
79
|
+
times_shown = finding_outcome_ledger.times_shown + excluded.times_shown,
|
|
80
|
+
outcome = excluded.outcome`),updateFindingOutcomeLedgerRow:n.prepare(`UPDATE finding_outcome_ledger
|
|
81
|
+
SET first_seen = MIN(first_seen, ?),
|
|
82
|
+
last_seen = MAX(last_seen, ?),
|
|
83
|
+
outcome = ?
|
|
84
|
+
WHERE check_name = ? AND finding_id = ?`),trimFindingOutcomeLedgerCheck:n.prepare(`DELETE FROM finding_outcome_ledger
|
|
85
|
+
WHERE rowid IN (
|
|
86
|
+
SELECT rowid
|
|
87
|
+
FROM finding_outcome_ledger
|
|
88
|
+
WHERE check_name = ?
|
|
89
|
+
ORDER BY last_seen DESC, first_seen DESC, finding_id DESC
|
|
90
|
+
LIMIT -1 OFFSET ?
|
|
91
|
+
)`)}}catch(n){wr("disabled (open failed)",n)}return ua.set(e,t),t}function qt(e,t,n){wr(`disabled (${t})`,n),ua.set(e,null)}function $P(e){if(!e)return null;try{TP(Jg(e),{recursive:!0});let t=new xu(e);return t.pragma("journal_mode = WAL"),t.pragma("busy_timeout = 250"),t.pragma("synchronous = NORMAL"),t.exec(`
|
|
92
|
+
CREATE TABLE IF NOT EXISTS file_evidence (
|
|
93
|
+
kind TEXT NOT NULL,
|
|
94
|
+
relative_path TEXT NOT NULL,
|
|
95
|
+
content_hash TEXT NOT NULL,
|
|
96
|
+
version TEXT NOT NULL,
|
|
97
|
+
payload TEXT NOT NULL,
|
|
98
|
+
last_accessed_at INTEGER NOT NULL,
|
|
99
|
+
PRIMARY KEY (kind, relative_path, content_hash, version)
|
|
100
|
+
);
|
|
101
|
+
CREATE INDEX IF NOT EXISTS idx_file_evidence_lru
|
|
102
|
+
ON file_evidence(last_accessed_at, kind, relative_path, content_hash, version);
|
|
103
|
+
`),{evidence:t,readFileEvidence:t.prepare("SELECT payload FROM file_evidence WHERE kind = ? AND relative_path = ? AND content_hash = ? AND version = ?"),writeFileEvidence:t.prepare(`INSERT INTO file_evidence (kind, relative_path, content_hash, version, payload, last_accessed_at)
|
|
104
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
105
|
+
ON CONFLICT(kind, relative_path, content_hash, version)
|
|
106
|
+
DO UPDATE SET payload = excluded.payload, last_accessed_at = excluded.last_accessed_at`),touchFileEvidence:t.prepare(`UPDATE file_evidence
|
|
107
|
+
SET last_accessed_at = ?
|
|
108
|
+
WHERE kind = ? AND relative_path = ? AND content_hash = ? AND version = ?
|
|
109
|
+
AND last_accessed_at < ?`)}}catch(t){return wr("shared cache disabled (open failed)",t),null}}function Cu(e,t,n){wr(`shared cache disabled (${t})`,n);try{e.shared?.evidence.close()}catch{}e.shared=null}function G9(e,t={}){if(!kP(e))return null;let n;try{n=new xu(e),n.pragma("busy_timeout = 50"),n.exec(`CREATE INDEX IF NOT EXISTS idx_file_evidence_lru
|
|
110
|
+
ON file_evidence(last_accessed_at, kind, relative_path, content_hash, version)`),n.pragma("wal_checkpoint(TRUNCATE)");let r=n.prepare("SELECT COUNT(*) AS count FROM file_evidence").get().count,i=t.maxRows??LP,o=t.budgetBytes??MP,s=Number(n.pragma("page_size",{simple:!0})),a=Number(n.pragma("page_count",{simple:!0})),c=Number(n.pragma("freelist_count",{simple:!0})),l=Math.max(0,a-c)*s,u=r>0&&l>o?Math.min(r,Math.ceil((l-o)/Math.max(1,l/r))):0,d=Math.max(r-i,u);return d>0&&(n.prepare(`DELETE FROM file_evidence WHERE rowid IN (
|
|
111
|
+
SELECT rowid FROM file_evidence ORDER BY last_accessed_at ASC, rowid ASC LIMIT ?
|
|
112
|
+
)`).run(d),n.pragma("wal_checkpoint(TRUNCATE)")),{deletedRows:d,remainingRows:r-d}}catch(r){return wr("shared cache maintenance skipped",r),null}finally{try{n?.close()}catch{}}}function Yg(e,t,n,r){let i=Gt(e);if(!i)return null;try{let o=i.readFileEvidence.get(t,n,r,pt)??i.readLegacyFileEvidence.get(t,n,r);if(o?.payload!==void 0)return o.payload;if(!Ru.has(t)||!i.shared)return null;try{let s=i.shared.readFileEvidence.get(t,n,r,pt);return s?.payload!==void 0&&HP(i.shared,t,n,r),s?.payload??null}catch(s){return Cu(i,"file_evidence read",s),null}}catch(o){return qt(e,"file_evidence read",o),null}}function HP(e,t,n,r){let i=Date.now();try{e.touchFileEvidence.run(i,t,n,r,pt,i-NP)}catch(o){wr("shared file_evidence recency touch skipped",o)}}function Xg(e,t,n,r,i){let o=Gt(e);if(o)try{if(o.writeFileEvidence.run(t,n,r,pt,i),Ru.has(t)&&o.shared)try{o.shared.writeFileEvidence.run(t,n,r,pt,i,Date.now())}catch(s){Cu(o,"file_evidence write",s)}}catch(s){qt(e,"file_evidence write",s)}}function Qg(e,t){if(t.length===0)return;let n=Gt(e);if(n)try{n.evidence.transaction(()=>{for(let i of t)n.writeFileEvidence.run(i.kind,i.relativePath,i.contentHash,pt,i.payload)})();let r=t.filter(i=>Ru.has(i.kind));if(r.length>0&&n.shared)try{n.shared.evidence.transaction(()=>{for(let i of r)n.shared.writeFileEvidence.run(i.kind,i.relativePath,i.contentHash,pt,i.payload,Date.now())})()}catch(i){Cu(n,"file_evidence batch write",i)}}catch(r){qt(e,"file_evidence batch write",r)}}function Zg(e,t,n,r){let i=Gt(e);if(!i)return null;try{return(i.readProjectEvidence.get(t,n,r,pt)??i.readLegacyProjectEvidence.get(t,n,r))?.payload??null}catch(o){return qt(e,"project_evidence read",o),null}}function eh(e,t,n,r,i){let o=Gt(e);if(o)try{o.writeProjectEvidence.run(t,n,r,pt,i)}catch(s){qt(e,"project_evidence write",s)}}function th(e,t,n,r){let i=Gt(e);if(!i)return new Map;try{let o=i.readCalleesForFile.all(t,n,r,pt),s=i.readLegacyCalleesForFile.all(t,n,r);return rh([...s,...o])}catch(o){return qt(e,"semantic_callees bulk read",o),new Map}}function nh(e,t,n){let r=Gt(e);if(!r)return new Map;try{let i=r.readReferencesForFile.all(t,n,pt),o=r.readLegacyReferencesForFile.all(t,n);return rh([...o,...i])}catch(i){return qt(e,"semantic_references bulk read",i),new Map}}function rh(e){let t=new Map;for(let n of e)t.set(n.symbol,n.payload);return t}function vu(e,t){if(t.length===0)return;let n=Gt(e);if(n)try{n.evidence.transaction(()=>{let r=new Set;for(let i of t){let o=`${i.relativePath}\0${i.contentHash}`;r.has(o)||(r.add(o),n.dropStaleCallees.run(i.relativePath,i.contentHash)),n.writeCallees.run(i.relativePath,i.symbol,i.contentHash,i.depsDigest,pt,i.payload)}})()}catch(r){qt(e,"semantic_callees write",r)}}function ih(e,t){if(t.length===0)return;let n=Gt(e);if(n)try{n.evidence.transaction(()=>{let r=new Set;for(let i of t){let o=`${i.relativePath}\0${i.projectFingerprint}`;r.has(o)||(r.add(o),n.dropStaleReferences.run(i.relativePath,i.projectFingerprint)),n.writeReferences.run(i.relativePath,i.symbol,i.projectFingerprint,pt,i.payload)}})()}catch(r){qt(e,"semantic_references write",r)}}function oh(e){let t=Gt(e);if(!t)return[];try{return da(t)}catch(n){return qt(e,"finding_outcome_ledger read",n),[]}}function sh(e,t,n,r={}){let i=Gt(e);if(!i)return{status:"unavailable",previous:[],current:[]};let o=r.busyTimeoutMs,s;try{if(o!==void 0){s=Number(i.evidence.pragma("busy_timeout",{simple:!0}));let c=Math.max(0,Math.min(6e4,Math.floor(o)));i.evidence.pragma(`busy_timeout = ${c}`)}return i.evidence.transaction(()=>{let c=da(i);if(i.claimFindingOutcomeObservation.run(t.observationId,t.fingerprint,t.observedAt).changes===0)return{status:i.readFindingOutcomeObservation.get(t.observationId)?.fingerprint===t.fingerprint?"duplicate":"conflict",previous:c,current:c};let u=[...n(c)],d=new Map(c.map(p=>[Su(p),p])),m=new Map,f=new Set;for(let p of u){let g=Su(p);if(m.has(g))throw new Error(`duplicate finding-outcome row in transition: ${p.check}/${p.findingId}`);m.set(g,p);let y=d.get(g);if(!y){if(p.timesShown<1)throw new Error(`new finding-outcome row has a non-positive count: ${p.check}/${p.findingId}`);f.add(p.check),i.upsertFindingOutcomeLedgerRow.run(p.check,p.findingId,p.firstSeen,p.lastSeen,p.timesShown,p.outcome);continue}let h=p.timesShown-y.timesShown;if(h<0)throw new Error(`finding-outcome count regressed: ${p.check}/${p.findingId}`);h>0?(f.add(p.check),i.upsertFindingOutcomeLedgerRow.run(p.check,p.findingId,p.firstSeen,p.lastSeen,h,p.outcome)):(p.firstSeen!==y.firstSeen||p.lastSeen!==y.lastSeen||p.outcome!==y.outcome)&&(f.add(p.check),i.updateFindingOutcomeLedgerRow.run(p.firstSeen,p.lastSeen,p.outcome,p.check,p.findingId))}for(let p of c)if(!m.has(Su(p)))throw new Error(`finding-outcome transition removed a row: ${p.check}/${p.findingId}`);for(let p of f)i.trimFindingOutcomeLedgerCheck.run(p,OP);return{status:"applied",previous:c,current:da(i)}}).immediate()}catch(a){if(GP(a)){let c=[];try{c=da(i)}catch{}return{status:"busy",previous:c,current:c}}return qt(e,"finding_outcome_ledger transition",a),{status:"unavailable",previous:[],current:[]}}finally{if(s!==void 0)try{i.evidence.pragma(`busy_timeout = ${Math.max(0,Math.floor(s))}`)}catch{}}}function da(e){return e.readFindingOutcomeLedger.all().map(n=>({check:n.check_name,findingId:n.finding_id,firstSeen:n.first_seen,lastSeen:n.last_seen,timesShown:n.times_shown,outcome:n.outcome}))}function Su(e){return`${e.check}\0${e.findingId}`}function GP(e){if(!e||typeof e!="object")return!1;let t=e.code;return t==="SQLITE_BUSY"||t==="SQLITE_BUSY_TIMEOUT"||t==="SQLITE_LOCKED"}import{appendFileSync as qP,mkdirSync as UP}from"fs";import{createHash as VP,randomUUID as zP}from"crypto";import{dirname as WP}from"path";import{performance as ci}from"perf_hooks";var uh="SCIP_QUERY_PROFILE",dh="SCIP_QUERY_PROFILE_OUT",mh="SCIP_QUERY_PROFILE_COMMAND",fh="SCIP_QUERY_PROFILE_CACHE_STATE",Iu="SCIP_QUERY_PROFILE_RUN_ID",wu="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY",Eu="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY_KIND",ph=[uh,dh,mh,fh,Iu,wu,Eu],K9=new Set(ph),ah=new Set,ch=new Map,lh=!1;function W(){let e=process.env[uh];return e==="1"||e==="true"}function KP(){return process.env[dh]}function gh(){return process.env[mh]}function JP(){return process.env[fh]}function hh(){let e=process.env[Iu];if(e)return e;if(!W())return;let t=zP();return process.env[Iu]=t,t}function yh(){return process.env[wu]}function YP(e){let t=yh();if(t)return t;if(!W())return;let n=hh();if(!n)return;let r=e.projectFingerprint?"published-project":"run-only",i=bo(["profile-workload-v1",e.toolVersion,e.command,e.projectFingerprint??n]);return process.env[wu]=i,process.env[Eu]=r,i}function bo(e){return VP("sha256").update(JSON.stringify(e)).digest("hex").slice(0,24)}function bh(){return Object.fromEntries(ph.flatMap(e=>{let t=process.env[e];return t===void 0?[]:[[e,t]]}))}function D(e,t,n){if(!W())return t();let r=ci.now();try{let i=t();return zn({type:"span",name:e,durationMs:Math.round(ci.now()-r),ok:!0,...ma(n)??{}}),i}catch(i){throw zn({type:"span",name:e,durationMs:Math.round(ci.now()-r),ok:!1,error:i instanceof Error?i.message:String(i),...ma(n)??{}}),i}}async function J9(e,t,n){if(!W())return t();let r=ci.now();try{let i=await t();return zn({type:"span",name:e,durationMs:Math.round(ci.now()-r),ok:!0,...ma(n)??{}}),i}catch(i){throw zn({type:"span",name:e,durationMs:Math.round(ci.now()-r),ok:!1,error:i instanceof Error?i.message:String(i),...ma(n)??{}}),i}}function zn(e,t=KP()){let n=XP(e),r={timestamp:new Date().toISOString(),pid:process.pid,runId:hh(),command:gh(),cacheState:JP(),...n,...e},i=`${JSON.stringify(r)}
|
|
113
|
+
`;if(t)try{let o=WP(t);ah.has(o)||(UP(o,{recursive:!0}),ah.add(o)),qP(t,i);return}catch(o){lh||(lh=!0,process.stderr.write(`[profile] failed to write ${t}: ${o instanceof Error?o.message:String(o)}
|
|
114
|
+
`));return}W()&&process.stderr.write(i)}function XP(e){let t=yh()??YP({command:gh()??"unknown",toolVersion:"unknown",projectFingerprint:null});if(!t)return{};let n=process.env[Eu],r=typeof e.name=="string"?e.name:void 0;if(!r)return{workloadIdentity:t,workloadIdentityKind:n};let i=r.split(/[.:]/,1)[0]??r,o=`${t}\0${r}`,s=ch.get(o);return s||(s=bo(["profile-subsystem-v1",t,r]),ch.set(o,s)),{workloadIdentity:t,workloadIdentityKind:n,subsystem:i,subsystemWorkIdentity:s}}function ma(e){return typeof e=="function"?e():e}import{spawnSync as QP}from"child_process";import{createHash as ZP}from"crypto";import{existsSync as ek,lstatSync as tk,realpathSync as nk}from"fs";import{dirname as rk,isAbsolute as ik,join as ok,resolve as pa}from"path";var li={run(e,t){let n=Sh(e,t);return n.kind==="success"?n.output:void 0},runResult:Sh},sk=["rev-parse","--show-toplevel","--absolute-git-dir","--git-common-dir","HEAD","HEAD^{tree}"],Du=/^[0-9a-f]{40,64}$/;function ku(e,t,n=li){if(!t||t.startsWith("-")||/[\0\r\n]/.test(t))throw new Error(`Invalid Git revision ${JSON.stringify(t)}.`);let r=n.runResult(e,["rev-parse","--verify","--end-of-options",`${t}^{commit}`]);if(r.kind!=="success"||!Du.test(r.output))throw new Error(`Git revision ${JSON.stringify(t)} does not resolve to exactly one commit.`);return r.output}function t8(e,t=li){let n=t.run(e,["rev-parse","--show-toplevel"])?.trim();return n?Yt(n):void 0}function ui(e,t=li){let n=t.runResult(e,sk);if(n.kind==="success"){let r=ak(n.output);if(r)return ck(r,t)}return lk(e,t)}function ak(e){let t=e.split(`
|
|
115
|
+
`).map(c=>c.trim());if(t.length!==5)return;let[n,r,i,o,s]=t;if(!n||!r||!i||!o||!s||!Du.test(o)||!Du.test(s))return;let a=Yt(n);return{root:a,gitDir:Yt(fa(a,r)),commonDir:Yt(fa(a,i)),headCommit:o,treeOid:s}}function ck(e,t){let n=t.run(e.root,["status","--porcelain=v1","-z","--untracked-files=all"]);return n===void 0?void 0:{...xh(e.root,e.gitDir),commonDir:e.commonDir,repositoryId:Tu("repository",e.commonDir),headCommit:e.headCommit,treeOid:e.treeOid,clean:n.length===0}}function lk(e,t){let n=uk(e,t);if(n.kind!=="worktree")return;let r=n.identity,i=r.projectRoot,o=t.run(i,["rev-parse","--git-common-dir"])?.trim();if(!o)return;let s=Yt(fa(i,o)),a=Pu(t.run(i,["rev-parse","--verify","HEAD"])),c=Pu(t.run(i,["rev-parse","--verify","HEAD^{tree}"])),l=t.run(i,["status","--porcelain=v1","-z","--untracked-files=all"]);if(l!==void 0)return{...r,commonDir:s,repositoryId:Tu("repository",s),headCommit:a,treeOid:c,clean:l.length===0}}function uk(e,t=li){let n=t.runResult(e,["rev-parse","--show-toplevel"]);if(n.kind==="not-repository")return{kind:"non-git"};if(n.kind==="error")return n;let r=n.output.trim();if(!r)return{kind:"error",message:"Git returned an empty worktree root."};let i=Yt(r),o=t.run(i,["rev-parse","--absolute-git-dir"])?.trim();if(!o)return{kind:"error",message:"Git did not return an absolute worktree directory."};let s=Yt(fa(i,o));return{kind:"worktree",identity:xh(i,s)}}function xh(e,t){return{projectRoot:e,gitDir:t,worktreeId:Tu("worktree",`${e}\0${t}`)}}function Rh(e,t=li){let n=t.run(e,["worktree","list","--porcelain","-z"]);return n===void 0?[]:dk(n)}function dk(e){let t=[],n;for(let r of e.split("\0")){if(r===""){n&&t.push(n),n=void 0;continue}let i=r.indexOf(" "),o=i<0?r:r.slice(0,i),s=i<0?"":r.slice(i+1);if(o==="worktree"){n&&t.push(n),n={path:Yt(s),detached:!1,bare:!1,prunable:!1,locked:!1};continue}n&&(o==="HEAD"?n.head=s:o==="branch"?n.branch=s:o==="detached"?n.detached=!0:o==="bare"?n.bare=!0:o==="prunable"?n.prunable=!0:o==="locked"&&(n.locked=!0))}return n&&t.push(n),t}function n8(e,t,n=li){return Pu(n.run(e,t))}function fa(e,t){return ik(t)?t:pa(e,t)}function Yt(e){try{return nk(e)}catch{return pa(e)}}function Tu(e,t){return ZP("sha256").update(`${e}\0${t}`).digest("hex").slice(0,24)}function Pu(e){return e?.trim()||void 0}function Sh(e,t){let n=QP("git",["-C",e,...t],{encoding:"utf-8",env:{...process.env,LC_ALL:"C"},maxBuffer:52428800,stdio:["ignore","pipe","pipe"],timeout:3e4,killSignal:"SIGKILL"});if(n.status===0)return{kind:"success",output:n.stdout.trimEnd()};let i=(typeof n.stderr=="string"?n.stderr.trim():"")||n.error?.message||`git exited with status ${n.status??"unknown"}`,o=n.error?.code;return(/not a git repository/i.test(i)||o==="ENOENT"&&ek(pa(e)))&&!mk(e)?{kind:"not-repository"}:{kind:"error",message:i}}function mk(e){if(process.env.GIT_DIR||process.env.GIT_COMMON_DIR)return!0;let t=pa(e);for(;;){try{return tk(ok(t,".git")),!0}catch(r){let i=r.code;if(i!=="ENOENT"&&i!=="ENOTDIR")return!0}let n=rk(t);if(n===t)return!1;t=n}}var fk={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function Te(e){if(e.startsWith("local "))return{kind:"local",id:e.slice(6),raw:e};let t=e.split(" ");if(t.length<4)return{scheme:t[0]??"",manager:t[1]??"",packageName:t[2]??"",version:"",descriptors:[],raw:e};let n=t[0],r=t[1],i=e.slice(n.length+1+r.length+1),o;if(i.startsWith("`")){let l=i.indexOf("`",1);l===-1?(o=i.slice(1),i=""):(o=i.slice(1,l),i=i.slice(l+2))}else{let l=i.indexOf(" ");l===-1?(o=i,i=""):(o=i.slice(0,l),i=i.slice(l+1))}let s,a=i.indexOf(" ");a===-1?(s=i,i=""):(s=i.slice(0,a),i=i.slice(a+1));let c=pk(i);return{scheme:n,manager:r,packageName:o,version:s,descriptors:c,raw:e}}function Xt(e){let t=Te(e);if("kind"in t)return null;for(let n=t.descriptors.length-2;n>=0;n--){let r=t.descriptors[n];if(r?.suffix==="type")return r.name}return null}function pk(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="["){let o=e.indexOf("]",n+1);if(o===-1){t.push({name:e.slice(n+1),suffix:"type-param"});break}t.push({name:e.slice(n+1,o),suffix:"type-param"}),n=o+1;continue}if(e[n]==="("&&(t.length===0||n===0||Ch(e[n-1]))){let o=e.indexOf(")",n+1);if(o!==-1&&e[o+1]!=="."){t.push({name:e.slice(n+1,o),suffix:"parameter"}),n=o+1;continue}}let r;if(e[n]==="`"){let o=e.indexOf("`",n+1);if(o===-1){r=e.slice(n+1),t.push({name:r,suffix:"term"});break}r=e.slice(n+1,o),n=o+1}else{let o=n;for(;n<e.length&&!Ch(e[n]);)n++;r=e.slice(o,n)}if(n>=e.length){r&&t.push({name:r,suffix:"term"});break}let i=e[n];if(i==="("){let o=e.indexOf(")",n+1);o!==-1&&e[o+1]==="."?(t.push({name:r,suffix:"method"}),n=o+2):o!==-1?(t.push({name:r,suffix:"method"}),n=o+1):(t.push({name:r,suffix:"term"}),n++)}else{let o=fk[i];o&&t.push({name:r,suffix:o}),n+=1}}return t}function Ch(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function E(e){let t=Te(e);if("kind"in t&&t.kind==="local")return`local:${t.id}`;let n=t;if(n.descriptors.length===0)return n.raw;let r=[];for(let i of n.descriptors){let o=gk(i);o&&r.push(o)}return r.join(":")}function gk(e){let t=e.suffix==="namespace"?hk(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function hk(e){return e.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/,"").replace(/\.(py|pyi)$/,"").replace(/\.(rs)$/,"").replace(/\.(java|scala|kt|kts)$/,"").replace(/\.(rb)$/,"").replace(/\.(go)$/,"").replace(/\.(cs|vb)$/,"").replace(/\.(dart)$/,"").replace(/\.(php)$/,"").replace(/\.(c|cc|cpp|cxx|h|hpp)$/,"")}function T(e){let t=Te(e);if("kind"in t&&t.kind==="local")return t.id;let n=t;return n.descriptors.length===0?"":n.descriptors[n.descriptors.length-1].name}function be(e){let t=Te(e);if("kind"in t&&t.kind==="local")return null;let n=t;return n.descriptors[n.descriptors.length-1]?.suffix??null}function ye(e){return e.endsWith("().")||be(e)==="method"}function ae(e){let t=be(e);return t==="method"?!0:t!=="term"?!1:e.endsWith("().")?!0:e.startsWith("rust-analyzer ")&&e.includes("#")?!1:e.startsWith("scip-typescript ")?!/#[A-Za-z0-9_$]+\.$/.test(e):!0}function Wn(e){return be(e)==="namespace"}var yk=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function $e(e){return yk.test(e)}var bk=new Set(["test","tests","_tests"]);function di(e){let t=Te(e);if("kind"in t)return!1;for(let n=0;n<t.descriptors.length-1;n+=1){let r=t.descriptors[n];if(r?.suffix==="namespace"&&r.name&&bk.has(r.name))return!0}return!1}function vh(e,t){let n=Te(e),r=Te(t);if("kind"in n||"kind"in r)return!1;let i=n.descriptors,o=r.descriptors;if(o.length!==i.length+1)return!1;for(let s=0;s<i.length;s++){let a=i[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}function Ih(e,t){let n=Te(e),r=Te(t);if("kind"in n||"kind"in r)return!1;let i=n.descriptors,o=r.descriptors;if(o.length<=i.length)return!1;for(let s=0;s<i.length;s++){let a=i[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}import{extname as wh}from"path";var Sk={".rs":"rust",".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".pyi":"python",".java":"java",".kt":"kotlin",".kts":"kotlin",".scala":"scala",".sc":"scala",".rb":"ruby",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".hxx":"cpp",".cs":"csharp",".php":"php",".vb":"vb",".clj":"clojure",".cljs":"clojure",".cljc":"clojure"};function N(e){return Sk[wh(e).toLowerCase()]??null}function hn(e){return wh(e).toLowerCase()===".vue"}import{createRequire as xk}from"module";var Qe=xk(import.meta.url),So=null,Fu=!1;function Eh(){if(Fu)return null;if(So)return So;try{return So=Qe("tree-sitter"),So}catch{return Fu=!0,null}}function c8(e){if(e==="clojure")return"reader";let t=Eh();if(!t)return"unavailable";let n=Dh(e);if(!n)return"unavailable";try{return new t().setLanguage(n),"ast"}catch{return mi.add(e),"unavailable"}}var _u=new Map,mi=new Set;function Dh(e){if(mi.has(e))return null;let t=_u.get(e);if(t)return t;let n;try{switch(e){case"rust":n=Qe("tree-sitter-rust");break;case"typescript":n=Qe("tree-sitter-typescript").typescript;break;case"tsx":n=Qe("tree-sitter-typescript").tsx;break;case"javascript":n=Qe("tree-sitter-javascript");break;case"python":n=Qe("tree-sitter-python");break;case"java":n=Qe("tree-sitter-java");break;case"kotlin":n=Qe("tree-sitter-kotlin");break;case"scala":n=Qe("tree-sitter-scala");break;case"ruby":n=Qe("tree-sitter-ruby");break;case"c":n=Qe("tree-sitter-c");break;case"cpp":n=Qe("tree-sitter-cpp");break;case"csharp":n=Qe("tree-sitter-c-sharp");break;case"php":n=Qe("tree-sitter-php").php;break;case"vb":{let r=Qe("tree-sitter-vb-dotnet");n=r.language??r;break}case"clojure":return mi.add(e),null}}catch{return mi.add(e),null}return _u.set(e,n),n}var Au=new Map;function l8(){So=null,Fu=!1,_u.clear(),mi.clear(),Au.clear(),vk.clear()}function Rk(e){let t=Au.get(e);if(t)return t;let n=Dh(e);if(!n)return null;let r=Eh();if(!r)return null;let i=new r;try{i.setLanguage(n)}catch{return mi.add(e),null}return Au.set(e,i),i}function Ck(e,t){return e.parse(r=>r>=t.length?null:t.slice(r,Math.min(t.length,r+16384)))}function xo(e,t){let n=Rk(e);if(!n)return null;try{return Ck(n,t)}catch{return null}}var vk=new Map;import{execFileSync as kk}from"child_process";import{createHash as Ah}from"crypto";import{closeSync as Tk,fstatSync as Lh,lstatSync as Mh,openSync as Fk,readdirSync as _k,readFileSync as Ak,readlinkSync as Lk,realpathSync as ha}from"fs";import{isAbsolute as Mk,join as Nh,relative as Nk,resolve as Ok,sep as Bk}from"path";import{isAbsolute as Ph,relative as Ik}from"path";var Ze=class extends Error{constructor(n,r){super(`refusing unsafe project file path ${JSON.stringify(n)} (${r})`);this.relativePath=n;this.reason=r;this.name="UnsafeProjectPathError"}relativePath;reason;code="SCIP_QUERY_UNSAFE_PROJECT_PATH"};function yn(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function te(e){return e.replace(/\\/g,"/")}function gt(e,t){return yn(e)===yn(t)}function fi(e,t){let n=Ik(e,t);return n===""||!n.startsWith("..")&&!Ph(n)}function ht(e){if(!e)throw new Ze(e,"empty-path");if(e.includes("\0"))throw new Ze(e,"nul-byte");if(Ph(e)||/^[A-Za-z]:/.test(e)||e.startsWith("//")||e.startsWith("\\\\"))throw new Ze(e,"absolute-path");let t=yn(e);if(t.split("/").some(r=>r===".."))throw new Ze(e,"parent-traversal");if(!t||t===".")throw new Ze(e,"empty-path");return t}import{closeSync as Lu,fstatSync as ga,openSync as Mu,readFileSync as wk,readSync as kh}from"fs";import{createHash as Ek}from"crypto";var Ie=8*1024*1024,He=64*1024*1024,Me=512*1024*1024,Th=256*1024*1024,Qt=class extends Error{constructor(n,r,i,o,s){let a=i==="too-large"?`is ${o} bytes; the safety limit is ${s} bytes`:i==="not-regular"?"is not a regular file":"changed while it was being read";super(`${n} ${JSON.stringify(r)} ${a}`);this.inputKind=n;this.inputPath=r;this.reason=i;this.observedBytes=o;this.limitBytes=s;this.name="BoundedFileReadError"}inputKind;inputPath;reason;observedBytes;limitBytes;code="SCIP_QUERY_BOUNDED_FILE_READ"};function Se(e,t){ju(t.maxBytes);let n=String(e),r=Mu(e,"r");try{let i=ga(r);_h(i,t,n);let o=wk(r),s=ga(r);if(s.dev!==i.dev||s.ino!==i.ino||s.size!==i.size||o.byteLength!==i.size)throw new Qt(t.inputKind,n,"changed-during-read",s.size,t.maxBytes);return o}finally{Lu(r)}}function J(e,t,n="utf8"){return Se(e,t).toString(n)}function O(e,t){return J(e,{maxBytes:Ie,inputKind:t})}function Dk(e,t){return J(e,{maxBytes:He,inputKind:t})}function Pk(e,t){return J(e,{maxBytes:Th,inputKind:t})}function Nu(e,t){ju(t.maxBytes);let n=[],r=Buffer.allocUnsafe(64*1024),i=0;for(;;){let o=kh(e,r,0,r.length,null);if(o===0)break;if(i+=o,!Number.isSafeInteger(i)||i>t.maxBytes)throw new Qt(t.inputKind,`file descriptor ${e}`,"too-large",i,t.maxBytes);n.push(Buffer.from(r.subarray(0,o)))}return Buffer.concat(n,i)}function Ou(e,t,n="utf8"){return Nu(e,t).toString(n)}function Fh(e,t){let n=Mu(e,"r");try{return Nu(n,t)}finally{Lu(n)}}function Bu(e,t,n="utf8"){return Fh(e,t).toString(n)}function pi(e,t,n){ju(t.maxBytes);let r=String(e),i=Mu(e,"r");try{let o=ga(i);_h(o,t,r);let s=Buffer.allocUnsafe(Math.min(1024*1024,Math.max(1,o.size))),a=0;for(;a<o.size;){let l=kh(i,s,0,Math.min(s.length,o.size-a),a);if(l===0)break;n(s.subarray(0,l)),a+=l}let c=ga(i);if(c.dev!==o.dev||c.ino!==o.ino||c.size!==o.size||a!==o.size)throw new Qt(t.inputKind,r,"changed-during-read",c.size,t.maxBytes);return a}finally{Lu(i)}}function Zt(e,t){let n=Ek("sha256");return pi(e,t,r=>n.update(r)),n.digest("hex")}function _h(e,t,n){if(!e.isFile())throw new Qt(t.inputKind,n,"not-regular",Number(e.size),t.maxBytes);if(e.size>t.maxBytes)throw new Qt(t.inputKind,n,"too-large",Number(e.size),t.maxBytes)}function ju(e){if(!Number.isSafeInteger(e)||e<0)throw new RangeError(`maxBytes must be a non-negative safe integer; received ${e}`)}var ya=64*1024*1024,Ro=class extends Error{constructor(n,r,i,o){super(`${n} ${JSON.stringify(r)} is ${i} bytes; the safety limit is ${o} bytes`);this.inputKind=n;this.inputPath=r;this.observedBytes=i;this.limitBytes=o;this.name="InputTooLargeError"}inputKind;inputPath;observedBytes;limitBytes;code="SCIP_QUERY_INPUT_TOO_LARGE"};function jk(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function bn(e,t,n={}){let r=ht(t),i=ha(e),o=Ok(i,...r.split("/"));if(!fi(i,o)||o===i)throw new Ze(t,"outside-project");let s=ha(o);if(!fi(i,s)||s===i)throw new Ze(t,"outside-project");let a=Mh(s);if(!a.isFile())throw new Ze(t,"not-a-file");let c={projectRoot:i,relativePath:r,absolutePath:s,size:a.size,mtimeMs:a.mtimeMs,device:a.dev,inode:a.ino},l=n.maxBytes??ya;if($k(l),c.size>l)throw new Ro(n.inputKind??"project file",c.relativePath,c.size,l);return c}function ba(e,t,n={}){let r=bn(e,t,n),i=n.maxBytes??ya,o=Fk(r.absolutePath,"r");try{let s=Lh(o);if(!s.isFile()||s.dev!==r.device||s.ino!==r.inode||s.size!==r.size)throw new Ze(t,"changed-during-read");if(s.size>i)throw new Ro(n.inputKind??"project file",r.relativePath,s.size,i);let a=Ak(o),c=Lh(o);if(c.dev!==s.dev||c.ino!==s.ino||c.size!==s.size||a.byteLength!==s.size)throw new Ze(t,"changed-during-read");return a}finally{Tk(o)}}function de(e,t,n={}){return ba(e,t,n).toString("utf8")}function we(e){return typeof e=="object"&&e!==null&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function st(e,t){try{return bn(e,t),!0}catch(n){if(we(n))return!1;throw n}}function $k(e){if(!Number.isSafeInteger(e)||e<0)throw new RangeError(`maxBytes must be a non-negative safe integer; received ${e}`)}function Hk(e){return(qk(e)??Uk(e)).filter(t=>t&&!Oh(t)).sort()}function $u(e,t={}){let n=Hk(e).filter(i=>!t.language||Gg(i,t.language,t.markerFiles)).filter(i=>!t.includePath||t.includePath(i)),r=ha(e);return n.map(i=>{let o=Nh(e,i);try{if(Mh(o).isSymbolicLink()){let c=ha(o),l=Nk(r,c);if(l===".."||l.startsWith(`..${Bk}`)||Mk(l))throw new Error("external symlink");let u=Lk(o);return{path:i,size:Buffer.byteLength(u),hash:Ah("sha256").update("symlink\0").update(u).digest("hex")}}let s=Ah("sha256"),a=pi(o,{inputKind:"project fingerprint input",maxBytes:ya},c=>s.update(c));return{path:i,size:a,hash:s.digest("hex")}}catch{return{path:i,size:-1,hash:"unreadable"}}})}function Co(e,t,n){return{version:2,languages:[...t].sort(),pnpmWorkspaces:n.typescriptProjectMode!=="workspace"&&n.pnpmWorkspaces===!0,typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:jk(n.typescriptProjects),clojureConfigPath:Gk(n.clojureConfigPath),files:$u(e)}}function Gk(e){return e?.trim()||void 0}function qk(e){try{return kk("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"}).split(`
|
|
116
|
+
`).filter(Boolean)}catch{return null}}function Uk(e){let t=[],n=[""];for(;n.length>0;){let r=n.pop(),i=r?Nh(e,r):e,o;try{o=_k(i,{withFileTypes:!0})}catch{continue}for(let s of o){let a=r?`${r}/${s.name}`:s.name;if(s.isDirectory()){Oh(a)||n.push(a);continue}t.push(a)}}return t}function Oh(e){let t=e.split("/");return e==="meta.json"||t[0]===".scipquery"&&(t[1]==="events"||t[1]==="ledger"||t[1]==="releases"||t[1]==="suppressions")||t.some(n=>Vk.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var Vk=new Set([".git","node_modules",".scipquery-cache",".scipquery-generations",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]);var zk=$("source-text",{clearGroups:["whole-project","source-file"]}),Wk=$("source-lines",{clearGroups:["whole-project","source-file"]});function k(e,t){let n=t.replace(/\\/g,"/");return zk.get(e,n,()=>{try{return de(e.config.projectRoot,n,{inputKind:"indexed source file"})}catch(r){if(we(r))return"";throw r}})}function Ne(e,t){let n=t.replace(/\\/g,"/");return Wk.get(e,n,()=>{let r=k(e,n);return r?r.split(`
|
|
117
|
+
`):[]})}var Kk=/^\s*(?:\/\/|#|\/\*+|\*)\s*scip-query[\s:-]*ignore(?:[\s:-]+(dead(?:-code)?|stale|wrapper|passthrough|drift|extract|similar|twin))?\b/i;function vo(e){let t=Kk.exec(e);return t?t[1]??"":null}function Sa(e,t,n){return Bh(e,t,n).length>0}function xa(e,t,n,r){let i=r.toLowerCase();return Bh(e,t,n).some(o=>o.toLowerCase()===i)}function Bh(e,t,n){if(n<=0)return[];let r=Ne(e,t);if(r.length===0)return[];let i=[];for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(r[o]??"").trim();if(s==="")continue;let a=vo(s);if(a!==null){i.push(a);continue}if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return i}return i}import{posix as Hu}from"path";import{parse as Jk}from"@vue/compiler-sfc";var Yk=Vn("vue-sfc-units");function gi(e,t){let n=Hh(t),r=k(e,n);return Yk.get(e,n,r,()=>Gu(e,n,r))}function Hh(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function Xk(e){let t=e?.toLowerCase();return!t||t==="js"||t==="javascript"||t==="jsx"?"javascript":t==="ts"||t==="typescript"?"typescript":t==="tsx"?"tsx":null}function Er(e){return!e||e.body.length===0?0:e.body.split(`
|
|
118
|
+
`).length}function Gu(e,t,n){let r={relativePath:t,template:null,scripts:[],styles:[],customBlocks:[],errors:[]};if(!n)return r;let i;try{i=Jk(n,{filename:t})}catch(s){return r.errors.push($h(s)),r}r.errors.push(...i.errors.map($h));let{descriptor:o}=i;return o.template&&(r.template=Ra(e,t,"template",o.template)),o.script&&r.scripts.push(jh(e,t,o.script,!1)),o.scriptSetup&&r.scripts.push(jh(e,t,o.scriptSetup,!0)),r.styles=o.styles.map(s=>Ra(e,t,"style",s)),r.customBlocks=o.customBlocks.map(s=>Ra(e,t,"custom",s)),r.errors.push(...[r.template,...r.scripts,...r.styles,...r.customBlocks].flatMap(s=>s?.errors??[])),r}function jh(e,t,n,r){let i=Ra(e,t,"script",n);return{...i,kind:"script",setup:r,astLanguage:Xk(i.lang)}}function Ra(e,t,n,r){let i=Zk(r.attrs),o=typeof i.lang=="string"?i.lang:null,s=typeof i.src=="string"?i.src:typeof r.src=="string"?r.src:void 0;if(s){let c=Qk(t,s);if(!c)return{kind:n,ownerPath:t,sourcePath:t,external:!0,src:s,attrs:i,lang:o,body:"",startLine:0,endLine:0,errors:[`Could not resolve Vue ${n} block source: ${s}`]};let l=k(e,c),u=l?Math.max(0,l.split(`
|
|
119
|
+
`).length-1):0;return{kind:n,ownerPath:t,sourcePath:c,external:!0,src:s,attrs:i,lang:o,body:l,startLine:0,endLine:u,errors:l?[]:[`Vue ${n} block source not found: ${c}`]}}let a=Math.max(0,r.loc.start.line-1);return{kind:n,ownerPath:t,sourcePath:t,external:!1,attrs:i,lang:o,body:r.content,startLine:a,endLine:Math.max(a,r.loc.end.line-1),errors:[]}}function Qk(e,t){let n=t.split(/[?#]/,1)[0];if(!n||n.startsWith("/")||n.includes("://"))return null;let r=Hh(Hu.normalize(Hu.join(Hu.dirname(e),n)));return r===".."||r.startsWith("../")?null:r}function Zk(e){return{...e}}function $h(e){return e instanceof Error?e.message:String(e)}function Ca(e,t,n){let i=Gu(e,t,n).scripts.filter(s=>s.astLanguage&&s.body.length>0),o=i[0]?.astLanguage;return o?{body:i.map(s=>`${`
|
|
120
|
+
`.repeat(s.startLine)}${s.body}`).join(`
|
|
121
|
+
`),startLine:0,language:o}:null}var Gh=Ir("ast-trees",{clearGroups:["whole-project","source-file"]});function ne(e,t){if(hn(t))return eT(e,t);let n=N(t);if(!n)return null;let r=k(e,t);return r?Gh.get(e,t,r,()=>xo(n,r)):null}function eT(e,t){let n=k(e,t);return n?Gh.get(e,t,n,()=>{let r=Ca(e,t,n);if(!r)return null;let i=`
|
|
122
|
+
`.repeat(r.startLine)+r.body;return xo(r.language,i)}):null}function hi(e,t){let n=tT(e,t);if(!n)return null;let r=Dr(n);return r?{calleeLeaf:r,memberAccess:nT(n),line:e.startPosition.row}:null}function tT(e,t){if(t==="rust")return e.type==="call_expression"?e.childForFieldName("function")??e.namedChild(0):e.type==="macro_invocation"?e.childForFieldName("macro")??e.namedChild(0):null;if(t==="python")return e.type!=="call"?null:e.childForFieldName("function")??e.namedChild(0);if(t==="typescript"||t==="tsx"||t==="javascript"){if(e.type==="call_expression")return e.childForFieldName("function")??e.namedChild(0);if(e.type==="new_expression")return e.childForFieldName("constructor")??e.namedChild(0)}return null}function nT(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}function Dr(e){switch(e.type){case"identifier":case"type_identifier":case"field_identifier":case"property_identifier":case"shorthand_property_identifier":return e.text;case"field_expression":case"member_expression":case"attribute":{let t=e.namedChild(e.namedChildCount-1);return t?Dr(t):null}case"generic_function":{let t=e.childForFieldName("function")??e.namedChild(0);return t?Dr(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?Dr(t):null}case"super":case"self":case"this":return null;default:return null}}var rT=[at("source-facts",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/source/source-facts.ts"}),at("file-definitions",{dependsOn:["content-hash","project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","contentHash","projectFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/symbols/definition-catalog.ts"}),at("definition-exclusions",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/analysis/framework-patterns.ts"}),at("doc-path-tokens",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-products.test.ts",owner:"tests/storage/evidence-cache.test.ts"}),at("doc-path-evidence",{dependsOn:["content-hash","git-history","git-head","tool-version"],keyParts:["kind","relativePath","contentHash","trackedFiles","historyWindow","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/queries/cleanup/doc-drift.ts"}),at("source-imports",{dependsOn:["content-hash","import-resolution-fingerprint","config","tool-version"],keyParts:["kind","relativePath","contentHash","importResolutionFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/language-parsers/index.ts"}),at("source-reexports",{dependsOn:["content-hash","import-resolution-fingerprint","config","tool-version"],keyParts:["kind","relativePath","contentHash","importResolutionFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/language-parsers/index.ts"}),at("source-fingerprints",{dependsOn:["content-hash","project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","contentHash","projectFingerprint","payloadVersion"],stalenessTest:"tests/symbols/definition-catalog.test.ts",owner:"src/queries/cleanup/similar.ts"}),at("consumer-file-usage",{dependsOn:["content-hash","project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","contentHash","projectFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/queries/internal/consumer-evidence.ts"}),at("react-component-behavior-profiles",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/source/react-profile.ts"}),at("git-file-adds",{dependsOn:["git-head","git-history","tool-version"],keyParts:["kind","cacheKey","head","historyWindow","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/analysis/git-history.ts"}),at("typescript-reference-fragments",{dependsOn:["content-hash","transitive-deps-digest","config","tool-version"],keyParts:["kind","relativePath","semanticIdentity","payloadVersion"],stalenessTest:"tests/semantic/typescript/typescript-reference-fragments.test.ts",owner:"src/semantic/typescript/reference-fragment-shadow.ts"}),at("typescript-import-usage",{dependsOn:["content-hash","transitive-deps-digest","config","tool-version"],keyParts:["kind","relativePath","semanticIdentity","payloadVersion"],stalenessTest:"tests/semantic/typescript/typescript-semantic-provider.test.ts",owner:"src/semantic/shared-primitives.ts"}),at("typescript-signatures",{dependsOn:["content-hash","transitive-deps-digest","config","tool-version"],keyParts:["kind","relativePath","semanticIdentity","payloadVersion"],stalenessTest:"tests/semantic/typescript/typescript-semantic-provider.test.ts",owner:"src/semantic/shared-primitives.ts"}),va("file-dependency-graph",{dependsOn:["project-fingerprint","indexed-language-set","import-resolution-fingerprint","tool-version"],keyParts:["kind","scope","projectFingerprint","payloadVersion"],stalenessTest:"tests/symbols/file-dep-graph.test.ts",owner:"src/symbols/graph/file-dep-graph.ts"}),va("semantic-import-usage",{dependsOn:["project-fingerprint","indexed-language-set","import-resolution-fingerprint","tool-version"],keyParts:["kind","relativePath","projectFingerprint","language","semanticEngine","payloadVersion"],stalenessTest:"tests/semantic/rust/rust-semantic-cache-gate.test.ts",owner:"src/semantic/shared-primitives.ts"}),va("semantic-signatures",{dependsOn:["project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","symbol","projectFingerprint","language","semanticEngine","payloadVersion"],stalenessTest:"tests/semantic/rust/rust-semantic-cache-gate.test.ts",owner:"src/semantic/shared-primitives.ts"}),va("health-semantic-prewarm",{dependsOn:["project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","scope","cliVersion","projectFingerprint","payloadVersion"],stalenessTest:"tests/runtime/cli-support.test.ts",owner:"src/runtime/cli-support.ts"})];function me(e){let t=new Map;return{kind:e.kind,read(n,r,i){let o=!1,s=0,a;if(W()){let c=We(n);if(c){let l=`${c}\0${r}\0${i}`;a=t.get(l),a||(a=bo(["evidence-product-file-read-v1",e.kind,c,r,i]),t.set(l,a))}}return D("evidence-product.file.read",()=>{let c=Yg(n,e.kind,r,i);if(c===null)return null;s=c.length;try{let l=e.deserialize(c);return o=l!==null,l}catch{return null}},()=>({...a?{workIdentity:a,workOutcome:"computed"}:{},scope:"file",kind:e.kind,available:!0,hit:o,payloadBytes:s}))},write(n,r,i,o){Xg(n,e.kind,r,i,e.serialize(o))},writeBatch(n,r){Qg(n,r.map(i=>({kind:e.kind,relativePath:i.relativePath,contentHash:i.contentHash,payload:e.serialize(i.value)})))}}}function Pr(e){let t=new Map;return{kind:e.kind,read(n,r,i){let o=!1,s=0,a;if(W()){let c=`${i}\0${r}`;a=t.get(c),a||(a=bo(["evidence-product-project-read-v1",e.kind,i,r]),t.set(c,a))}return D("evidence-product.project.read",()=>{let c=Zg(n,e.kind,r,i);if(c===null)return null;s=c.length;try{let l=e.deserialize(c);return o=l!==null,l}catch{return null}},()=>({...a?{workIdentity:a,workOutcome:"computed"}:{},scope:"project",kind:e.kind,available:!0,hit:o,payloadBytes:s}))},write(n,r,i,o){eh(n,e.kind,r,i,e.serialize(o))}}}function re(e){let t=rT.find(n=>n.kind===e);if(!t)throw new Error(`missing evidence product manifest entry for ${e}`);return t.invalidation}function at(e,t){return{scope:"file",kind:e,invalidation:{scope:"file",...t}}}function va(e,t){return{scope:"project",kind:e,invalidation:{scope:"project",...t}}}function Io(e){return e.type==="comment"||e.type==="line_comment"||e.type==="block_comment"}var iT=new Set(["function_declaration","method_definition","method_signature","function_signature"]);function Ia(e,t){let n=sT(e,t);if(n)return{name:n.name,startLine:n.definitionNode.startPosition.row,endLine:n.definitionNode.endPosition.row,paramCount:Vh(n.functionNode),params:qh(n.functionNode),paramsEndLine:Uh(n.functionNode),isLiteralPassthrough:zh(n.functionNode,t)};if(!oT(e.type,t))return null;let r=e.childForFieldName("name")??e.namedChildren.find(i=>i.type==="identifier"||i.type==="property_identifier");return r?{name:r.text,startLine:e.startPosition.row,endLine:e.endPosition.row,paramCount:Vh(e),params:qh(e),paramsEndLine:Uh(e),isLiteralPassthrough:zh(e,t)}:null}function Wh(e){return e.namedChildren.find(t=>t.type==="parameters"||t.type==="formal_parameters")}function qh(e){let t=Wh(e);if(!t)return[];let n=[];for(let r of t.namedChildren){if(Io(r))continue;if(r.type==="identifier"){n.push({name:r.text,simple:!0});continue}let i=r.namedChildren.some(a=>a.type.endsWith("_modifier"))||/^\s*(?:public|private|protected|readonly|override)\b/.test(r.text),o=r.childForFieldName("pattern");if(!i&&o&&o.type==="identifier"){n.push({name:o.text,simple:!0});continue}let s=r.namedChildren.find(a=>a.type==="identifier");n.push({name:o?.type==="identifier"?o.text:s?.text??"",simple:!1})}return n}function Uh(e){let t=Wh(e);return t?t.endPosition.row:e.startPosition.row}function oT(e,t){return t==="rust"?e==="function_item"||e==="function_signature_item":t==="python"?e==="function_definition":t==="typescript"||t==="tsx"||t==="javascript"?iT.has(e):!1}function sT(e,t){if(t!=="typescript"&&t!=="tsx"&&t!=="javascript")return null;if(e.type==="variable_declarator"){let n=e.childForFieldName("name")??e.namedChild(0),r=e.childForFieldName("value")??e.namedChild(1);return!n||!r||r.type!=="arrow_function"&&r.type!=="function_expression"?null:{name:n.text,definitionNode:e,functionNode:r}}if(e.type==="public_field_definition"){let n=e.childForFieldName("name")??e.namedChild(0),r=e.childForFieldName("value")??e.namedChild(1);return!n||!r||r.type!=="arrow_function"&&r.type!=="function_expression"?null:{name:n.text,definitionNode:e,functionNode:r}}return null}function Vh(e){let t=e.namedChildren.find(r=>r.type==="parameters"||r.type==="formal_parameters");if(!t)return 0;let n=0;for(let r of t.namedChildren)Io(r)||(n+=1);return n}function zh(e,t){let n=e.namedChildren.find(d=>d.type==="block"||d.type==="statement_block");if(!n)return!1;let r=n.namedChildren.filter(d=>!Io(d));if(r.length!==1)return!1;let i=r[0],o=null;if(i.type==="return_statement"||i.type==="expression_statement"?o=i.namedChild(0)??null:t==="rust"&&(i.type==="call_expression"||i.type==="macro_invocation")&&(o=i),!o)return!1;let s=t==="python"?"call":"call_expression";if(o.type!==s)return!1;let a=o.namedChildren.find(d=>d.type==="arguments"||d.type==="argument_list");if(!a)return!1;let c=a.namedChildren.filter(d=>!Io(d)),l=e.namedChildren.find(d=>d.type==="parameters"||d.type==="formal_parameters");if(!l)return!1;let u=[];for(let d of l.namedChildren){if(d.type==="identifier"){u.push(d.text);continue}let m=d.namedChildren.find(f=>f.type==="identifier");m&&u.push(m.text)}if(c.length!==u.length)return!1;for(let d=0;d<u.length;d+=1){let m=c[d];if(m.type!=="identifier"||m.text!==u[d])return!1}return!0}var aT=new Set(["identifier","type_identifier","field_identifier"]),cT=new Set(["identifier"]),lT=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),uT=new Set(["rust","python"]),dT=/\{([^{}]*)\}/g,mT=/\b([A-Za-z_][\w]*)\b/g;function Kh(e,t){return fT(t).has(e.type)}function Jh(e,t){return uT.has(t)&&e.type==="string_content"}function qu(e){let t=0;for(let r of e.values()){let i=r[r.length-1];i!==void 0&&i>t&&(t=i)}let n=new Array(t+1);for(let r=0;r<=t;r+=1)n[r]=new Set;for(let[r,i]of e)for(let o of i)n[o].add(r);return n}function fT(e){return e==="rust"?aT:e==="python"?cT:lT}function Yh(e,t){let n=e.startPosition.row;for(let r of e.text.matchAll(dT)){let i=r[1]??"";for(let o of i.matchAll(mT))o[1]&&t(o[1],n)}}var pT=[/\bdefault\s*=\s*"([^"]+)"/g,/\bwith\s*=\s*"([^"]+)"/g,/\bserialize_with\s*=\s*"([^"]+)"/g,/\bdeserialize_with\s*=\s*"([^"]+)"/g,/\bskip_serializing_if\s*=\s*"([^"]+)"/g,/\bgetter\s*=\s*"([^"]+)"/g,/\brename_all_with\s*=\s*"([^"]+)"/g,/\bschema_with\s*=\s*"([^"]+)"/g],gT=/^#!?\[\s*serde\s*\(/,hT=/^#!?\[\s*schemars\s*\(/,yT=/^#!?\[\s*validate\s*\(/,bT=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function Xh(e,t,n){if(t!=="typescript"&&t!=="tsx"&&t!=="javascript"||e.type!=="call_expression")return;let r=e.childForFieldName("function")??e.namedChild(0);if(!r)return;let i=Dr(r);if(!i||!bT.has(i))return;let o=e.namedChildren.find(c=>c.type==="arguments");if(!o)return;let s=o.namedChild(0);if(!s||s.type!=="string")return;let a=s.namedChildren.find(c=>c.type==="string_fragment");a&&n.add(a.text)}function Qh(e,t){let n=gT.test(e),r=hT.test(e),i=yT.test(e);if(!(!n&&!r&&!i))for(let o of pT){o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;){let a=s[1],c=a.split("::").pop()??a;c==="is_none"&&/\bOption\b/.test(a)||c==="is_empty"&&/\b(String|Vec|HashMap|BTreeMap|HashSet|BTreeSet)\b/.test(a)||c&&t.add(c)}}}function Zh(e,t){let n=new Map,r=(s,a)=>{if(s===a)return;let c=n.get(s);c||(c=new Set,n.set(s,c)),c.add(a)},i=t==="python"?new Set(["identifier"]):new Set(["type_identifier"]),o=(s,a)=>{let c=l=>{i.has(l.type)&&l.text!==a&&r(l.text,a);for(let u of l.children)c(u)};for(let l of s.children)c(l)};if(t==="rust")for(let s of e.rootNode.descendantsOfType(["struct_item","enum_item","union_item","type_item"])){let a=s.namedChildren.find(l=>l.type==="type_identifier")?.text;if(!a)continue;let c=s.namedChildren.find(l=>l.type==="field_declaration_list"||l.type==="enum_variant_list"||l.type==="ordered_field_declaration_list");c&&o(c,a),s.type==="type_item"&&o(s,a)}else if(t==="python")for(let s of e.rootNode.descendantsOfType("class_definition")){let a=s.namedChildren.find(u=>u.type==="identifier")?.text;if(!a)continue;let c=s.childForFieldName("superclasses");c&&o(c,a);let l=s.namedChildren.find(u=>u.type==="block");if(l)for(let u of l.descendantsOfType("type"))for(let d of u.descendantsOfType("identifier"))d.text!==a&&r(d.text,a)}else for(let s of e.rootNode.descendantsOfType(["interface_declaration","type_alias_declaration","class_declaration"])){let a=s.namedChildren.find(c=>c.type==="type_identifier")?.text;a&&o(s,a)}return n}var ST=new Map([["defn","function"],["defn-","function"],["defmacro","macro"],["defmacro-","macro"],["defmethod","method"]]),Uu=new Set(["catch","comment","def","defprotocol","defrecord","deftype","defmethod","defmacro","defmacro-","defn","defn-","do","doseq","dotimes","fn","for","if","let","loop","ns","quote","recur","throw","try","extend-protocol","extend-type","when","when-let","when-not"]);function ey(e){let t=[],n=[],r=[],i=new Map,o=[],s=0,a=0,c=(l,u)=>{let d=i.get(l);if(!d){i.set(l,[u]);return}d[d.length-1]!==u&&d.push(u)};for(;a<e.length;){let l=e[a];if(l===`
|
|
123
|
+
`){s+=1,a+=1;continue}if(/\s|,/.test(l)){a+=1;continue}if(l===";"){a=Ea(e,a);continue}if(l==='"'){let p=Eo(e,a,s);s=p.line,a=p.index;continue}if(l==="("||l==="["||l==="{"){o.push({kind:l,startLine:s,endLine:s,headTokens:[],tokens:[],children:[]}),a+=1;continue}if(l===")"||l==="]"||l==="}"){let p=o.pop();p&&(p.endLine=s,xT(p,{callables:t,callSites:n,clojureMembers:r,recordIdentifier:c}),o[o.length-1]?.children.push(p)),a+=1;continue}if(Vu(l)){a+=1;continue}let u=s,d=a;for(;a<e.length&&!zu(e[a]);)a+=1;let m=e.slice(d,a);if(!m)continue;let f={text:m,line:u};RT(o[o.length-1],f),c(Dt(m),u)}return{language:"clojure",callables:t,callSites:n,clojureMembers:r,typeContainerMap:new Map,identifierLineMap:i,identifiersByLine:ET(i),fileIdentifiers:new Set(i.keys()),rustAttrReferencedNames:new Set,crossLanguageDispatchNames:new Set}}function xT(e,t){if(e.kind!=="("||e.headTokens.length===0)return;let n=e.headTokens[0],r=Dt(n.text),i=ST.get(n.text);if(i){let s=e.headTokens[1];if(s){let a=Dt(s.text);t.recordIdentifier(a,s.line),t.callables.push({name:a,startLine:e.startLine,endLine:e.endLine,paramCount:0,params:[],paramsEndLine:s.line,isLiteralPassthrough:!1,clojureKind:i})}}if(CT(e,t),!r||Uu.has(n.text)||Uu.has(r)||r.startsWith(":"))return;let o=wT(n.text);t.callSites.push({calleeLeaf:o.leaf,calleeQualifier:o.qualifier,calleeText:o.text,memberAccess:!1,line:n.line})}function RT(e,t){e&&(e.headTokens.length<2&&e.headTokens.push(t),e.tokens.length<200&&e.tokens.push(t))}function CT(e,t){let n=Dt(e.tokens[0]?.text??"");if(n==="defprotocol"){let r=Dt(e.tokens[1]?.text??"");if(!r)return;for(let i of wa(e))wo(t,r,"protocol",i,"protocol-method");return}if(n==="defrecord"||n==="deftype"){let r=Dt(e.tokens[1]?.text??"");if(!r)return;let i=n==="defrecord"?"record":"type",o=n==="defrecord"?"record-method":"type-method";for(let s of wa(e))wo(t,r,i,s,o);return}if(n==="extend-type"){let r=Dt(e.tokens[1]?.text??"");if(!r)return;for(let i of wa(e))wo(t,r,"extension",i,"extension-method");return}if(n==="extend-protocol"){let r=Dt(e.tokens[1]?.text??"");for(let i of wa(e)){r&&wo(t,r,"extension",i,"extension-method");let o=IT(e,i.startLine);o&&o!==r&&wo(t,o,"extension",i,"extension-method")}}}function wa(e){return e.children.filter(vT)}function vT(e){if(e.kind!=="(")return!1;let t=Dt(e.tokens[0]?.text??"");return!!(t&&!Uu.has(t)&&!t.startsWith(":"))}function wo(e,t,n,r,i){let o=r.tokens[0],s=Dt(o?.text??"");!o||!s||(e.recordIdentifier(s,o.line),e.clojureMembers.push({ownerName:t,ownerKind:n,memberName:s,memberKind:i,startLine:r.startLine,endLine:r.endLine}))}function IT(e,t){let n=null;for(let r=2;r<e.tokens.length;r+=1){let i=e.tokens[r];if(i.line>t)break;let o=Dt(i.text);o&&!o.startsWith(":")&&(n=o)}return n}function Dt(e){return e.replace(/^#?['`~@]+/,"").split("/").pop()?.replace(/^\./,"")??""}function wT(e){let t=e.replace(/^#?['`~@]+/,""),n=t.lastIndexOf("/"),r=Dt(t);if(n<=0)return{leaf:r,text:t};let i=t.slice(0,n);return{leaf:r,qualifier:i,text:t}}function Ea(e,t){let n=t;for(;n<e.length&&e[n]!==`
|
|
124
|
+
`;)n+=1;return n}function Eo(e,t,n){let r=t+1,i=n;for(;r<e.length;){let o=e[r];if(o==="\\"){r+=2;continue}if(o===`
|
|
125
|
+
`&&(i+=1),r+=1,o==='"')break}return{index:r,line:i}}function Vu(e){return e==="'"||e==="`"||e==="~"||e==="@"||e==="^"||e==="#"}function zu(e){return/\s|,/.test(e)||e==="("||e===")"||e==="["||e==="]"||e==="{"||e==="}"||e==='"'||e===";"}function ET(e){let t=[];for(let[n,r]of e)for(let i of r)t[i]??=new Set,t[i].add(n);return t}var ty=3,DT=Ir("source-facts",{clearGroups:["whole-project","source-file"]}),Wu=me({kind:"source-facts",invalidation:re("source-facts"),serialize:TT,deserialize:FT});function Y(e,t){return Ku(e,t).facts}function Ku(e,t){let n=k(e,t);if(!n)return{facts:null};let r=PT(e,t,n);return r?DT.get(e,t,n,()=>kT(e,t,r,n)):{facts:null}}function PT(e,t,n){return hn(t)?Ca(e,t,n)?.language??null:N(t)}function kT(e,t,n,r){let i=he(e,t,r),o=Wu.read(e,t,i);if(o&&o.language===n)return{facts:o};if(n==="clojure"){let c=ey(r);return Wu.write(e,t,i,c),{facts:c}}let s=ne(e,t);if(!s)return{facts:null,unavailable:{language:n,reason:"parser-unavailable"}};let a=AT(s,n);return Wu.write(e,t,i,a),{facts:a}}function TT(e){let t={version:ty,language:e.language,callables:e.callables,callSites:e.callSites,clojureMembers:e.clojureMembers,typeContainerMap:[...e.typeContainerMap.entries()].map(([n,r])=>[n,[...r]]),identifierLineMap:[...e.identifierLineMap.entries()],rustAttrReferencedNames:[...e.rustAttrReferencedNames],crossLanguageDispatchNames:[...e.crossLanguageDispatchNames]};return JSON.stringify(t)}function FT(e){try{let t=JSON.parse(e);if(t.version!==ty||t.language==="clojure"&&(t.clojureMembers===void 0||t.callSites.some(r=>r.calleeText===void 0)))return null;let n=new Map(t.identifierLineMap);return{language:t.language,callables:t.callables,callSites:t.callSites,clojureMembers:t.clojureMembers??[],typeContainerMap:new Map(t.typeContainerMap.map(([r,i])=>[r,new Set(i)])),identifierLineMap:n,identifiersByLine:qu(n),fileIdentifiers:new Set(n.keys()),rustAttrReferencedNames:new Set(t.rustAttrReferencedNames),crossLanguageDispatchNames:new Set(t.crossLanguageDispatchNames)}}catch{return null}}function Ju(e,t,n,r){let i=Y(e,t);return i?_T(i,n,r)?.isLiteralPassthrough??!0:!0}function Do(e,t){return t.relativePath.includes(".clj-kondo/hooks/")?!0:Y(e,t.relativePath)?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine)?.clojureKind==="macro"}function _T(e,t,n){return e.callables.find(r=>r.startLine===t&&r.endLine===n)??null}function AT(e,t){let n=[],r=[],i=new Set,o=new Set,s=new Map,a=(l,u)=>{let d=s.get(l);if(!d){s.set(l,[u]);return}d[d.length-1]!==u&&d.push(u)},c=l=>{let u=Ia(l,t);u&&n.push(u);let d=hi(l,t);d&&r.push(d),Xh(l,t,o),t==="rust"&&(l.type==="attribute_item"||l.type==="inner_attribute_item")&&Qh(l.text,i),Kh(l,t)&&a(l.text,l.startPosition.row),Jh(l,t)&&Yh(l,a);for(let m of l.children)c(m)};return c(e.rootNode),{language:t,callables:n,callSites:r,clojureMembers:[],typeContainerMap:Zh(e,t),identifierLineMap:s,identifiersByLine:qu(s),fileIdentifiers:new Set(s.keys()),rustAttrReferencedNames:i,crossLanguageDispatchNames:o}}var ny=new Set(["rust","typescript","tsx","javascript","python","clojure"]);function Yu(e,t){let n=Y(e,t);return!n||!ny.has(n.language)?null:n.callables.map(r=>({name:r.name,startLine:r.startLine,endLine:r.endLine}))}function Kn(e,t){let n=Y(e,t);return!n||!ny.has(n.language)?null:n.callSites}function Xu(e,t){return Y(e,t)?.typeContainerMap??new Map}import{ElementTypes as MT,NodeTypes as Qu,parse as NT}from"@vue/compiler-dom";import{parse as C7}from"@vue/compiler-sfc";var LT=new Set(["children","className","data","e","err","error","ev","event","false","id","idx","index","item","key","null","props","res","result","state","style","true","undefined","val","value"]);function Da(e){return e.length<=2||LT.has(e)}function Pa(e,t){return e.split(t).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}var OT=Vn("vue-template-facts"),BT=new Set(["component","keep-alive","slot","suspense","teleport","template","transition","transition-group"]),jT=new Set(["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","link","main","map","mark","menu","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","search","section","select","slot","small","source","span","strong","style","sub","summary","sup","svg","table","tbody","td","template","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr"]),$T=new Set(["div","span","template"]),HT=new Set(["as","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","false","finally","for","from","function","if","import","in","instanceof","let","new","null","of","return","super","switch","this","throw","true","try","typeof","undefined","var","void","while","with","yield"]);function ka(e,t){let n=t.replace(/\\/g,"/"),r=k(e,n);return OT.get(e,n,r,()=>GT(n,gi(e,n).template))}function GT(e,t){let n={relativePath:e,template:t?{startLine:t.startLine,endLine:t.endLine}:null,componentTags:[],nativeTags:[],builtinTags:[],props:[],events:[],directives:[],slots:[],expressionIdentifiers:[],structuralTokens:[]};if(!t)return n;let r;try{r=NT(t.body,{comments:!1})}catch{return n}let i=new Set,o=s=>{s.trim()&&i.add(s)};return iy(r.children,t.startLine,n,o),n.structuralTokens=[...i].sort(),n}function iy(e,t,n,r){for(let i of e)if(i.type===Qu.ELEMENT)qT(i,t,n,r),iy(i.children,t,n,r);else if(i.type===Qu.INTERPOLATION){r("interpolation");let o=Zu(i.content);o&&oy(o,t,i.loc.start.line,n,r)}}function qT(e,t,n,r){let i=YT(e.tag),o={tag:e.tag,normalized:i,kind:JT(e),startLine:yi(t,e.loc.start.line),endLine:yi(t,e.loc.end.line)};o.kind==="component"?(n.componentTags.push(o),r(`component:${i}`)):o.kind==="builtin"?(n.builtinTags.push(o),r(`builtin:${i}`)):(n.nativeTags.push(o),$T.has(e.tag)||r(`native:${e.tag}`));for(let s of e.props)UT(s,t,n,r)}function UT(e,t,n,r){if(e.type===Qu.ATTRIBUTE){let a=e.value?.content??null,c=ry("prop",e.name,a,t,e.loc.start.line,e.loc.end.line);n.props.push(c),r(`prop:${e.name}`);return}let i=zT(e),o=Zu(e.exp),s=ry(VT(e.name),i,o,t,e.loc.start.line,e.loc.end.line);switch(s.kind){case"prop":n.props.push(s),r(`prop:${i}`);break;case"event":n.events.push(s),r(`event:${i}`);break;case"slot":n.slots.push(s),r(`slot:${i}`);break;case"directive":n.directives.push(s),r(`directive:${i}`);break}o&&oy(o,t,e.loc.start.line,n,r)}function ry(e,t,n,r,i,o){return{kind:e,name:t,value:n,startLine:yi(r,i),endLine:yi(r,o)}}function VT(e){switch(e){case"bind":case"model":return"prop";case"on":return"event";case"slot":return"slot";default:return"directive"}}function zT(e){let t=Zu(e.arg);return t||e.name}function Zu(e){if(!e)return null;let t=("content"in e&&typeof e.content=="string"?e.content:e.loc.source).trim();return t||null}function oy(e,t,n,r,i){for(let o of WT(e)){let s={name:o,startLine:yi(t,n),endLine:yi(t,n)};r.expressionIdentifiers.push(s),i(`id:${o}`)}}function WT(e){let t=new Set,n=KT(e),r=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,i;for(;i=r.exec(n);){let o=i[0];HT.has(o)||Da(o)||/^[A-Z_]+$/.test(o)||t.add(o)}return[...t].sort()}function KT(e){return e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/.*$/gm," ").replace(/`(?:\\[\s\S]|\$\{([^}]*)\}|[^`\\])*`/g,(t,n)=>n??" ").replace(/'(?:\\[\s\S]|[^'\\])*'/g," ").replace(/"(?:\\[\s\S]|[^"\\])*"/g," ")}function JT(e){let t=e.tag;return e.tagType===MT.COMPONENT?"component":BT.has(t)?"builtin":jT.has(t)?"native":/^[A-Z]/.test(t)||t.includes("-")?"component":"native"}function YT(e){return Pa(e,/[-_:]/)}function yi(e,t){return e+Math.max(0,t-1)}import{createRequire as cF}from"module";import{existsSync as Fr}from"fs";import{basename as ly,dirname as yt,extname as Sn,join as Pt,relative as kr,resolve as Ge,sep as lF}from"path";import{basename as sy}from"path";var XT=$("indexed-document-paths",{clearGroups:["whole-project"]});function L(e,t={}){let n=QT(t);return[...XT.get(e,n,()=>{let i=t.scope?"AND relative_path LIKE ?":"",o=t.like?"AND relative_path LIKE ?":"",s=[...t.scope?[`%${t.scope}%`]:[],...t.like?[t.like]:[]],a=e.all(`SELECT relative_path
|
|
126
|
+
FROM documents
|
|
127
|
+
WHERE 1 = 1
|
|
128
|
+
${e.pathExclusionsFor("documents")}
|
|
129
|
+
${i}
|
|
130
|
+
${o}
|
|
131
|
+
ORDER BY relative_path`,...s).map(l=>l.relative_path),c=t.extensions?a.filter(l=>t.extensions.some(u=>l.toLowerCase().endsWith(u.toLowerCase()))):a;return t.includeIgnored===!1?c.filter(l=>!e.isIgnored(l)):c})]}function QT(e){let t=e.extensions?[...new Set(e.extensions.map(n=>n.toLowerCase()))].sort():null;return JSON.stringify({scope:e.scope??null,like:e.like??null,extensions:t,includeIgnored:e.includeIgnored!==!1})}function Ta(e,t,n){let r=cy(t);if(!r)return[];let i=e.all(`SELECT relative_path
|
|
132
|
+
FROM documents
|
|
133
|
+
WHERE relative_path = ?
|
|
134
|
+
${e.pathExclusionsFor("documents")}`,r).filter(c=>!e.isIgnored(c.relative_path)).map(c=>({relativePath:c.relative_path,score:ay(c.relative_path,r)}));if(i.length>0)return i;let o=L(e,{includeIgnored:!1}).map(c=>({relativePath:c,score:ay(c,r)})).filter(c=>c.score>0).sort((c,l)=>l.score-c.score||c.relativePath.localeCompare(l.relativePath)),s=o.filter(c=>c.score>=1100);if(s.length>0)return n.allowMultiple?s:[s[0]];let a=o.filter(c=>c.score>=800);return a.length>0?n.allowMultiple?a:[a[0]]:n.allowMultiple?o:o.slice(0,1)}function ay(e,t){let n=cy(e),r=sy(n),i=sy(t),o=0;return n===t&&(o+=1200),n.endsWith(`/${t}`)&&(o+=1100),r===i&&(o+=900),n.startsWith(`${t}/`)&&(o+=850),n.includes(t)&&(o+=250),o}function cy(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}import{existsSync as td,readdirSync as ZT,statSync as eF}from"fs";import{join as bi,relative as tF}from"path";function Si(e){let t=nF(e)??sF(e);if(!t||t.length===0)return[];let n=[],r=new Set;for(let i of t)for(let o of nd(e,i)){if(r.has(o))continue;r.add(o);let s=aF(e,o);s&&n.push(s)}return n}function nF(e){let t=bi(e,"pnpm-workspace.yaml");if(!td(t))return null;try{return rF(O(t,"pnpm workspace manifest"))}catch{return null}}function rF(e){let t=[],n=!1;for(let r of e.split(/\r?\n/)){let i=iF(r);if(!n){/^packages\s*:\s*$/.test(i.trim())&&(n=!0);continue}let o=/^\s+-\s*(.+)$/.exec(i);if(o){let s=oF(o[1].trim());s&&t.push(s);continue}if(i.trim()!=="")break}return t}function iF(e){let t=e.indexOf("#");return t===-1?e:e.slice(0,t)}function oF(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function sF(e){let t=bi(e,"package.json");if(!td(t))return null;try{let n=JSON.parse(O(t,"workspace package manifest"));return n.workspaces?Array.isArray(n.workspaces)?n.workspaces:n.workspaces.packages??[]:null}catch{return null}}function nd(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=bi(e,t);return ed(s)?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=bi(e,r||".");return ed(o)?ZT(o).map(s=>bi(o,s,i)).filter(ed):[]}function ed(e){try{return eF(e).isDirectory()}catch{return!1}}function aF(e,t){let n=bi(t,"package.json");if(!td(n))return null;try{let r=JSON.parse(O(n,"workspace package manifest"));return typeof r.name!="string"||r.name.length===0?null:{name:r.name,relativeDir:tF(e,t).replace(/\\/g,"/"),exports:r.exports}}catch{return null}}var uF=z("indexed-paths",{clearGroups:[]}),dF=z("indexed-path-digest",{clearGroups:[]}),mF=$("tsconfig-alias-config",{clearGroups:["whole-project"]}),fF=$("tsconfig-alias-config-for-dir",{clearGroups:["whole-project"]}),pF=cF(import.meta.url),Po;function gF(){if(Po!==void 0)return Po;try{Po=pF("typescript")}catch{Po=null}return Po}var hF=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"],yF=z("workspace-packages",{clearGroups:["whole-project"]}),Tr=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],Fa=[".py",".pyi"],bt=[".java",".scala",".kt",".kts"],_a=[".rs"],Aa=[".rb"],La=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],Jn=[".cs",".vb"],Ma=[".dart"],_r=[".php"],xi=[".clj",".cljs",".cljc"],bF=new Set(Tr),rd=new Set(Fa),uy=new Set(bt),id=new Set(_a),od=new Set(Aa),dy=new Set(La),my=new Set(Jn),sd=new Set(Ma),fy=new Set(_r),py=new Set(xi),SF=[{extensions:Tr,lookup:bF},{extensions:Fa,lookup:rd},{extensions:bt,lookup:uy},{extensions:_a,lookup:id},{extensions:Aa,lookup:od},{extensions:La,lookup:dy},{extensions:Jn,lookup:my},{extensions:Ma,lookup:sd},{extensions:_r,lookup:fy},{extensions:xi,lookup:py}];function xn(e,t){return t.has(Sn(e).toLowerCase())}function xF(e){return xn(e,rd)}function RF(e){return xn(e,uy)}function CF(e){return xn(e,id)}function vF(e){return xn(e,od)}function IF(e){return xn(e,dy)}function wF(e){return xn(e,my)}function gy(e){return Sn(e).toLowerCase()===".vb"}function EF(e){return xn(e,sd)}function DF(e){return xn(e,fy)}function PF(e){return xn(e,py)}function ad(e){let t=Sn(e).toLowerCase();for(let n of SF)if(n.lookup.has(t))return n.extensions;return Tr}function kF(e){return RF(e)||wF(e)||DF(e)}function St(e,t,n){return xF(t)?Ri(e,t,n):CF(t)?Rn(e,t,n):vF(t)?Na(e,t,n):IF(t)?Oa(e,t,n):kF(t)?Fe(e,n.replace(/\\/g,"."),ad(t)):EF(t)?Ba(e,t,n):PF(t)?cd(e,n):TF(e,t,n)}function TF(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return FF(e,t,n)??AF(e,n);let r=yt(Pt(e.config.projectRoot,t)),i=Ge(r,n),o=Cn(e);for(let s of ud(i)){let a=te(kr(e.config.projectRoot,s));if(o.has(a)||Fr(s))return a}return te(kr(e.config.projectRoot,i))}function FF(e,t,n){let r=jF(e,t);if(!r)return null;let i=Cn(e);for(let o of _F(r,n)){let s=Ge(r.baseUrl,o);for(let a of ud(s)){let c=te(kr(e.config.projectRoot,a));if(i.has(c)||Fr(a))return c}}return null}function _F(e,t){let n=[];for(let[r,i]of Object.entries(e.paths)){let o=r.indexOf("*");if(o===-1){if(t!==r)continue;n.push(...i);continue}let s=r.slice(0,o),a=r.slice(o+1);if(!t.startsWith(s)||!t.endsWith(a)||t.length<s.length+a.length)continue;let c=t.slice(s.length,t.length-a.length);for(let l of i)n.push(l.includes("*")?l.replace("*",c):l)}return n}function AF(e,t){let n=MF(LF(e),t);if(!n)return null;let r=Cn(e);for(let i of NF(n)){let o=Ge(e.config.projectRoot,n.pkg.relativeDir,i);for(let s of ud(o)){let a=te(kr(e.config.projectRoot,s));if(r.has(a)||Fr(s))return a}}return null}function LF(e){return yF.get(e,()=>Si(e.config.projectRoot))}function MF(e,t){let n=null;for(let r of e){let i=null;t===r.name?i="":t.startsWith(`${r.name}/`)&&(i=t.slice(r.name.length+1)),i!==null&&(!n||r.name.length>n.pkg.name.length)&&(n={pkg:r,subpath:i})}return n}function NF(e){let t=[],n=OF(e.pkg.exports,e.subpath);if(n){let r=BF(n);r&&t.push(r)}return t.push(e.subpath?`src/${e.subpath}`:"src/index"),t}function OF(e,t){if(!e||typeof e!="object")return null;let n=t===""?".":`./${t}`;return hy(e[n])}function hy(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return null;let t=e;for(let n of["types","import","default","require","node"]){let r=hy(t[n]);if(r)return r}return null}function BF(e){let t=e.replace(/^\.\//,"");return t.startsWith("dist/")?`src/${t.slice(5)}`:null}function jF(e,t){let n=te(yt(t));return fF.get(e,n,()=>$F(e,n))}function $F(e,t){let n=gF();if(!n)return null;let r=Ge(e.config.projectRoot),i=Ge(r,t);for(;i===r||i.startsWith(r+lF);){for(let s of hF){let a=Pt(i,s);if(!Fr(a))continue;let c=mF.get(e,a,()=>HF(n,a));if(c)return c}let o=yt(i);if(o===i)break;i=o}return null}function HF(e,t){try{let n=e.readConfigFile(t,e.sys.readFile);if(n.error||!n.config)return null;let r=e.parseJsonConfigFileContent(n.config,e.sys,yt(t)),i=r.options.paths;return!i||Object.keys(i).length===0?null:{baseUrl:r.options.baseUrl?Ge(yt(t),r.options.baseUrl):yt(t),paths:i}}catch{return null}}function Ri(e,t,n){let r=Cn(e),i;if(n.startsWith(".")){let o=n.match(/^(\.+)(.*)$/);if(!o)return null;let s=o[1].length,a=o[2].replace(/^\./,""),c=yt(Pt(e.config.projectRoot,t));for(let l=1;l<s;l++)c=yt(c);i=a?Ge(c,a.replace(/\./g,"/")):c}else i=Ge(e.config.projectRoot,n.replace(/\./g,"/"));for(let o of GF(i)){let s=te(kr(e.config.projectRoot,o));if(r.has(s)||Fr(o))return s}return null}function Rn(e,t,n){if(!n)return null;let r=n.replace(/\s+as\s+.+$/,"").trim();if(!r.startsWith("crate::")&&!r.startsWith("self::")&&!r.startsWith("super::"))return null;let i=yt(Pt(e.config.projectRoot,t)),o;return r.startsWith("crate::")?o=Ge(e.config.projectRoot,"src",r.slice(7).replace(/::/g,"/")):r.startsWith("self::")?o=Ge(i,r.slice(6).replace(/::/g,"/")):o=Ge(yt(i),r.slice(7).replace(/::/g,"/")),ld(e,qF(o))}function Na(e,t,n){let r=yt(Pt(e.config.projectRoot,t)),i=Ge(r,n);return ld(e,UF(i))}function Oa(e,t,n){let r=yt(Pt(e.config.projectRoot,t)),i=[Ge(r,n),Ge(e.config.projectRoot,n),Ge(e.config.projectRoot,"include",n),Ge(e.config.projectRoot,"src",n)];return ld(e,i)}function Fe(e,t,n){let r=Cn(e),i=t.replace(/\\/g,".").replace(/::/g,".").replace(/^global::/,""),o=i.replace(/\./g,"/"),s=i.split(".").pop()??i;for(let c of n){let l=`${o}${c}`,u=[...r].find(d=>d.endsWith(l));if(u)return u}for(let c of n){let l=[...r].find(u=>ly(u)===`${s}${c}`);if(l)return l}let a=[...r].filter(c=>n.includes(Sn(c).toLowerCase())).filter(c=>c.includes(`/${o}/`)||c.includes(`/${s}/`)).sort((c,l)=>c.localeCompare(l));return a.length===1?a[0]:null}function Ba(e,t,n){let r=Cn(e);if(n.startsWith("package:")){let s=n.slice(8),a=s.indexOf("/");if(a<0)return null;let c=s.slice(a+1),l=te(c.startsWith("lib/")?c:`lib/${c}`);return r.has(l)?l:null}let i=yt(Pt(e.config.projectRoot,t)),o=Ge(i,n);for(let s of VF(o)){let a=te(kr(e.config.projectRoot,s));if(r.has(a)||Fr(s))return a}return null}function cd(e,t){let n=t.replace(/-/g,"_").replace(/\./g,"/"),r=Cn(e);for(let i of xi){let o=`${n}${i}`,s=[...r].find(a=>a.endsWith(o));if(s)return s}for(let i of xi){let o=[...r].find(s=>ly(s)===`${n.split("/").pop()}${i}`);if(o)return o}return null}function GF(e){let t=Sn(e);return rd.has(t)?[e]:[`${e}.py`,`${e}.pyi`,Pt(e,"__init__.py"),Pt(e,"__init__.pyi")]}function ld(e,t){let n=Cn(e);for(let r of t){let i=te(kr(e.config.projectRoot,r));if(n.has(i)||Fr(r))return i}return null}function qF(e){let t=Sn(e);return id.has(t)?[e]:[`${e}.rs`,Pt(e,"mod.rs")]}function UF(e){let t=Sn(e);return od.has(t)?[e]:[`${e}.rb`,Pt(e,"index.rb")]}function VF(e){let t=Sn(e);return sd.has(t)?[e]:[`${e}.dart`,e]}function ud(e){let t=Sn(e),n=new Set;if(t){n.add(e);for(let r of Tr)n.add(e.slice(0,-t.length)+r)}else for(let r of Tr)n.add(`${e}${r}`),n.add(Pt(e,`index${r}`));return[...n]}function Cn(e){return uF.get(e,()=>new Set(L(e,{includeIgnored:!1}).map(te)))}function dd(e){return dF.get(e,()=>ke([...Cn(e)].sort().join(`
|
|
135
|
+
`)))}import{readdirSync as zF}from"fs";import{execFileSync as WF}from"child_process";import{extname as ja,join as KF}from"path";var JF=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".rs",".py",".pyi",".java",".kt",".kts",".scala",".sc",".clj",".cljs",".cljc",".rb",".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx",".cs",".vb",".php",".dart"],Y7=[".vue"],yy=[".tsx",".jsx"],by=[".vue"],YF=[...yy,...by],XF=new Set(yy),QF=new Set(by),Sy=new Set(JF.map(e=>e.toLowerCase())),ZF=[...Sy].sort().join(","),xy=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo",".nbb",".cpcache",".shadow-cljs","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function ct(e,t={}){let n=t.includeIndexed??!0,r=t.includeAuxiliary??!0,i=t.extensions?.map(c=>c.toLowerCase()),o=i?new Set(i):Sy,s=i?[...o].sort().join(","):ZF,a=`${n?"1":"0"}|${r?"1":"0"}|${s}`;return e_.get(e,a,()=>{let c=new Set;if(n)for(let l of L(e,{includeIgnored:!1}))o.has(ja(l).toLowerCase())&&c.add(l);if(r)for(let l of t_(e.config.projectRoot,o))e.isIgnored(l)||n&&c.has(l)||c.add(l);return[...c].sort()})}function $a(e,t={}){let n=!1,r=!1;for(let i of ct(e,{extensions:YF})){if(t.scope&&!i.includes(t.scope))continue;let o=ja(i).toLowerCase();if(n||=XF.has(o),r||=QF.has(o),n&&r)break}return{react:n,vue:r}}var e_=$("source-files",{clearGroups:[]});function t_(e,t){return n_(e,t)??i_(e,t)}function n_(e,t){try{let n=WF("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf-8",timeout:1e4,killSignal:"SIGKILL",stdio:["ignore","pipe","ignore"]}),r=new Set;for(let i of n.split(`
|
|
136
|
+
`)){let o=i.trim();o&&(r_(o)||t.has(ja(o).toLowerCase())&&r.add(o))}return r}catch{return null}}function r_(e){return e.split("/").some(t=>xy.has(t))}function i_(e,t){let n=new Set,r=i=>{let o=i?KF(e,i):e,s;try{s=zF(o,{withFileTypes:!0})}catch{return}for(let a of s)if(!xy.has(a.name)){if(a.isDirectory()){r(i?`${i}/${a.name}`:a.name);continue}t.has(ja(a.name).toLowerCase())&&n.add(i?`${i}/${a.name}`:a.name)}};return r(""),n}var o_=new Set(["ref","shallowRef","reactive","computed","watch","watchEffect"]),s_=new Set(["onBeforeMount","onMounted","onBeforeUpdate","onUpdated","onBeforeUnmount","onUnmounted","onActivated","onDeactivated","onErrorCaptured"]),a_=new Set(["axios","fetch","runRequest","useAsyncData","useFetch","useResource"]),c_=new Set(["defineEmits","defineExpose","defineModel","defineOptions","defineProps","withDefaults"]),l_=new Set(["catch","for","function","if","return","switch","while"]);function Ga(e){let t={imports:[],functions:[],calls:[],composables:[],stores:[],reactivity:[],lifecycle:[],requests:[],macros:[],lineCount:0,externalLineCount:0,externalScriptPaths:[],unresolvedScripts:[]};for(let n of e.scripts){t.lineCount+=Er(n),n.external&&(t.externalLineCount+=Er(n),t.externalScriptPaths.push(n.sourcePath));for(let i of n.errors)t.unresolvedScripts.push({sourcePath:n.sourcePath,reason:i});if(!n.body||!n.astLanguage){n.astLanguage||t.unresolvedScripts.push({sourcePath:n.sourcePath,reason:`Unsupported Vue script language: ${n.lang??"unknown"}`});continue}t.imports.push(...f_(n));let r=xo(n.astLanguage,n.body);r?d_(n,r.rootNode,t):m_(n,t)}return u_(t),t.externalScriptPaths=Cy(t.externalScriptPaths),t}function u_(e){e.composables=Ci(e,"composable"),e.stores=Ci(e,"store"),e.reactivity=Ci(e,"reactivity"),e.lifecycle=Ci(e,"lifecycle"),e.requests=Ci(e,"request"),e.macros=Ci(e,"macro")}function Ci(e,t){return Cy(e.calls.filter(n=>n.categories.includes(t)).map(n=>n.name))}function d_(e,t,n){let r=new Set,i=new Set,o=s=>{let a=Ia(s,e.astLanguage);if(a){let l=`${a.name}:${a.startLine}:${a.endLine}`;i.has(l)||(i.add(l),n.functions.push({name:a.name,sourcePath:e.sourcePath,startLine:e.startLine+a.startLine,endLine:e.startLine+a.endLine,setup:e.setup}))}let c=hi(s,e.astLanguage);if(c){let l=`${c.calleeLeaf}:${c.line}`;r.has(l)||(r.add(l),n.calls.push({name:c.calleeLeaf,sourcePath:e.sourcePath,line:e.startLine+c.line,categories:Ry(c.calleeLeaf),setup:e.setup}))}for(let l of s.children)o(l)};o(t)}function m_(e,t){for(let n of e.body.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(/g)){let r=n[1];!r||l_.has(r)||t.calls.push({name:r,sourcePath:e.sourcePath,line:e.startLine+Ha(e.body,n.index??0),categories:Ry(r),setup:e.setup})}for(let n of e.body.matchAll(/\bfunction\s+([A-Za-z_$][\w$]*)\b/g)){let r=n[1];if(!r)continue;let i=e.startLine+Ha(e.body,n.index??0);t.functions.push({name:r,sourcePath:e.sourcePath,startLine:i,endLine:i,setup:e.setup})}for(let n of e.body.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)/g)){let r=n[1];if(!r)continue;let i=e.startLine+Ha(e.body,n.index??0);t.functions.push({name:r,sourcePath:e.sourcePath,startLine:i,endLine:i,setup:e.setup})}}function f_(e){let t=[];for(let n of e.body.matchAll(/\bimport\s+(?:type\s+)?([^'";]+?)\s+from\s+['"]([^'"]+)['"]/g)){let r=n[1]?.trim(),i=n[2];if(!r||!i)continue;let o=e.startLine+Ha(e.body,n.index??0);for(let s of p_(r))t.push({local:s,source:i,sourcePath:e.sourcePath,line:o,setup:e.setup})}return t}function p_(e){let t=[],r=e.split(",").map(s=>s.trim()).filter(Boolean)[0];r&&!r.startsWith("{")&&!r.startsWith("*")&&t.push(r);let i=/\{([^}]*)\}/.exec(e)?.[1];if(i)for(let s of i.split(",")){let a=s.trim();if(!a)continue;let c=/\bas\s+([A-Za-z_$][\w$]*)$/.exec(a)?.[1];t.push(c??a.replace(/^type\s+/,"").trim())}let o=/\*\s+as\s+([A-Za-z_$][\w$]*)/.exec(e)?.[1];return o&&t.push(o),t.filter(s=>/^[A-Za-z_$][\w$]*$/.test(s))}function Ry(e){let t=["call"];return/^use[A-Z0-9_]/.test(e)&&t.push("composable"),/^use[A-Z0-9_].*Store$/.test(e)&&t.push("store"),o_.has(e)&&t.push("reactivity"),s_.has(e)&&t.push("lifecycle"),a_.has(e)&&t.push("request"),c_.has(e)&&t.push("macro"),t}function Ha(e,t){let n=0;for(let r=0;r<t&&r<e.length;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}function Cy(e){return[...new Set(e)].sort()}var g_=new Set(["in","key","of"]),h_=new Set(["computed","defineEmits","defineProps","reactive","ref","watch","watchEffect"]),y_=Vn("vue-component-behavior-profiles");function vy(e,t={}){let n=ct(e,{extensions:[".vue"]}).filter(i=>!t.scope||i.includes(t.scope)).sort();return(typeof t.scanLimit=="number"&&t.scanLimit>0?n.slice(0,t.scanLimit):n).map(i=>md(e,i)).filter(i=>(t.minTemplateTokens===void 0||i.templateTokens.size>=t.minTemplateTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function md(e,t){let n=t.replace(/\\/g,"/"),r=k(e,n),i=y_.get(e,n,r,()=>b_(e,n,r));return x_(i)}function b_(e,t,n){let r=gi(e,t),i=ka(e,t),o=Ga(r),s=v_(i),a=i.expressionIdentifiers.map(y=>y.name).filter(y=>!s.includes(y)).filter((y,h,S)=>S.indexOf(y)===h).sort(),c=i.componentTags.map(y=>y.normalized).filter((y,h,S)=>S.indexOf(y)===h).sort(),l=n?n.split(`
|
|
137
|
+
`).length:0,u=Er(r.template),d=o.lineCount,m=r.styles.reduce((y,h)=>y+Er(h),0),f=r.customBlocks.reduce((y,h)=>y+Er(h),0),{lines:p,paths:g}=S_(e,t,o);return{file:t,sfc:r,templateFacts:i,scriptFacts:o,templateTokens:new Set(i.structuralTokens),behaviorTokens:C_(i,o,a),templateBindingNames:a,templateLocalNames:s,componentNames:c,sfcLines:l,totalLines:l+o.externalLineCount,templateLines:u,scriptLines:d,styleLines:m,externalScriptLines:o.externalLineCount,externalScriptPaths:o.externalScriptPaths,customBlockLines:f,delegatedComposableLines:p,delegatedComposablePaths:g}}function S_(e,t,n){let r=new Set;for(let s of n.composables){let a=n.imports.find(l=>l.local===s);if(!a)continue;let c=St(e,a.sourcePath,a.source);!c||c===t||r.add(c)}let i=[...r].sort();return{lines:i.reduce((s,a)=>{let c=k(e,a);return s+(c?c.split(`
|
|
138
|
+
`).length:0)},0),paths:i}}function x_(e){let t=R_(e.scriptFacts);return{...e,scriptFacts:t,templateTokens:new Set(e.templateTokens),behaviorTokens:new Set(e.behaviorTokens),templateBindingNames:[...e.templateBindingNames],templateLocalNames:[...e.templateLocalNames],componentNames:[...e.componentNames],externalScriptPaths:t.externalScriptPaths,delegatedComposablePaths:[...e.delegatedComposablePaths]}}function R_(e){return{...e,imports:e.imports.map(t=>({...t})),functions:e.functions.map(t=>({...t})),calls:e.calls.map(t=>({...t,categories:[...t.categories]})),composables:[...e.composables],stores:[...e.stores],reactivity:[...e.reactivity],lifecycle:[...e.lifecycle],requests:[...e.requests],macros:[...e.macros],externalScriptPaths:[...e.externalScriptPaths],unresolvedScripts:e.unresolvedScripts.map(t=>({...t}))}}function C_(e,t,n){let r=new Set;for(let i of t.composables)r.add(`composable:${i}`);for(let i of t.stores)r.add(`store:${i}`);for(let i of t.reactivity)r.add(`reactivity:${i}`);for(let i of t.lifecycle)r.add(`lifecycle:${i}`);for(let i of t.requests)r.add(`request:${i}`);for(let i of t.macros)r.add(`macro:${i}`);for(let i of t.functions){if(h_.has(i.name))continue;r.add(`function:${i.name}`);let o=/^[a-z]+/.exec(i.name)?.[0]??null;o&&o.length>2&&o!==i.name&&r.add(`function-verb:${o}`)}for(let i of e.events)r.add(`template-event:${i.name}`);for(let i of n)r.add(`template-binding:${i}`);return r}function v_(e){let t=new Set;for(let n of e.directives)if(n.name==="for"&&n.value)for(let r of I_(n.value))t.add(r);for(let n of e.slots)if(n.value)for(let r of Iy(n.value))t.add(r);return[...t].sort()}function I_(e){let t=/^(.*?)\s+(?:in|of)\s+/.exec(e.trim());return t?Iy(t[1]??""):[]}function Iy(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let r=n[0];g_.has(r)||t.push(r)}return t}import{extname as w_}from"path";function en(e){return typeof e=="object"&&e!==null}function et(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")?e:null}var E_=[".tsx",".jsx"],wy=new Set(["useActionState","useCallback","useContext","useDebugValue","useDeferredValue","useEffect","useId","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useOptimistic","useReducer","useRef","useState","useSyncExternalStore","useTransition"]),D_=new Set(["useEffect","useInsertionEffect","useLayoutEffect"]),P_=new Set(["useActionState","useOptimistic","useReducer","useRef","useState"]),k_=new Set(["useLocation","useNavigate","useParams","useSearchParams","useTranslation"]),T_=new Set(["axios","fetch","gql","graphql","mutate","query","request","useMutation","useQuery","useSuspenseQuery"]),F_=new Set(["add","apply","cancel","change","clear","close","create","delete","fetch","filter","handle","load","open","refresh","remove","render","reset","save","select","submit","toggle","update"]),__=new Set(["aria-hidden","className","clipRule","d","fill","fillRule","height","role","stroke","strokeLinecap","strokeLinejoin","strokeWidth","style","viewBox","width","xmlns"]),A_=Vn("react-component-behavior-profiles"),Ey=me({kind:"react-component-behavior-profiles",invalidation:re("react-component-behavior-profiles"),serialize:O_,deserialize:B_});function Ty(e,t={}){let n=ct(e,{extensions:E_}).filter(i=>!t.scope||i.includes(t.scope)).sort();return(typeof t.scanLimit=="number"&&t.scanLimit>0?n.slice(0,t.scanLimit):n).flatMap(i=>pd(e,i)).filter(i=>(t.minJsxTokens===void 0||i.jsxTokens.size>=t.minJsxTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function pd(e,t){let n=t.replace(/\\/g,"/"),r=k(e,n);return A_.get(e,n,r,()=>L_(e,n,r)).map(N_)}function L_(e,t,n){let r=he(e,t,n),i=Ey.read(e,t,r);if(i)return i;let o=M_(e,t);return Ey.write(e,t,r,o),o}function M_(e,t){let n=$_(t);if(!n)return[];let r=ne(e,t);if(!r)return[];let i=Ne(e,t).length;return H_(r.rootNode,n).filter(s=>s.kind==="hook"||gd(s.bodyNode)).map(s=>{let a=K_(s.bodyNode),c=Z_(s.bodyNode,n);return{file:t,name:s.name,kind:s.kind,startLine:s.node.startPosition.row,endLine:s.node.endPosition.row,loc:Math.max(1,s.node.endPosition.row-s.node.startPosition.row+1),fileLines:i,jsxTokens:a.tokens,behaviorTokens:c.tokens,componentNames:vn(a.componentNames),nativeTags:vn(a.nativeTags),propNames:vn(a.propNames),eventNames:vn(a.eventNames),hookNames:vn(c.hookNames),requestNames:vn(c.requestNames),stateNames:vn(c.stateNames),effectNames:vn(c.effectNames),handlerNames:vn(c.handlerNames)}})}function N_(e){return{...e,jsxTokens:new Set(e.jsxTokens),behaviorTokens:new Set(e.behaviorTokens),componentNames:[...e.componentNames],nativeTags:[...e.nativeTags],propNames:[...e.propNames],eventNames:[...e.eventNames],hookNames:[...e.hookNames],requestNames:[...e.requestNames],stateNames:[...e.stateNames],effectNames:[...e.effectNames],handlerNames:[...e.handlerNames]}}function O_(e){return JSON.stringify(e.map(t=>({...t,jsxTokens:[...t.jsxTokens],behaviorTokens:[...t.behaviorTokens]})))}function B_(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=[];for(let r of t){let i=j_(r);if(!i)return null;n.push(i)}return n}catch{return null}}function j_(e){if(!en(e))return null;let{file:t,name:n,kind:r,startLine:i,endLine:o,loc:s,fileLines:a,jsxTokens:c,behaviorTokens:l,componentNames:u,nativeTags:d,propNames:m,eventNames:f,hookNames:p,requestNames:g,stateNames:y,effectNames:h,handlerNames:S}=e;if(typeof t!="string"||typeof n!="string"||r!=="component"&&r!=="hook"||!qa(i)||!qa(o)||!qa(s)||!qa(a))return null;let b={jsxTokens:et(c),behaviorTokens:et(l),componentNames:et(u),nativeTags:et(d),propNames:et(m),eventNames:et(f),hookNames:et(p),requestNames:et(g),stateNames:et(y),effectNames:et(h),handlerNames:et(S)};return Object.values(b).some(R=>R===null)?null:{file:t,name:n,kind:r,startLine:i,endLine:o,loc:s,fileLines:a,jsxTokens:new Set(b.jsxTokens),behaviorTokens:new Set(b.behaviorTokens),componentNames:b.componentNames,nativeTags:b.nativeTags,propNames:b.propNames,eventNames:b.eventNames,hookNames:b.hookNames,requestNames:b.requestNames,stateNames:b.stateNames,effectNames:b.effectNames,handlerNames:b.handlerNames}}function qa(e){return typeof e=="number"&&Number.isFinite(e)}function $_(e){let t=w_(e).toLowerCase();return t!==".tsx"&&t!==".jsx"?null:N(e)}function H_(e,t){let n=[],r=new Set,i=o=>{let s=G_(o);if(s&&(!z_(o)||s.kind==="component")){let a=`${s.name}:${s.node.startIndex}:${s.node.endIndex}`;r.has(a)||(r.add(a),n.push(s))}for(let a of o.namedChildren)i(a)};return(t==="tsx"||t==="javascript")&&i(e),n}function G_(e){if(e.type==="class_declaration"){let o=fd(e);if(!o||!/^[A-Z]/.test(o))return null;let s=q_(e);return!s||!U_(e)&&!gd(s)?null:{name:o,kind:"component",node:e,bodyNode:s}}if(e.type==="function_declaration"){let o=fd(e);return!o||!Dy(o)?null:{name:o,kind:Py(o),node:e,bodyNode:e}}if(e.type!=="variable_declarator")return null;let t=e.childForFieldName("name")??e.namedChild(0),n=e.childForFieldName("value")??e.namedChild(1),r=ko(t);if(!r||!n||!Dy(r))return null;let i=V_(n);return i?{name:r,kind:Py(r),node:e,bodyNode:i}:null}function q_(e){for(let t of e.namedChildren)if(t.type==="class_body")for(let n of t.namedChildren){if(n.type!=="method_definition")continue;if((n.childForFieldName("name")??n.namedChild(0))?.text==="render")return n}return null}function U_(e){return/\b(?:React\.)?(?:Pure)?Component\b/.test(e.text)}function Dy(e){return/^[A-Z]/.test(e)||/^use[A-Z0-9_]/.test(e)}function Py(e){return/^use[A-Z0-9_]/.test(e)?"hook":"component"}function V_(e){if(e.type==="arrow_function"||e.type==="function_expression")return e;if(e.type!=="call_expression")return null;let t=W_(e);return t!=="memo"&&t!=="forwardRef"?null:e.namedChildren.find(i=>i.type==="arguments")?.namedChildren.find(i=>i.type==="arrow_function"||i.type==="function_expression")??null}function z_(e){let t=e.parent;for(;t;){if(t.type==="function_declaration"||t.type==="function_expression"||t.type==="arrow_function"||t.type==="method_definition")return!0;t=t.parent}return!1}function fd(e){return ko(e.childForFieldName("name")??e.namedChild(0))}function W_(e){let t=e.childForFieldName("function")??e.namedChild(0);return t?t.text.split(".").pop()??t.text:null}function gd(e){return e.type.startsWith("jsx_")?!0:e.namedChildren.some(gd)}function K_(e){let t={tokens:new Set,componentNames:new Set,nativeTags:new Set,propNames:new Set,eventNames:new Set},n=r=>{r.type==="jsx_opening_element"||r.type==="jsx_self_closing_element"?J_(r,t):r.type==="jsx_element"&&r.text.trimStart().startsWith("<>")?t.tokens.add("jsx:fragment"):r.type==="jsx_expression"?Y_(r,t):r.type==="jsx_fragment"&&t.tokens.add("jsx:fragment");for(let i of r.children)n(i)};return n(e),t}function J_(e,t){let n=X_(e),r=!1;if(n){let i=ky(n),o=i==="Fragment"||i==="React.Fragment";r=iA(i)&&!o,o?t.tokens.add("jsx:fragment"):r?(t.componentNames.add(i),t.tokens.add(`component:${i}`)):(t.nativeTags.add(i),t.tokens.add(`native:${i}`))}for(let i of e.namedChildren)if(i.type==="jsx_attribute"){let o=Q_(i);if(!o)continue;let s=ky(o);if(s.startsWith("on")&&s.length>2){let a=s.slice(2).replace(/^[A-Z]/,c=>c.toLowerCase());t.eventNames.add(a),t.tokens.add(`event:${a}`)}else __.has(s)||(t.propNames.add(s),t.tokens.add(`${r?"prop":"native-prop"}:${s}`))}else i.type==="jsx_spread_attribute"&&t.tokens.add(Fy(i))}function Y_(e,t){let n=e.text;/^\{\s*\.\.\./.test(n)&&t.tokens.add(Fy(e)),_y(e)&&t.tokens.add("jsx:conditional"),(n.includes(".map(")||n.includes(".flatMap("))&&t.tokens.add("jsx:list");for(let r of oA(n))Da(r)||t.tokens.add(`binding:${r}`)}function Fy(e){let t=/^\{\s*\.\.\.\s*([^}]+)\s*\}$/.exec(e.text)?.[1],n=e.namedChildren.find(o=>o.type!=="comment"),r=t??n?.text??"",i=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.exec(r.trim())?.[0];return i?`prop:spread:${i}`:"prop:spread"}function _y(e){return e.type==="ternary_expression"||e.type==="conditional_expression"?!0:e.namedChildren.some(_y)}function X_(e){for(let t of e.namedChildren)if(t.type==="identifier"||t.type==="jsx_identifier"||t.type==="property_identifier"||t.type==="member_expression"||t.type==="jsx_member_expression")return t.text;return/^<\s*([A-Za-z][\w$.]*)/.exec(e.text)?.[1]??null}function Q_(e){for(let t of e.namedChildren)if(t.type==="property_identifier"||t.type==="identifier"||t.type==="jsx_identifier")return t.text;return/^([A-Za-z_$][\w$:-]*)/.exec(e.text)?.[1]??null}function Z_(e,t){let n={tokens:new Set,hookNames:new Set,requestNames:new Set,stateNames:new Set,effectNames:new Set,handlerNames:new Set},r=i=>{if(i.type==="call_expression"){let o=hi(i,t);o&&eA(o.calleeLeaf,n)}else if(i.type==="variable_declarator")nA(i,n);else if(i.type==="function_declaration"){let o=fd(i);o&&Ay(o,n)}for(let o of i.namedChildren)r(o)};return r(e),n}function eA(e,t){/^use[A-Z0-9_]/.test(e)&&(t.hookNames.add(e),!wy.has(e)&&!k_.has(e)&&t.tokens.add(`hook:${e}`)),wy.has(e)&&t.tokens.add(`react-hook:${e}`),D_.has(e)&&(t.effectNames.add(e),t.tokens.add(`effect:${e}`)),P_.has(e)&&t.tokens.add(`state-hook:${e}`),tA(e)&&(t.requestNames.add(e),t.tokens.add(`request:${e}`))}function tA(e){if(T_.has(e))return!0;let t=/^use([A-Z0-9_].*)$/.exec(e)?.[1];return t?/(Query|Mutation|Fetch|Resource)$/.test(t):!1}function nA(e,t){let n=e.childForFieldName("name")??e.namedChild(0),r=e.childForFieldName("value")??e.namedChild(1);if(n?.type==="array_pattern"&&r?.text.includes("useState")){let o=n.namedChildren.find(a=>ko(a)),s=ko(o);s&&(t.stateNames.add(s),t.tokens.add(`state:${s}`))}let i=ko(n);i&&Ay(i,t)}function Ay(e,t){let n=rA(e);!n||!F_.has(n)||(t.handlerNames.add(e),t.tokens.add(`handler:${e}`),t.tokens.add(`handler-verb:${n}`))}function rA(e){let t=e.startsWith("handle")&&e.length>6?e.slice(6).replace(/^[A-Z]/,n=>n.toLowerCase()):e;return/^[a-z]+/.exec(t)?.[0]??null}function iA(e){return/^[A-Z]/.test(e)||e.includes(".")}function ky(e){return e.replace(/^this\./,"").replace(/\$/g,".")}function ko(e){return e&&(e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"||/^[A-Za-z_$][\w$]*$/.test(e.text))?e.text:null}function oA(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let r=n[0];t.includes(r)||t.push(r)}return t}function vn(e){return[...e].sort()}function kt(e){return{capability:(t,n)=>sA(t,n),reactProfiles:(t={})=>Ty(e,t),reactProfilesForFile:t=>pd(e,t),vueProfiles:(t={})=>vy(e,t),vueProfileForFile:t=>md(e,t),vueTemplateFacts:t=>ka(e,t),vueScriptFacts:t=>Ga(gi(e,t))}}function sA(e,t){let n=e.startsWith("react-")?"react":"vue";if(t===void 0)return{slot:e,available:!0,framework:n};let r=t.replace(/\\/g,"/").toLowerCase();return n==="react"&&!r.endsWith(".tsx")&&!r.endsWith(".jsx")?{slot:e,available:!1,framework:n,reason:"React behavior profiles are only available for .tsx and .jsx files"}:n==="vue"&&!r.endsWith(".vue")?{slot:e,available:!1,framework:n,reason:"Vue behavior facts are only available for .vue files"}:{slot:e,available:!0,framework:n}}function Ar(e,t,n={}){let r=Y(e,t);if(!r)return[];let i=[];if(n.includeCrossLanguageDispatchNames)for(let o of r.crossLanguageDispatchNames)i.push({name:o,kind:"cross-language-dispatch",occurrences:1});if(n.includeRustAttributeNames&&r.language==="rust")for(let o of r.rustAttrReferencedNames)i.push({name:o,kind:"rust-attribute",occurrences:1});return i}import{basename as Ny}from"path";function H(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Tt(e){return e.replace(/'''[\s\S]*?'''/g,Yn).replace(/"""[\s\S]*?"""/g,Yn).replace(/#.*$/gm,Yn).replace(/\/\/.*$/gm,Yn).replace(/\/\*[\s\S]*?\*\//g,Yn).replace(/`(?:\\[\s\S]|[^`])*`/g,Yn).replace(/'(?:\\.|[^'\\\r\n])*'/g,Yn).replace(/"(?:\\.|[^"\\\r\n])*"/g,Yn)}function Fo(e){return My(e,{maskStrings:!1})}function Ly(e){return My(e,{maskStrings:!0})}function My(e,t){let n="",r=0,i=e.length;for(;r<i;){if(e[r]==="/"&&e[r+1]==="/"){let s=e.indexOf(`
|
|
139
|
+
`,r),a=s===-1?i:s;n+=hd(e,r,a),r=a;continue}if(e[r]==="/"&&e[r+1]==="*"){let s=e.indexOf("*/",r+2),a=s===-1?i:s+2;n+=hd(e,r,a),r=a;continue}let o=e[r];if(o==="`"||o==="'"||o==='"'){let s=o,a=r+1;for(;a<i;){if(e[a]==="\\"){a+=2;continue}if(e[a]===s){a+=1;break}if(s!=="`"&&e[a]===`
|
|
140
|
+
`)break;a+=1}n+=t.maskStrings?hd(e,r,a):e.slice(r,a),r=a;continue}n+=o,r+=1}return n}function hd(e,t,n){let r="";for(let i=t;i<n;i+=1)r+=e[i]===`
|
|
141
|
+
`?`
|
|
142
|
+
`:" ";return r}function Yn(e){return e.replace(/[^\r\n]/g," ")}var Uee=Ir("stripped-lines",{clearGroups:["whole-project","source-file"]});Un({name:"stripped-source-singleton",groups:["whole-project","source-file"],clearAll:()=>{Ua=null,To=""},clearFile:()=>{Ua=null,To=""}});var Ua=null,To="";function aA(e){return Ua===e||(Ua=e,To=Tt(e)),To}function Xn(e,t,n){let r=aA(e);return`${r.slice(0,t)}${" ".repeat(n-t)}${r.slice(n)}`}function lt(e,t){return new RegExp(`\\b${H(t)}\\b`,"m").test(e)}function vi(e,t){let n=new Set,r=new RegExp(`\\b${H(t)}\\s*\\.\\s*([A-Za-z_$][\\w$]*)`,"g");for(let i of e.matchAll(r)){let o=i[1];o&&n.add(o)}return[...n]}function _o(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}var cA=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function ut(e){let t=[],n=0,r=0;for(let i=0;i<e.length;i++){let o=e[i];(o==="{"||o==="["||o==="(")&&n++,(o==="}"||o==="]"||o===")")&&n--,o===","&&n===0&&(t.push(e.slice(r,i)),r=i+1)}return t.push(e.slice(r)),t}function xt(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function _e(e,t){let n=new Set,r=(i,o)=>{let s=o||t.has(i.type);!s&&cA.has(i.type)&&n.add(i.text);for(let a of i.children)r(a,s)};return r(e.rootNode,!1),n}function Ut(e,t,n,r,i,o,s){return{importedName:i,localName:o,sourcePath:s??Fe(e,r,ad(t)),kind:"named",used:lt(n,o),usedMembers:[]}}function Ee(e,t,n,r,i="named",o={}){return{importedName:e,localName:t,sourcePath:n,kind:i,used:r.has(t),usedMembers:[],isTypeOnly:o.isTypeOnly}}function In(e,t,n,r,i="named",o=[],s={}){return{importedName:e,localName:t,sourcePath:n,kind:i,used:r,usedMembers:o,isTypeOnly:s.isTypeOnly}}function Lr(e,t){return{importedName:e,localName:null,sourcePath:t,kind:"side-effect",used:!0,usedMembers:[]}}function Mr(e,t,n={}){return{importedName:e,localName:n.localName??null,sourcePath:t,kind:"namespace",used:n.used??!0,usedMembers:n.usedMembers??[],isTypeOnly:n.isTypeOnly}}function Ft(e,t,n){let r=[];for(let i of e.matchAll(t)){let o=i[0];if(!o||typeof i.index!="number")continue;let s=Xn(e,i.index,i.index+o.length);for(let a of n(i,s))r.push(a)}return r}function _t(e,t,n,r){let i=ne(e,t);if(i){let o=n(i);if(o)return o}return r()}function Va(e,t,n,r){let i=ne(e,t),o=N(t),s=o?n[o]:void 0;return i&&s?s(i):r()}function Oy(e,t,n){return _t(e,t,r=>uA(e,t,r),()=>lA(e,t,n))}function lA(e,t,n){return Ft(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(r,i)=>{let o=r[1]?.trim();if(!o)return[];let s=Ny(o).replace(/\.[^.]+$/,"");return[In(o,s,Oa(e,t,o),lt(i,s))]})}function uA(e,t,n){let r=_e(n,new Set(["preproc_include"])),i=[];for(let o of n.rootNode.descendantsOfType("preproc_include")){let s=null;for(let c of o.namedChildren){if(c.type==="system_lib_string"){s=c.text.replace(/^<|>$/g,"");break}if(c.type==="string_literal"){s=c.namedChildren.find(u=>u.type==="string_content")?.text??c.text.replace(/^"|"$/g,"");break}}if(!s)continue;let a=Ny(s).replace(/\.[^.]+$/,"");i.push(Ee(s,a,Oa(e,t,s),r))}return i}var dA=new Set([":require",":require-macros",":use"]),Sd=String.raw`A-Za-z0-9_$*+!?.<>=-`;function jy(e,t,n){let r=CA(n);if(!r)return[];let i=RA(n,r.start,r.end),o=[];for(let s of r.children.slice(2)){if(s.type!=="list"||s.children.length===0)continue;let a=At(s.children[0]);if(a){if(dA.has(a)){for(let c of pA(s.children.slice(1)))o.push(...fA(e,c,i));continue}if(a===":import")for(let c of hA(s.children.slice(1)))o.push(c)}}return o}function mA(e){return e.type==="list"&&At(e.children[0])==="ns"}function fA(e,t,n){let r=cd(e,t.namespace),i=t.alias??t.namespace,o=bA(n,i),s=[{importedName:t.namespace,localName:i,sourcePath:r,kind:"namespace",used:t.refers.length>0||t.referAll||o.length>0||SA(n,t.namespace),usedMembers:o}];t.referAll&&s.push({importedName:"*",localName:null,sourcePath:r,kind:"side-effect",used:!0,usedMembers:[]});for(let a of t.refers)s.push({importedName:a,localName:a,sourcePath:r,kind:"named",used:xA(n,a),usedMembers:[]});return s}function pA(e){return e.flatMap(t=>za(t,null))}function za(e,t){if(e.type==="atom")return e.text.startsWith(":")?[]:[{namespace:bd(t,e.text),alias:null,refers:[],referAll:!1}];if(e.type==="vector")return e.children.length>0&&At(e.children[0])===null?e.children.flatMap(n=>za(n,t)):gA(e,t);if(e.type==="list"&&e.children.length>0){let n=At(e.children[0]);return n?!n||n.startsWith(":")?[]:e.children.slice(1).flatMap(r=>za(r,bd(t,n))):e.children.flatMap(r=>za(r,t))}return[]}function gA(e,t){let n=At(e.children[0]);if(!n||n.startsWith(":"))return[];let r={namespace:bd(t,n),alias:null,refers:[],referAll:!1};for(let i=1;i<e.children.length;i+=1){let o=At(e.children[i]);if(!o?.startsWith(":"))continue;let s=e.children[i+1];if((o===":as"||o===":as-alias")&&s){r.alias=At(s),i+=1;continue}o===":refer"&&s&&(At(s)===":all"?r.referAll=!0:(s.type==="vector"||s.type==="list")&&r.refers.push(...s.children.map(At).filter(yA)),i+=1)}return[r]}function hA(e){let t=[];for(let n of e){if(n.type==="atom"){let i=n.text.split(".").pop()??n.text;t.push(In(i,i,null,!0));continue}if(n.type!=="vector")continue;let r=At(n.children[0]);if(r)for(let i of n.children.slice(1)){let o=At(i);o&&t.push(In(`${r}.${o}`,o,null,!0))}}return t}function bd(e,t){return e?`${e}.${t}`:t}function At(e){return e?.type==="atom"?e.text:null}function yA(e){return!!(e&&!e.startsWith(":"))}function bA(e,t){let n=new Set,r=new RegExp(`${xd()}${H(t)}\\s*/\\s*([${Sd}]+)`,"g");for(let i of e.matchAll(r)){let o=i[1];o&&n.add(o)}return[...n]}function SA(e,t){return new RegExp(`${xd()}${H(t)}\\s*/`,"m").test(e)}function xA(e,t){return new RegExp(`${xd()}${H(t)}(?![${Sd}])`,"m").test(e)}function xd(){return`(?<![${Sd}])`}function RA(e,t,n){let r="",i=0;for(;i<e.length;){if(i>=t&&i<n){r+=e[i]===`
|
|
143
|
+
`?`
|
|
144
|
+
`:" ",i+=1;continue}let o=e[i];if(o===";"){let s=Ea(e,i);r+=By(e.slice(i,s)),i=s;continue}if(o==='"'){let s=Eo(e,i,0).index;r+=By(e.slice(i,s)),i=s;continue}r+=o,i+=1}return r}function CA(e){let t=0;for(;t<e.length&&(t=Rd(e,t),!(t>=e.length));){let n=Wa(e,t);if(!n){t+=1;continue}if(mA(n.form))return n.form;t=n.index}return null}function Wa(e,t){let n=Rd(e,t);if(e.startsWith("#?@",n)||e.startsWith("#?",n))return vA(e,n);if(e.startsWith("#_",n)){let i=Wa(e,n+2);return i?{form:{type:"atom",text:"",start:n,end:i.index},index:i.index}:null}for(;Vu(e[n]);)n+=1;let r=e[n];return r?r==="("?yd(e,n,"list",")"):r==="["?yd(e,n,"vector","]"):r==="{"?yd(e,n,"map","}"):r==='"'?{form:{type:"atom",text:"",start:n,end:Eo(e,n,0).index},index:Eo(e,n,0).index}:wA(e,n):null}function vA(e,t){let n=e.startsWith("#?@",t)?3:2,r=Wa(e,t+n);return r?{form:{type:"list",children:r.form.type==="list"||r.form.type==="vector"||r.form.type==="map"?IA(r.form.children):[],start:t,end:r.index},index:r.index}:null}function IA(e){let t=[];for(let n=0;n<e.length;n+=2){let r=At(e[n]),i=e[n+1];r?.startsWith(":")&&i&&t.push(i)}return t}function yd(e,t,n,r){let i=[],o=t+1;for(;o<e.length;){if(o=Rd(e,o),e[o]===r)return{form:{type:n,children:i,start:t,end:o+1},index:o+1};let s=Wa(e,o);if(!s){o+=1;continue}s.form.type==="atom"&&s.form.text===""||i.push(s.form),o=s.index}return{form:{type:n,children:i,start:t,end:e.length},index:e.length}}function wA(e,t){let n=t;for(;n<e.length&&!zu(e[n]);)n+=1;return{form:{type:"atom",text:e.slice(t,n),start:t,end:n},index:n}}function Rd(e,t){let n=t;for(;n<e.length;){let r=e[n];if(/\s|,/.test(r)){n+=1;continue}if(r===";"){n=Ea(e,n);continue}break}return n}function By(e){return e.replace(/[^\r\n]/g," ")}function $y(e,t,n){let r=[];for(let i of n.matchAll(/^[ \t]*import\s+['"]([^'"]+)['"](?:\s+as\s+([A-Za-z_]\w*))?[\s\S]*?;$/gm)){let o=i[1]?.trim(),s=i[2]?.trim()??null,a=i[0];if(!o||!a||typeof i.index!="number")continue;let c=Xn(n,i.index,i.index+a.length);r.push({importedName:o,localName:s,sourcePath:Ba(e,t,o),kind:s?"namespace":"side-effect",used:s?lt(c,s):!0,usedMembers:s?vi(c,s):[]})}return r}function Hy(e,t,n){let r=[];for(let i of n.matchAll(/^[ \t]*export\s+['"]([^'"]+)['"][\s\S]*?;$/gm)){let o=i[1]?.trim();o&&r.push({specifier:o,sourcePath:Ba(e,t,o)})}return r}function Gy(e,t,n){return Va(e,t,{csharp:r=>DA(e,t,r),vb:r=>EA(e,t,r)},()=>{let r=gy(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return Ft(n,r,(i,o)=>{let s=i[1]?.trim();if(!s)return[];let[a,c]=s.split(/\s*=\s*/),l=!!c,u=(l?c:a)?.trim()??s,d=u.split(".").pop()??u,m=l?a?.trim()??d:d;return[Ut(e,t,o,u,d,m,Fe(e,u,Jn))]})})}function EA(e,t,n){let r=_e(n,new Set(["imports_statement"])),i=[];for(let o of n.rootNode.descendantsOfType("imports_statement")){let s=o.namedChildren.filter(m=>m.type==="namespace_name");if(s.length===0)continue;let a=s[s.length-1],c=s.length>1?s[0]:null,l=a.text,u=l.split(".").pop()??l,d=c?.text??u;i.push(Ee(u,d,Fe(e,l,Jn),r,c?"namespace":"named"))}return i}function DA(e,t,n){let r=_e(n,new Set(["using_directive"])),i=[];for(let o of n.rootNode.descendantsOfType("using_directive")){let s=o.namedChildren;if(s.length===0)continue;let a=null,c;s.length>=2&&s[0].type==="identifier"&&(s[1].type==="qualified_name"||s[1].type==="identifier")?(a=s[0],c=s[1]):c=s[s.length-1];let l=c.text,u=l.split(".").pop()??l,d=a?.text??u;i.push(Ee(u,d,Fe(e,l,Jn),r,a?"namespace":"named"))}return i}var PA=$("vue-non-script-identifiers",{clearGroups:["whole-project","source-file"]});function qy(e,t){return PA.get(e,t,()=>{let n=new Set,r=k(e,t);if(!r)return n;let o=r.replace(/<script\b[^>]*>[\s\S]*?<\/script>/g,s=>s.replace(/[^\r\n]/g," ")).replace(/<!--[\s\S]*?-->/g,s=>s.replace(/[^\r\n]/g," ")).replace(/\/\*[\s\S]*?\*\//g,s=>s.replace(/[^\r\n]/g," "));for(let s of o.matchAll(/[A-Za-z_$][\w$]*/g))n.add(s[0]);return n})}function Cd(e,t,n){return _t(e,t,r=>TA(e,t,r),()=>kA(e,t,n))}function kA(e,t,n){return HA(n).flatMap(r=>GA(e,t,r.clause,r.specifier,r.start,r.end,n))}function TA(e,t,n){let r=FA(e,t,n),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))i.push(..._A(e,t,n,o,r));return i}function FA(e,t,n){let r=_e(n,new Set(["import_statement"]));if(hn(t))for(let i of qy(e,t))r.add(i);return r}function _A(e,t,n,r,i){let o=OA(r);if(!o)return[];let s=St(e,t,o),a=xt(r,"import_clause");return a?AA(n,a,s,i,BA(r.text)):[Lr("*",s)]}function AA(e,t,n,r,i){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(LA(s.text,n,r,i));else if(s.type==="namespace_import"){let a=MA(e,s,n,r,i);a&&o.push(a)}else s.type==="named_imports"&&o.push(...NA(s,n,r,i));return o}function LA(e,t,n,r){return Ee("default",e,t,n,"default",{isTypeOnly:r})}function MA(e,t,n,r,i){let s=xt(t,"identifier")?.text??"";if(!s)return null;let a=$A(e,s);return Mr("*",n,{localName:s,usedMembers:a,isTypeOnly:i,used:a.length>0||r.has(s)})}function NA(e,t,n,r){let i=[];for(let o of e.namedChildren){if(o.type!=="import_specifier")continue;let s=o.namedChild(0),a=o.namedChild(1);if(!s)continue;let c=s.text,l=a?.text??c;i.push(Ee(c,l,t,n,"named",{isTypeOnly:r||jA(o.text)}))}return i}function OA(e){let t=xt(e,"string");if(!t)return null;let n=xt(t,"string_fragment");return n?n.text:null}function BA(e){return/^\s*import\s+type\b/.test(e)}function jA(e){return/^\s*type\b/.test(e.trim())}function $A(e,t){let n=new Set;for(let r of e.rootNode.descendantsOfType("member_expression")){let i=r.namedChild(0),o=r.namedChild(1);!i||!o||i.type!=="identifier"||i.text!==t||(o.type==="property_identifier"||o.type==="identifier")&&n.add(o.text)}return[...n]}function HA(e){let t=[],n=/^[ \t]*import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let i of e.matchAll(n)){let o=i[0],s=i[1],a=i[2];!o||!a||typeof i.index!="number"||t.push({clause:s,specifier:a,start:i.index,end:i.index+o.length})}let r=/^[ \t]*import\s+['"]([^'"]+)['"]\s*;?/gm;for(let i of e.matchAll(r)){let o=i[0],s=i[1];!o||!s||typeof i.index!="number"||t.push({clause:null,specifier:s,start:i.index,end:i.index+o.length})}return t.sort((i,o)=>i.start-o.start)}function GA(e,t,n,r,i,o,s){let a=St(e,t,r),c=Xn(s,i,o);return n?qA(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let d=vi(c,u.localName);return Mr(u.importedName,u.sourcePath,{localName:u.localName,usedMembers:d,used:d.length>0||lt(c,u.localName),isTypeOnly:u.isTypeOnly})}return u.kind==="side-effect"?Lr(u.importedName,u.sourcePath):In(u.importedName,u.localName??"",u.sourcePath,u.localName?lt(c,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[Lr("*",a)]}function qA(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,o]=UA(r),s=[];return i&&s.push(...Uy(i,n)),o&&s.push(...Uy(o,n)),s}function Uy(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let r=n.slice(1,-1).trim();return r?ut(r).map(i=>{let o=i.trim(),s=t||/^type\b/.test(o),a=o.replace(/^type\s+/,""),[c,l]=a.split(/\s+as\s+/);return{importedName:c.trim(),localName:(l??c).trim(),kind:"named",isTypeOnly:s}}):[]}return n.startsWith("* as ")?[{importedName:"*",localName:n.slice(5).trim(),kind:"namespace",isTypeOnly:t}]:[{importedName:"default",localName:n,kind:"default",isTypeOnly:t}]}function UA(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r==="{"&&t++,r==="}"&&t--,r===","&&t===0)return[e.slice(0,n).trim(),e.slice(n+1).trim()]}return[e.trim(),null]}function vd(e,t,n){let r=ne(e,t);return r?YA(e,t,r):VA(e,t,n)}function VA(e,t,n){return[...zA(e,t,n),...WA(e,t,n),...KA(e,t,n)]}function zA(e,t,n){let r=[],i=/^[ \t]*export\s+(?:type\s+)?\{([\s\S]*?)\}\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[1]??"",a=o[2]??"",c=ut(s).map(d=>JA(d.trim())).filter(d=>!!d),l=Ii(n,o.index),u=Ii(n,o.index+o[0].length-1);r.push({kind:"named",sourcePath:St(e,t,a),names:c,startLine:l,endLine:u})}return r}function WA(e,t,n){let r=[],i=/^[ \t]*export\s+\*\s+as\s+(\w+)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[2]??"",a=Ii(n,o.index),c=Ii(n,o.index+o[0].length-1);r.push({kind:"star-as",sourcePath:St(e,t,s),names:[],startLine:a,endLine:c})}return r}function KA(e,t,n){let r=[],i=/^[ \t]*export\s+\*\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[1]??"",a=Ii(n,o.index),c=Ii(n,o.index+o[0].length-1);r.push({kind:"star",sourcePath:St(e,t,s),names:[],startLine:a,endLine:c})}return r}function JA(e){if(!e)return null;let t=e.replace(/^type\s+/,"").trim();if(!t)return null;let n=t.match(/^(\w+)\s+as\s+(\w+)$/);if(n)return n[2]??null;let r=t.match(/^(\w+)$/);return r?r[1]??null:null}function Ii(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function YA(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let o=XA(e,t,i);if(o===void 0)continue;let s=i.startPosition.row,a=i.endPosition.row,c=QA(i,o,s,a);r.push(c)}return r}function XA(e,t,n){let r=xt(n,"string");if(!r)return;let i=xt(r,"string_fragment");if(i)return St(e,t,i.text)}function QA(e,t,n,r){let i=xt(e,"export_clause");if(i){let s=[];for(let a of i.namedChildren){if(a.type!=="export_specifier")continue;let c=a.namedChild(0),l=a.namedChild(1);c&&s.push((l??c).text)}return{kind:"named",sourcePath:t,names:s,startLine:n,endLine:r}}return xt(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:r}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:r}}function Vy(e,t,n){return Va(e,t,{java:r=>ZA(e,t,r),kotlin:r=>eL(e,t,r),scala:r=>tL(e,t,r)},()=>Ft(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(r,i)=>{let o=r[1]?.trim();return o?nL(e,t,o,i):[]}))}function ZA(e,t,n){let r=_e(n,new Set(["import_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.children.some(d=>d.type==="asterisk"),c=o.namedChildren.find(d=>d.type==="scoped_identifier")??o.namedChildren.find(d=>d.type==="identifier");if(!c)continue;let l=c.text;if(s){i.push(Mr("*",Fe(e,l,bt)));continue}let u=l.split(".").pop()??l;i.push(Ee(u,u,Fe(e,l,bt),r))}return i}function eL(e,t,n){let r=_e(n,new Set(["import_header","import_list"])),i=[];for(let o of n.rootNode.descendantsOfType("import_header")){let s=o.namedChildren.find(f=>f.type==="identifier");if(!s)continue;let a=o.namedChildren.some(f=>f.type==="wildcard_import"),c=o.namedChildren.find(f=>f.type==="import_alias");if(a){i.push(Mr("*",Fe(e,s.text,bt)));continue}let l=s.text,u=l.split(".").pop()??l,m=c?.namedChild(0)?.text??u;i.push(Ee(u,m,Fe(e,l,bt),r))}return i}function tL(e,t,n){let r=_e(n,new Set(["import_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.namedChildren.find(d=>d.type==="namespace_selectors"||d.type==="namespace_wildcard"),a=o.namedChildren.filter(d=>d!==s&&(d.type==="identifier"||d.type==="stable_identifier")),c=a.map(d=>d.text).join(".");if(!c)continue;if(s?.type==="namespace_wildcard"){i.push(Mr("*",Fe(e,c,bt)));continue}if(s?.type==="namespace_selectors"){for(let d of s.namedChildren)if(d.type==="arrow_renamed_identifier"){let[m,f]=d.namedChildren;if(!m)continue;let p=m.text,g=f?.text??p;if(p==="_")continue;i.push(Ee(p,g,Fe(e,`${c}.${p}`,bt),r))}else if(d.type==="identifier"){let m=d.text;i.push(Ee(m,m,Fe(e,`${c}.${m}`,bt),r))}continue}let l=a[a.length-1]?.text??c,u=a.slice(0,-1).map(d=>d.text).join(".")||c;i.push(Ee(l,l,Fe(e,u&&a.length>1?`${u}.${l}`:c,bt),r))}return i}function nL(e,t,n,r){if(n.includes("{")&&n.includes("}")){let i=n.slice(0,n.indexOf("{")).replace(/\.$/,"").trim(),o=n.slice(n.indexOf("{")+1,n.lastIndexOf("}")).trim();return ut(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.includes("=>")?a.split(/\s*=>\s*/):a.split(/\s+as\s+/),u=c?.trim();if(!u||u==="_")return[];let d=(l??u.split(".").pop()??u).trim(),m=u==="_"?i:`${i}.${u}`.replace(/\.\./g,".");return[Ut(e,t,r,m,u,d)]})}return[Ut(e,t,r,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function Wy(e,t,n){return _t(e,t,r=>rL(e,t,r),()=>Ft(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?ut(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.split(/\s+as\s+/i),u=c?.trim()??a,d=u.split("\\").pop()??u,m=(l??d).trim();return[Ut(e,t,i,u,d,m,Fe(e,u.replace(/\\/g,"."),_r))]}):[]}))}function rL(e,t,n){let r=_e(n,new Set(["namespace_use_declaration"])),i=[],o=(s,a,c)=>{i.push(Ee(a,c,Fe(e,s.replace(/\\/g,"."),_r),r))};for(let s of n.rootNode.descendantsOfType("namespace_use_declaration")){let a=s.namedChildren.find(c=>c.type==="namespace_use_group");if(a){let c=s.namedChildren.find(l=>l.type==="namespace_name")?.text??"";for(let l of a.namedChildren){if(l.type!=="namespace_use_clause")continue;let{importedName:u,localName:d,qualified:m}=zy(l,c);u&&o(m,u,d)}continue}for(let c of s.namedChildren){if(c.type!=="namespace_use_clause")continue;let{importedName:l,localName:u,qualified:d}=zy(c,"");l&&o(d,l,u)}}return i}function zy(e,t){let n=e.namedChildren.find(l=>l.type==="qualified_name"),r=e.namedChildren.filter(l=>l.type==="name"),i="";n?i=n.text:r.length>=1&&(i=r[0].text);let o=n&&r.length>0?r[r.length-1]:null,s=i.split("\\").pop()??i,a=o?.text??s,c=t?`${t}\\${i}`:i;return{importedName:s,localName:a,qualified:c}}function Jy(e,t,n){return _t(e,t,r=>iL(e,t,r),()=>sL(n).flatMap(r=>cL(e,t,r,n)))}function iL(e,t,n){let r=_e(n,new Set(["import_statement","import_from_statement"])),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))for(let s of o.namedChildren){let a=Ky(s);if(!a)continue;let c=Ri(e,t,a.qualifiedName);i.push({importedName:a.qualifiedName,localName:a.localName,sourcePath:c,kind:"namespace",used:r.has(a.localName),usedMembers:[]})}for(let o of n.rootNode.descendantsOfType("import_from_statement")){let s=o.namedChild(0);if(!s)continue;let a=oL(s);if(a===null)continue;let c=Ri(e,t,a);for(let l=1;l<o.namedChildCount;l+=1){let u=o.namedChild(l);if(u.type==="wildcard_import"){i.push({importedName:"*",localName:null,sourcePath:c,kind:"side-effect",used:!0,usedMembers:[]});continue}let d=Ky(u);d&&i.push({importedName:d.qualifiedName,localName:d.localName,sourcePath:c,kind:"named",used:r.has(d.localName),usedMembers:[]})}}return i}function Ky(e){if(e.type==="aliased_import"){let t=e.namedChild(0),n=e.namedChild(1);return!t||!n?null:{qualifiedName:t.text,localName:n.text}}if(e.type==="dotted_name"){let t=e.text;return{qualifiedName:t,localName:t.split(".")[0]??t}}return e.type==="identifier"?{qualifiedName:e.text,localName:e.text}:null}function oL(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=xt(e,"import_prefix")?.text??"",n=xt(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function sL(e){let t=e.split(`
|
|
145
|
+
`),n=[],r=0;for(let i=0;i<t.length;i++){let o=t[i],s=o.trimStart(),a=r;if(r+=o.length+1,!s.startsWith("import ")&&!s.startsWith("from "))continue;let c=o,l=a+o.length,u=_o(o);for(;i+1<t.length&&(u>0||c.trimEnd().endsWith("\\"));){i++;let m=t[i];c+=`
|
|
146
|
+
${m}`,l+=1+m.length,u+=_o(m),r+=m.length+1}let d=aL(c);d&&n.push({...d,start:a,end:l})}return n}function aL(e){let t=e.replace(/\\\s*\n/g," ").trim();if(t.startsWith("import "))return{kind:"import",module:null,clause:t.slice(7).trim()};let n=t.match(/^from\s+([.\w]+)\s+import\s+([\s\S]+)$/);if(!n)return null;let r=n[2].trim();return r.startsWith("(")&&r.endsWith(")")&&(r=r.slice(1,-1).trim()),{kind:"from",module:n[1],clause:r}}function cL(e,t,n,r){let i=Xn(r,n.start,n.end),o=n.clause.replace(/\n/g," ").trim();if(n.kind==="import")return ut(o).flatMap(c=>{let l=c.trim().replace(/,$/,"");if(!l)return[];let[u,d]=l.split(/\s+as\s+/),m=u.trim(),f=(d??m.split(".")[0]??m).trim(),p=Ri(e,t,m),g=vi(i,f);return[{importedName:m,localName:f,sourcePath:p,kind:"namespace",used:lt(i,f)||g.length>0,usedMembers:g}]});let s=n.module?Ri(e,t,n.module):null,a=[];for(let c of ut(o)){let l=c.trim().replace(/,$/,"");if(!l)continue;if(l==="*"){a.push({importedName:"*",localName:null,sourcePath:s,kind:"side-effect",used:!0,usedMembers:[]});continue}let[u,d]=l.split(/\s+as\s+/),m=(d??u).trim();a.push({importedName:u.trim(),localName:m,sourcePath:s,kind:"named",used:lt(i,m),usedMembers:[]})}return a}import{basename as lL}from"path";function Yy(e,t,n){return _t(e,t,r=>dL(e,t,r),()=>uL(e,t,n))}function uL(e,t,n){return Ft(n,/^[ \t]*(require_relative|require)\s+["']([^"']+)["']\s*$/gm,(r,i)=>{let o=r[1],s=r[2];if(!o||!s)return[];let a=o==="require_relative"?Na(e,t,s):null;if(a){let c=Xy(s);return[In(c,c,a,lt(i,c))]}return[Lr(s,a)]})}function dL(e,t,n){let r=_e(n,new Set([])),i=[],o=new Set(["require","require_relative","load"]);for(let s of n.rootNode.descendantsOfType("call")){let a=s.namedChild(0);if(!a||a.type!=="identifier"||!o.has(a.text))continue;let l=s.namedChildren.find(f=>f.type==="argument_list")?.namedChild(0);if(!l||l.type!=="string")continue;let d=l.namedChildren.find(f=>f.type==="string_content")?.text;if(!d)continue;let m=a.text==="require_relative"?Na(e,t,d):null;if(m){let f=Xy(d);i.push(Ee(f,f,m,r))}else i.push(Lr(d,m))}return i}function Xy(e){return Pa(lL(e).replace(/\.[^.]+$/,""),/_/)}function Qy(e,t,n){return _t(e,t,r=>mL(e,t,r),()=>Ft(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?fL(e,t,o,i):[]}))}function mL(e,t,n){let r=_e(n,new Set(["use_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("use_declaration")){let s=o.namedChild(0);if(s)for(let a of Ao(s,"")){if(!a.importedName||a.importedName==="*")continue;let c=Rn(e,t,a.qualifiedName)??Rn(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));i.push(Ee(a.importedName,a.localName,c,r))}}return i}function Ao(e,t){switch(e.type){case"identifier":case"super":case"crate":{let n=e.text;return[{qualifiedName:wi(t,n),importedName:n,localName:n}]}case"self":{let n=t.split("::").filter(Boolean).pop()??"self";return[{qualifiedName:t||"self",importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,r=n.split("::").pop()??n;return[{qualifiedName:wi(t,n),importedName:r,localName:r}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=wi(t,n.text),o=[];for(let s of r.namedChildren)o.push(...Ao(s,i));return o}case"use_list":{let n=[];for(let r of e.namedChildren)n.push(...Ao(r,t));return n}case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=Ao(n,t),o=r.text;return i.map(s=>({...s,localName:o}))}case"use_wildcard":{let n=e.namedChild(0),r=n?n.text:"";return[{qualifiedName:wi(t,`${r}::*`),importedName:"*",localName:"*"}]}default:return[]}}function wi(e,t){return e?t?`${e}::${t}`:e:t}function fL(e,t,n,r){let i=n.trim();if(i.includes("{")&&i.includes("}")){let u=i.slice(0,i.indexOf("{")).replace(/::$/,"").trim(),d=i.slice(i.indexOf("{")+1,i.lastIndexOf("}")).trim();return ut(d).flatMap(m=>{let f=m.trim();if(!f)return[];if(f==="self"){let b=u.split("::").filter(Boolean).pop();return b?[Ut(e,t,r,u,b,b)]:[]}let[p,g]=f.split(/\s+as\s+/),y=p?.trim();if(!y)return[];let h=(g??y.split("::").pop()??y).trim(),S=`${u}::${y}`.replace(/::::/g,"::");return[Ut(e,t,r,S,y.split("::").pop()??y,h,Rn(e,t,u))]})}let[o,s]=i.split(/\s+as\s+/),a=o?.trim()??i,c=(s??a.split("::").pop()??a).trim(),l=Rn(e,t,a)??Rn(e,t,a.split("::").slice(0,-1).join("::"));return[Ut(e,t,r,a,a.split("::").pop()??a,c,l)]}function Zy(e,t,n){let r=ne(e,t);if(r)return pL(e,t,r);let i=[];for(let o of n.matchAll(/^[ \t]*pub\s+use\s+(.+?)\s*;$/gm)){let s=o[1]?.trim();s&&i.push(...hL(e,t,s))}return i}function pL(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("use_declaration")){if(!gL(i))continue;let o=i.namedChildren.find(s=>s.type!=="visibility_modifier");if(o)for(let s of Ao(o,""))s.importedName&&r.push(Id(e,t,s.qualifiedName))}return r}function gL(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function hL(e,t,n){let r=n.trim();if(r.includes("{")&&r.includes("}")){let i=r.slice(0,r.indexOf("{")).replace(/::$/,"").trim(),o=r.slice(r.indexOf("{")+1,r.lastIndexOf("}")).trim();return ut(o).flatMap(s=>{let a=s.trim();if(!a||a==="self")return[];let[c]=a.split(/\s+as\s+/),l=`${i}::${c?.trim()??a}`.replace(/::::/g,"::");return[Id(e,t,l)]})}return[Id(e,t,r)]}function Id(e,t,n){return{specifier:n,sourcePath:Rn(e,t,n)??Rn(e,t,n.split("::").slice(0,-1).join("::"))}}function Qn({language:e,extensions:t,imports:n,parseImports:r}){return{language:e,extensions:t,capabilities:{imports:n},parseImports:r}}function eb(e,t){let n=t.toLowerCase();for(let r of e)for(let i of r.extensions)if(n.endsWith(i))return r;return null}var yL={language:"javascript",extensions:Tr,capabilities:{imports:"ast-with-regex-fallback",reExports:"ast-with-regex-fallback"},parseImports:Cd,parseReExports:vd},bL=Qn({language:"python",extensions:Fa,imports:"ast-with-regex-fallback",parseImports:Jy}),SL=Qn({language:"jvm",extensions:bt,imports:"ast-dispatch-with-regex-fallback",parseImports:Vy}),xL={language:"rust",extensions:_a,capabilities:{imports:"ast-with-regex-fallback",exports:"ast-with-regex-fallback"},parseImports:Qy,parseExports:Zy},RL=Qn({language:"ruby",extensions:Aa,imports:"ast-with-regex-fallback",parseImports:Yy}),CL=Qn({language:"c/cpp",extensions:La,imports:"ast-with-regex-fallback",parseImports:Oy}),vL=Qn({language:"dotnet",extensions:Jn,imports:"ast-dispatch-with-regex-fallback",parseImports:Gy}),IL={language:"dart",extensions:Ma,capabilities:{imports:"regex-only",exports:"regex-only"},parseImports:$y,parseExports:Hy},wL=Qn({language:"php",extensions:_r,imports:"ast-with-regex-fallback",parseImports:Wy}),EL=Qn({language:"clojure",extensions:xi,imports:"regex-only",parseImports:jy}),tb=[yL,bL,SL,xL,RL,CL,vL,IL,wL,EL];function Ka(e){return eb(tb,e)}function cne(e){return tb.find(n=>n.language===e)?.capabilities??null}var wd={clearGroups:["whole-project","source-file"]},DL=$("source-imports",wd),PL=$("source-exports",wd),kL=$("source-reexports",wd),nb=me({kind:"source-imports",invalidation:re("source-imports"),serialize:TL,deserialize:FL}),rb=me({kind:"source-reexports",invalidation:re("source-reexports"),serialize:_L,deserialize:AL});function wn(e,t){let n=te(t);return kL.get(e,n,()=>{let r=Ka(n);if(!r?.parseReExports)return[];let i=k(e,n);if(!i)return[];let o=he(e,n,i),s=dd(e),a=rb.read(e,n,o);if(a?.resolutionFingerprint===s)return a.reExports;let c=r.parseReExports(e,n,i);return rb.write(e,n,o,{resolutionFingerprint:s,reExports:c}),c})}function oe(e,t){let n=te(t);return DL.get(e,n,()=>{let r=Ka(n);if(!r)return[];let i=k(e,n);if(!i)return[];let o=he(e,n,i),s=dd(e),a=nb.read(e,n,o);if(a?.resolutionFingerprint===s)return a.imports;let c=r.parseImports(e,n,i);return nb.write(e,n,o,{resolutionFingerprint:s,imports:c}),c})}function Ja(e,t){let n=te(t);return PL.get(e,n,()=>{let r=Ka(n);if(!r?.parseExports)return[];let i=k(e,n);return i?r.parseExports(e,n,i):[]})}function TL(e){return JSON.stringify(e)}function FL(e){try{let t=JSON.parse(e);return!en(t)||typeof t.resolutionFingerprint!="string"||!Array.isArray(t.imports)?null:{resolutionFingerprint:t.resolutionFingerprint,imports:t.imports}}catch{return null}}function _L(e){return JSON.stringify(e)}function AL(e){try{let t=JSON.parse(e);return!en(t)||typeof t.resolutionFingerprint!="string"||!Array.isArray(t.reExports)?null:{resolutionFingerprint:t.resolutionFingerprint,reExports:t.reExports}}catch{return null}}function Lt(e){return{forFile(t,n){return ib(e,t,n)},forFiles(t,n){let r=new Map;for(let i of t)r.set(i,ib(e,i,n));return r}}}function ib(e,t,n){let r={file:t},i=n.facts||n.identifiers;if(n.text&&(r.text=k(e,t)),n.lines&&(r.lines=Ne(e,t)),n.ast&&(r.ast=ne(e,t)),n.imports&&(r.imports=oe(e,t)),n.reexports&&(r.reexports=wn(e,t)),i){let o=Ku(e,t),s=o.facts;n.facts&&(r.facts=s),o.unavailable&&(r.sourceFactsUnavailable=o.unavailable),n.identifiers&&s&&(r.identifiers=s.fileIdentifiers,r.identifierLineMap=s.identifierLineMap)}return r}function Nr(e,t){return e.all(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.start_char, der.end_line, der.end_char, d.relative_path, gs.display_name, gs.documentation
|
|
147
|
+
FROM global_symbols gs
|
|
148
|
+
JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
|
|
149
|
+
JOIN documents d ON der.document_id = d.id
|
|
150
|
+
WHERE ${t.where}
|
|
151
|
+
${e.pathExclusionsFor("d")}
|
|
152
|
+
${sb(t.orderBy)}
|
|
153
|
+
${ab(t.limit)}`,...t.params??[])}function Ei(e,t){return e.all(`SELECT
|
|
154
|
+
gs.id,
|
|
155
|
+
gs.symbol,
|
|
156
|
+
c.document_id,
|
|
157
|
+
MIN(c.start_line) AS start_line,
|
|
158
|
+
0 AS start_char,
|
|
159
|
+
MAX(c.end_line) AS end_line,
|
|
160
|
+
0 AS end_char,
|
|
161
|
+
d.relative_path,
|
|
162
|
+
gs.display_name,
|
|
163
|
+
gs.documentation
|
|
164
|
+
FROM global_symbols gs
|
|
165
|
+
JOIN mentions m ON m.symbol_id = gs.id
|
|
166
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
167
|
+
JOIN documents d ON c.document_id = d.id
|
|
168
|
+
WHERE m.role = 1
|
|
169
|
+
AND ${t.where}
|
|
170
|
+
${e.pathExclusionsFor("d")}
|
|
171
|
+
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name, gs.documentation
|
|
172
|
+
${sb(t.orderBy)}
|
|
173
|
+
${ab(t.limit)}`,...t.params??[])}function sb(e){return e?`ORDER BY ${e}`:""}function ab(e){return typeof e=="number"?`LIMIT ${e}`:""}function En(e){return!e||!e.trim()?null: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()||null}function Dn(e){if(!e)return null;let t=ob(e);if(t)return t.replace(/\n/g," ");let n=e.indexOf("|");if(n===-1)return e.replace(/\n/g," ");let r=e.slice(n+1);return(ob(r)??r).replace(/\n/g," ")}function ob(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}function LL(e,t={}){if(Xt(e.symbol)!==null)return t.includeClassMemberFallbacks===!0;let i=(e.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(i)}function Zn(e,t,n={}){let r=new Map;for(let o of t)e.length>0&&!LL(o,{includeClassMemberFallbacks:n.includeClassMemberFallbacks})||r.set(o.id,o);for(let o of e)r.set(o.id,o);let i=[...r.values()];return n.sort?i.sort((o,s)=>o.start_line-s.start_line||o.end_line-s.end_line||o.symbol.localeCompare(s.symbol)):i}var ML=$("file-definitions",{clearGroups:["definition-catalog"]}),NL=z("scoped-matched-definitions",{clearGroups:["definition-catalog"]}),OL=$("file-function-like-definitions",{clearGroups:["definition-catalog"]}),cb=new WeakMap;function ie(e,t,n={}){return n.includeClassMemberFallbacks?Ed(e,t,void 0,{includeClassMemberFallbacks:!0}):ML.get(e,t,()=>{let r=mb(e,t);if(r)return r;let i=Ed(e,t),o=We(e),s=Lt(e).forFile(t,{text:!0}).text;return o&&s&&db.write(e,t,he(e,t,s),{projectFingerprint:o,definitions:i.map(a=>({...a}))}),i})}function BL(e,t){return OL.get(e,t,()=>{let n=mb(e,t);return n?n.filter(r=>r.isFunctionLike):Ed(e,t,r=>r.isFunctionLike)})}var db=me({kind:"file-definitions",invalidation:re("file-definitions"),serialize:jL,deserialize:$L});function mb(e,t){let n=We(e);if(!n)return null;let r=Lt(e).forFile(t,{text:!0}).text;if(!r)return null;let i=db.read(e,t,he(e,t,r));return i?HL(i,n,t):null}function jL(e){return JSON.stringify(e)}function $L(e){try{let t=JSON.parse(e);return!en(t)||typeof t.projectFingerprint!="string"||!Array.isArray(t.definitions)?null:{projectFingerprint:t.projectFingerprint,definitions:t.definitions}}catch{return null}}function HL(e,t,n){if(e.projectFingerprint!==t)return null;let r=[];for(let i of e.definitions){let o=GL(i,n);if(!o)return null;r.push(o)}return r}function GL(e,t){return!en(e)||typeof e.symbolId!="number"||typeof e.symbol!="string"||typeof e.documentId!="number"||typeof e.startLine!="number"||typeof e.startChar!="number"&&e.startChar!==void 0||typeof e.endLine!="number"||typeof e.endChar!="number"&&e.endChar!==void 0||e.relativePath!==t||typeof e.leaf!="string"||typeof e.parentTypeName!="string"&&e.parentTypeName!==null||typeof e.isFunctionLike!="boolean"||typeof e.isTypeLike!="boolean"||typeof e.kind!="number"&&e.kind!==null||typeof e.documentation!="string"&&e.documentation!==null||typeof e.enclosingSymbol!="string"&&e.enclosingSymbol!==null?null:{symbolId:e.symbolId,symbol:e.symbol,documentId:e.documentId,startLine:e.startLine,startChar:e.startChar,endLine:e.endLine,endChar:e.endChar,relativePath:e.relativePath,leaf:e.leaf,parentTypeName:e.parentTypeName,isFunctionLike:e.isFunctionLike,isTypeLike:e.isTypeLike,kind:e.kind,documentation:e.documentation,enclosingSymbol:e.enclosingSymbol}}function Ed(e,t,n,r={}){let i=Zn(qL(e,t),UL(e,t),{sort:!0,includeClassMemberFallbacks:r.includeClassMemberFallbacks}).map(fb);return n&&(i=i.filter(n)),hb(e,t,i)}function qL(e,t){return e.all(`SELECT
|
|
174
|
+
gs.id,
|
|
175
|
+
gs.symbol,
|
|
176
|
+
der.document_id,
|
|
177
|
+
der.start_line,
|
|
178
|
+
der.start_char,
|
|
179
|
+
der.end_line,
|
|
180
|
+
der.end_char,
|
|
181
|
+
d.relative_path,
|
|
182
|
+
gs.display_name,
|
|
183
|
+
gs.kind,
|
|
184
|
+
gs.documentation,
|
|
185
|
+
gs.enclosing_symbol
|
|
186
|
+
FROM global_symbols gs
|
|
187
|
+
JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
|
|
188
|
+
JOIN documents d ON der.document_id = d.id
|
|
189
|
+
WHERE d.relative_path = ?
|
|
190
|
+
${e.symbolNoiseFor("gs")}
|
|
191
|
+
ORDER BY der.start_line, der.end_line`,t)}function UL(e,t){return e.all(`SELECT
|
|
192
|
+
gs.id,
|
|
193
|
+
gs.symbol,
|
|
194
|
+
c.document_id,
|
|
195
|
+
MIN(c.start_line) AS start_line,
|
|
196
|
+
0 AS start_char,
|
|
197
|
+
MAX(c.end_line) AS end_line,
|
|
198
|
+
0 AS end_char,
|
|
199
|
+
d.relative_path,
|
|
200
|
+
gs.display_name,
|
|
201
|
+
gs.kind,
|
|
202
|
+
gs.documentation,
|
|
203
|
+
gs.enclosing_symbol
|
|
204
|
+
FROM global_symbols gs
|
|
205
|
+
JOIN mentions m ON m.symbol_id = gs.id
|
|
206
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
207
|
+
JOIN documents d ON c.document_id = d.id
|
|
208
|
+
WHERE d.relative_path = ?
|
|
209
|
+
AND m.role = 1
|
|
210
|
+
${e.symbolNoiseFor("gs")}
|
|
211
|
+
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
|
|
212
|
+
ORDER BY start_line, end_line`,t)}function fb(e){return{symbolId:e.id,symbol:e.symbol,documentId:e.document_id,startLine:e.start_line,startChar:e.start_char??0,endLine:e.end_line,endChar:e.end_char??0,relativePath:e.relative_path,leaf:T(e.symbol),parentTypeName:Xt(e.symbol),isFunctionLike:ae(e.symbol),isTypeLike:be(e.symbol)==="type",kind:e.kind??null,documentation:e.documentation??null,enclosingSymbol:e.enclosing_symbol??null}}function Oe(e,t={}){return Dd(e,t.scope)}function Dd(e,t){return L(e,{scope:t,includeIgnored:!1}).flatMap(n=>ie(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function pb(e,t){return L(e,{scope:t,includeIgnored:!1}).flatMap(n=>BL(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function Lo(e,t){let n=NL.get(e,()=>new WeakMap),r=n.get(t.symbolMatches);r||(r=new Map,n.set(t.symbolMatches,r));let i=JSON.stringify({scope:t.scope??null,sqlPrefilter:t.sqlPrefilter??null}),o=r.get(i);if(o)return[...o];let s=lb(VL(e,t.scope,t.sqlPrefilter)),a=lb(zL(e,t.scope,t.sqlPrefilter)),c=new Set([...s.keys(),...a.keys()]),l=[];for(let u of[...c].sort()){if(e.isIgnored(u))continue;let d=Zn(s.get(u)??[],a.get(u)??[],{sort:!0}).filter(m=>t.symbolMatches(m.symbol));d.length!==0&&l.push(...hb(e,u,d.map(fb)))}return r.set(i,l),[...l]}function VL(e,t,n){let r=t?"AND d.relative_path LIKE ?":"",i=n?`AND ${gb("gs",n)}`:"",o=t?[`%${t}%`]:[];return e.all(`SELECT
|
|
213
|
+
gs.id,
|
|
214
|
+
gs.symbol,
|
|
215
|
+
der.document_id,
|
|
216
|
+
der.start_line,
|
|
217
|
+
der.start_char,
|
|
218
|
+
der.end_line,
|
|
219
|
+
der.end_char,
|
|
220
|
+
d.relative_path,
|
|
221
|
+
gs.display_name,
|
|
222
|
+
gs.kind,
|
|
223
|
+
gs.documentation,
|
|
224
|
+
gs.enclosing_symbol
|
|
225
|
+
FROM global_symbols gs
|
|
226
|
+
JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
|
|
227
|
+
JOIN documents d ON der.document_id = d.id
|
|
228
|
+
WHERE 1 = 1
|
|
229
|
+
${e.pathExclusionsFor("d")}
|
|
230
|
+
${r}
|
|
231
|
+
${i}
|
|
232
|
+
${e.symbolNoiseFor("gs")}
|
|
233
|
+
ORDER BY d.relative_path, der.start_line, der.end_line`,...o)}function zL(e,t,n){let r=t?"AND d.relative_path LIKE ?":"",i=n?`AND ${gb("gs",n)}`:"",o=t?[`%${t}%`]:[];return e.all(`SELECT
|
|
234
|
+
gs.id,
|
|
235
|
+
gs.symbol,
|
|
236
|
+
c.document_id,
|
|
237
|
+
MIN(c.start_line) AS start_line,
|
|
238
|
+
0 AS start_char,
|
|
239
|
+
MAX(c.end_line) AS end_line,
|
|
240
|
+
0 AS end_char,
|
|
241
|
+
d.relative_path,
|
|
242
|
+
gs.display_name,
|
|
243
|
+
gs.kind,
|
|
244
|
+
gs.documentation,
|
|
245
|
+
gs.enclosing_symbol
|
|
246
|
+
FROM global_symbols gs
|
|
247
|
+
JOIN mentions m ON m.symbol_id = gs.id
|
|
248
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
249
|
+
JOIN documents d ON c.document_id = d.id
|
|
250
|
+
WHERE m.role = 1
|
|
251
|
+
AND NOT EXISTS (
|
|
252
|
+
SELECT 1
|
|
253
|
+
FROM defn_enclosing_ranges existing_der
|
|
254
|
+
WHERE existing_der.symbol_id = gs.id
|
|
255
|
+
)
|
|
256
|
+
${e.pathExclusionsFor("d")}
|
|
257
|
+
${r}
|
|
258
|
+
${i}
|
|
259
|
+
${e.symbolNoiseFor("gs")}
|
|
260
|
+
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
|
|
261
|
+
ORDER BY d.relative_path, start_line, end_line`,...o)}function WL(e){return`(${e}.symbol LIKE '%().' OR ${e}.symbol LIKE '%()')`}function gb(e,t){return t==="callable"?WL(e):KL(e)}function KL(e){return`(${e}.symbol LIKE '%.' OR ${e}.symbol LIKE '%()')`}function lb(e){let t=new Map;for(let n of e){let r=t.get(n.relative_path);r?r.push(n):t.set(n.relative_path,[n])}return t}function Ya(e,t,n={}){if(t.length===0)return[];let r=t.flatMap(i=>ie(e,i)).filter(i=>!e.isIgnored(i.relativePath));return n.onlyDocumented&&(r=r.filter(i=>i.documentation!==null&&i.documentation!=="")),n.sort&&(r=r.sort((i,o)=>i.relativePath.localeCompare(o.relativePath)||i.startLine-o.startLine||i.endLine-o.endLine)),r.map(i=>({startLine:i.startLine,endLine:i.endLine,symbol:i.symbol,shortName:E(i.symbol),signature:En(Dn(i.documentation)),relativePath:i.relativePath,enclosingSymbol:i.enclosingSymbol}))}function Pd(e){let t=new Map,n=e.map((r,i)=>({definition:r,index:i,span:r.endLine-r.startLine})).sort((r,i)=>r.span-i.span||r.index-i.index);for(let{definition:r}of n)for(let i=r.startLine;i<=r.endLine;i+=1)t.has(i)||t.set(i,r);return t}function tn(e,t){let n=cb.get(e);return n||(n=Pd(e),cb.set(e,n)),n.get(t)??null}function Xa(e,t){let n=ie(e,t.relative_path).find(r=>r.symbolId===t.id);return n?{symbolId:n.symbolId,symbol:n.symbol,documentId:n.documentId,startLine:n.startLine,startChar:n.startChar,endLine:n.endLine,endChar:n.endChar,relativePath:n.relativePath}:{symbolId:t.id,symbol:t.symbol,documentId:t.document_id,startLine:t.start_line,startChar:t.start_char??0,endLine:t.end_line,endChar:t.end_char??0,relativePath:t.relative_path}}function hb(e,t,n){let r=Lt(e).forFile(t,{text:!0}).text,i=Yu(e,t);return i?eM(n,i,r):r?JL(n,r):n}function JL(e,t){let n=t.split(/\r?\n/),r=YL(e,n),i=XL(e,r),o=QL(i,n);return ZL(e,o)}function YL(e,t){let n=e.some(i=>Qa(i.symbol))?aM(t):null,r=new Map;for(let i of e)r.set(i.symbolId,sM(t,n,i));return r}function XL(e,t){return e.filter(n=>Qa(n.symbol)).map(n=>({definition:n,startLine:t.get(n.symbolId)??n.startLine})).sort((n,r)=>n.startLine-r.startLine||n.definition.startLine-r.definition.startLine||n.definition.symbol.localeCompare(r.definition.symbol))}function QL(e,t){let n=new Map;for(let r=0;r<e.length;r+=1){let i=e[r],o=e[r+1],s=o?Math.max(i.startLine,o.startLine-1):t.length-1;n.set(i.definition.symbolId,{startLine:i.startLine,endLine:cM(t,i.definition,i.startLine,s)})}return n}function ZL(e,t){return e.map(n=>{let r=t.get(n.symbolId);return r?{...n,startLine:r.startLine,endLine:r.endLine}:n})}function eM(e,t,n=null){let r=new Map;for(let i of t){let o=r.get(i.name);o?o.push(i):r.set(i.name,[i])}return e.map(i=>{if(!oM(i)||!i.leaf)return ub(i,n);let o=r.get(i.leaf);if(!o||o.length===0)return ub(i,n);let s=n?tM(i,o,n):null;if(s)return{...i,startLine:s.startLine,endLine:s.endLine};let a=o[0],c=Math.abs(a.startLine-i.startLine);for(let l=1;l<o.length;l+=1){let u=o[l],d=Math.abs(u.startLine-i.startLine);d<c&&(a=u,c=d)}return{...i,startLine:a.startLine,endLine:a.endLine}})}function tM(e,t,n){let r=nM(e.symbol);if(!r)return null;let i=n.split(/\r?\n/),o=new RegExp(`\\b${H(r)}\\b`);for(let s of t){let a=rM(i,s.startLine);if(a&&o.test(a))return s}return null}function nM(e){return e.match(/\/impl#\[([^\]]+)\]/)?.[1]??null}function rM(e,t){for(let n=t;n>=0;n-=1){let r=e[n]?.trim()??"";if(r){if(/^impl\b/.test(r))return iM(e,n,t);if(/^(?:struct|enum|trait|mod)\b/.test(r))return null}}return null}function iM(e,t,n){let r=[];for(let i=t;i<=n;i+=1){let o=e[i]??"";if(r.push(o),o.includes("{"))break}return r.join(" ")}function oM(e){return Qa(e.symbol)?!0:be(e.symbol)==="term"&&Xt(e.symbol)===null}function ub(e,t){if(!t||!e.leaf||be(e.symbol)!=="term"||Xt(e.symbol)!==null)return e;let n=H(e.leaf),r=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${n}\\b`),o=t.split(/\r?\n/).findIndex(s=>r.test(s));return o>=0?{...e,startLine:o,endLine:o}:e}function sM(e,t,n){if(!Qa(n.symbol))return n.startLine;let r=Math.max(0,Math.min(n.startLine,e.length-1));if(!t)return r;let i=t.get(n.leaf);if(!i||i.length===0)return r;let o=null;for(let s of i){let a=Math.abs(s-n.startLine);(!o||a<o.distance)&&(o={line:s,distance:a})}return o?.line??r}function aM(e){let t=/\b(?:function|def|fn)\s+([A-Za-z_$][\w$]*)/g,n=/\b([A-Za-z_$][\w$]*)\s*[:=]\s*(?:async\s*)?(?:function\b|\()/g,r=/^\s*(?:(?:export|public|private|protected|static|readonly|async|abstract|get|set)\s+)*([A-Za-z_$][\w$]*)\s*(?:<[^(]*>)?\s*\(/,i=/\b([A-Za-z_$][\w$]*)\s*\(/g,o=new Map,s=(a,c)=>{let l=o.get(a);if(!l){o.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)};for(let a=0;a<e.length;a+=1){let c=e[a]??"";for(let u of c.matchAll(t))u[1]&&s(u[1],a);for(let u of c.matchAll(n))u[1]&&s(u[1],a);let l=c.match(r);l?.[1]&&s(l[1],a);for(let u of c.matchAll(i))u[1]&&s(u[1],a)}return o}function cM(e,t,n,r){let i=Math.max(n,Math.min(e.length-1,r)),o=Math.max(n,Math.min(i,t.endLine)),s=0,a=0,c=!1;for(let l=n;l<=i;l+=1){let u=lM(e[l]??"");for(let d of u)d==="{"?(s+=1,c=!0):d==="}"?s=Math.max(0,s-1):d==="("?a+=1:d===")"&&(a=Math.max(0,a-1));if(c&&s===0||!c&&a===0&&l>=o)return l}return o}function lM(e){let t="",n=null,r=!1;for(let i=0;i<e.length;i+=1){let o=e[i],s=e[i+1];if(!n&&o==="/"&&s==="/"){t+=" ".repeat(e.length-i);break}if(n){if(r){r=!1,t+=" ";continue}if(o==="\\"){r=!0,t+=" ";continue}o===n&&(n=null),t+=" ";continue}if(o==='"'||o==="'"||o==="`"){n=o,t+=" ";continue}t+=o}return t}function Qa(e){return e.includes("().")}function Za(e){let t=Te(e);if("kind"in t)return[];let n=[];for(let r=t.descriptors.length-2;r>=0;r-=1){let i=t.descriptors[r];i?.suffix==="type"&&i.name&&n.push(i.name)}return n}var uM=$("symbol-resolution",{clearGroups:[]});function G(e,t){return Or(e,t).match}function Or(e,t){return uM.get(e,t,()=>{let n=bb(e,t.trim()).filter(o=>!e.isIgnored(o.relative_path));if(n.length>0)return Mo(e,n);let r=yM(e,t);if(r&&!e.isIgnored(r.relative_path))return Mo(e,[r]);let i=dM(e,t);return i.length>0?Mo(e,i):gM(e,t)})}function dM(e,t){let n=ec(t),r=kd(n);if(!r)return[];let i=`%${r.path}%`,o=r.leaf;return mM(e,i,o,n)}function mM(e,t,n,r){let i=Zn([],[...fM(e,t,n),...pM(e,t,n)]).filter(o=>!e.isIgnored(o.relative_path)).filter(o=>Di(o,r)>1);return i.sort((o,s)=>Di(s,r)-Di(o,r)||o.end_line-o.start_line-(s.end_line-s.start_line)||o.start_line-s.start_line||o.symbol.localeCompare(s.symbol)),i}function fM(e,t,n){return Nr(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function pM(e,t,n){return Ei(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function gM(e,t){let n=ec(t),r=vM(t),i=RM(e,r),o=IM(i,t,n).filter(a=>!e.isIgnored(a.relative_path));if(o.length>0)return Mo(e,o);let s=[];for(let a of i){if(e.isIgnored(a.relative_path))continue;let c=CM(a,t,n,r);c<=0||s.push({row:a,score:c})}return s.sort((a,c)=>c.score-a.score||a.row.end_line-a.row.start_line-(c.row.end_line-c.row.start_line)||a.row.relative_path.localeCompare(c.row.relative_path)||a.row.symbol.localeCompare(c.row.symbol)),Mo(e,s.map(a=>a.row))}function Mo(e,t){let n=t.map(i=>Xa(e,i)),r=n[0]??null;return{match:r,candidates:r?hM(n,r):[],total:n.length}}function hM(e,t){let n=new Set([`${t.symbolId}:${t.relativePath}:${t.startLine}`]),r=[];for(let i of e){let o=`${i.symbolId}:${i.relativePath}:${i.startLine}`;if(!n.has(o)&&(n.add(o),r.push({symbol:i.symbol,shortName:E(i.symbol),relativePath:i.relativePath,startLine:i.startLine}),r.length>=5))break}return r}function yM(e,t){let n=t.match(/^(.+):(\d+)-(\d+)$/);if(!n)return;let[,r,i,o]=n,s=Ta(e,r,{allowMultiple:!1})[0]?.relativePath;if(!s)return;let a=Math.max(0,parseInt(i,10)-1),c=Math.max(a,parseInt(o,10)-1);return bM(e,s,a,c)??SM(e,s,a,c)}function bM(e,t,n,r){return Nr(e,{where:"d.relative_path = ? AND der.start_line <= ? AND der.end_line >= ?",params:[t,n,r],orderBy:"(der.end_line - der.start_line) ASC",limit:1})[0]}function SM(e,t,n,r){return Ei(e,{where:"d.relative_path = ? AND c.start_line <= ? AND c.end_line >= ?",params:[t,n,r],orderBy:"(MAX(c.end_line) - MIN(c.start_line)) ASC",limit:1})[0]}function No(e,t){let n=bb(e,t).find(r=>!e.isIgnored(r.relative_path));return n?Xa(e,n):null}function bb(e,t){let n=Nr(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, der.start_line"}),r=n.length>0?[]:Ei(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, start_line"});return Zn(n,r)}function Oo(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=xM(e,t.symbolId)[0];return n?Xa(e,n):null}function xM(e,t){let n=Nr(e,{where:"gs.id = ?",params:[t],orderBy:"der.start_line, der.end_line"}),r=Ei(e,{where:"gs.id = ?",params:[t],orderBy:"start_line, end_line"});return Zn(n,r)}function RM(e,t){let n=t.map(()=>"(gs.symbol LIKE ? OR d.relative_path LIKE ? OR COALESCE(gs.display_name, '') LIKE ?)"),r=t.flatMap(a=>{let c=`%${a}%`;return[c,c,c]}),i=n.join(`
|
|
262
|
+
AND `),o=Nr(e,{where:i,params:r,limit:200}),s=Ei(e,{where:i,params:r,limit:200});return Zn(o,s)}function CM(e,t,n,r){let i=t.trim(),o=n,s=o.replace(/\(\)$/,""),a=t.toLowerCase(),c=n.toLowerCase(),l=c.replace(/\(\)$/,""),u=e.symbol,d=E(e.symbol),m=T(e.symbol),f=e.display_name??"",p=e.symbol.toLowerCase(),g=d.toLowerCase(),y=m.toLowerCase(),h=f.toLowerCase(),S=e.relative_path.toLowerCase(),b=/[/:.]/.test(n),R=kd(n),x=R?.leaf.toLowerCase(),v=0;return(u===i||u===o)&&(v+=1150),(d===i||d===o)&&(v+=1100),f===s&&(v+=1180),m===s&&(v+=1160),(`${m}()`===i||`${m}()`===o)&&(v+=955),(p===a||p===c)&&(v+=1e3),(g===a||g===c)&&(v+=950),(S===a||S===c)&&(v+=925),(S.endsWith(`/${c}`)||S.endsWith(`/${a}`))&&(v+=875),h===l&&(v+=850),y===l&&(v+=825),(`${y}()`===a||`${y}()`===c)&&(v+=820),(g.endsWith(`:${c}`)||g.endsWith(`:${l}`)||g.endsWith(`:${l}()`))&&(v+=800),p.includes(c)&&(v+=120),g.includes(c)&&(v+=140),S.includes(c)&&(v+=140),h.includes(c)&&(v+=110),r.every(C=>{let w=C.toLowerCase();return p.includes(w)||g.includes(w)||S.includes(w)||h.includes(w)})&&(v+=100+r.length*15),R&&S.includes(R.path.toLowerCase())&&(v+=360,x&&(y===x||`${y}()`===x||`${y}()`==`${x}()`)&&(v+=700),ye(e.symbol)&&(v+=180)),ae(e.symbol)&&y===l&&(v+=60),!b&&Wn(e.symbol)&&(v-=160),v-=Math.min(50,Math.max(0,e.end_line-e.start_line)),v}function kd(e){let t=e.trim().replace(/\\/g,"/"),n=t.lastIndexOf("/");if(n<=0||n===t.length-1)return null;let r=t.slice(n+1).replace(/\(\)$/,"");return!r||r.includes(".")?null:{path:t.slice(0,n),leaf:r}}function ec(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function vM(e){let t=ec(e),n=t.split(/[^A-Za-z0-9_]+/).map(r=>r.trim()).filter(r=>r.length>0);return n.length>0?[...new Set(n)]:[t]}function IM(e,t,n){let r=t.trim(),i=e.filter(o=>{let s=E(o.symbol),a=(o.display_name??"").trim();return o.symbol===r||s===r||s===n||a===r||a===n||`${a}()`===r||Di(o,n)>1||o.relative_path===r});return i.length===0?[]:(i.sort((o,s)=>Di(s,n)-Di(o,n)||o.end_line-o.start_line-(s.end_line-s.start_line)||o.relative_path.localeCompare(s.relative_path)||o.symbol.localeCompare(s.symbol)),i)}function Di(e,t){let n=kd(t);if(!n)return 0;let r=e.relative_path.toLowerCase(),i=T(e.symbol).toLowerCase(),o=n.path.toLowerCase(),s=n.leaf.toLowerCase();return r.includes(o)?i!==s?1:ye(e.symbol)?Xt(e.symbol)===null?5:4:Xt(e.symbol)===null?3:2:0}function Sb(e,t,n=5){let r=yb(t);if(!r)return[];let i=Nr(e,{where:"1 = 1",orderBy:"d.relative_path, der.start_line",limit:5e3}),o=new Map;for(let s of i){if(e.isIgnored(s.relative_path))continue;let a=E(s.symbol),c=T(s.symbol),l=s.display_name??c,u=[a,c,l].filter(f=>f.trim().length>0),d=Math.min(...u.map(f=>wM(yb(f),r))),m=o.get(a);(!m||d<m.distance)&&o.set(a,{shortName:a,distance:d})}return[...o.values()].sort((s,a)=>s.distance-a.distance||s.shortName.localeCompare(a.shortName)).slice(0,n).map(s=>s.shortName)}function yb(e){return ec(e).toLowerCase().replace(/[^a-z0-9_]+/g,"")}function wM(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let n=Array.from({length:t.length+1},(r,i)=>i);for(let r=0;r<e.length;r++){let i=[r+1];for(let o=0;o<t.length;o++){let s=e[r]===t[o]?0:1;i[o+1]=Math.min(i[o]+1,n[o+1]+1,n[o]+s)}n=i}return n[t.length]}function tc(e,t,n,r={}){if(!n)return[];let i=k(e,t);return i?i.indexOf(n)===-1?[]:(Pn(e,t).get(n)??[]).filter(s=>!EM(s,r)):[]}function EM(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var DM=$("file-identifiers",{clearGroups:["whole-project","source-file"]});function xb(e,t){let n=Y(e,t);return n?n.fileIdentifiers:DM.get(e,t,()=>new Set(Pn(e,t).keys()))}var PM=$("file-ident-lines",{clearGroups:["whole-project","source-file"]});function Pn(e,t){let n=Y(e,t);return n?n.identifierLineMap:PM.get(e,t,()=>TM(e,t))}var kM=$("file-idents-by-line",{clearGroups:["whole-project","source-file"]});function Rb(e,t){let n=Y(e,t);return n?n.identifiersByLine:kM.get(e,t,()=>{let r=Pn(e,t),i=0;for(let s of r.values()){let a=s[s.length-1];a!==void 0&&a>i&&(i=a)}let o=new Array(i+1);for(let s=0;s<=i;s+=1)o[s]=new Set;for(let[s,a]of r)for(let c of a)o[c].add(s);return o})}function TM(e,t){let n=new Map,r=(a,c)=>{let l=n.get(a);if(!l){n.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)},i=k(e,t);if(!i)return n;let o=Tt(i).split(/\r?\n/),s=/\b([A-Za-z_$][\w$]*)\b/g;for(let a=0;a<o.length;a+=1){let c=o[a]??"";for(let l of c.matchAll(s))l[1]&&r(l[1],a)}return n}function Cb(e,t){return nc(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT
|
|
263
|
+
m.symbol_id,
|
|
264
|
+
d.relative_path,
|
|
265
|
+
COUNT(*) AS ref_count
|
|
266
|
+
FROM mentions m
|
|
267
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
268
|
+
JOIN documents d ON c.document_id = d.id
|
|
269
|
+
WHERE m.role != 1
|
|
270
|
+
${r}
|
|
271
|
+
${e.pathExclusionsFor("d")}
|
|
272
|
+
GROUP BY m.symbol_id, d.relative_path`,...n??[])})}function vb(e,t){return nc(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id, d.relative_path
|
|
273
|
+
FROM mentions m
|
|
274
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
275
|
+
JOIN documents d ON c.document_id = d.id
|
|
276
|
+
WHERE m.role != 1
|
|
277
|
+
${r}
|
|
278
|
+
${e.pathExclusionsFor("d")}`,...n??[])}).filter(n=>n.symbol_id!==null)}function Ib(e,t){return nc(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id
|
|
279
|
+
FROM mentions m
|
|
280
|
+
WHERE m.role != 1
|
|
281
|
+
${r}`,...n??[])}).filter(n=>n.symbol_id!==null)}function Pi(e,t){return nc(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id, d.relative_path, c.document_id,
|
|
282
|
+
c.start_line AS chunk_start, c.end_line AS chunk_end
|
|
283
|
+
FROM mentions m
|
|
284
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
285
|
+
JOIN documents d ON c.document_id = d.id
|
|
286
|
+
WHERE m.role != 1
|
|
287
|
+
${r}
|
|
288
|
+
${e.pathExclusionsFor("d")}
|
|
289
|
+
ORDER BY d.relative_path, c.start_line`,...n??[])})}function nc(e,t,n){if(!t)return n();if(t.length===0)return[];let r=[];for(let i=0;i<t.length;i+=750)r.push(...n(t.slice(i,i+750)));return r}function rc(e,t){let n=wb(e);return n?t.filter(r=>wb(r.file)===n):t}function ic(e,t,n,r){let i=n.find(o=>o.file===t);if(i)return i;if(r){let o=new Set(oe(e,t).map(s=>s.sourcePath).filter(s=>!!s));for(let s of n)for(let a of o)if(gt(a,s.file))return s;return null}return n.length===1?n[0]:null}function wb(e){let t=N(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var FM=z("global-leaf-index",{clearGroups:["whole-project"]});function kn(e){return FM.get(e,()=>{let t=e.all(`SELECT gs.id, gs.symbol,
|
|
290
|
+
COALESCE(der_doc.relative_path, mention_doc.relative_path) AS relative_path
|
|
291
|
+
FROM global_symbols gs
|
|
292
|
+
LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
293
|
+
LEFT JOIN documents der_doc ON der_doc.id = der.document_id
|
|
294
|
+
LEFT JOIN (
|
|
295
|
+
SELECT m.symbol_id, MIN(d.relative_path) AS relative_path
|
|
296
|
+
FROM mentions m
|
|
297
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
298
|
+
JOIN documents d ON c.document_id = d.id
|
|
299
|
+
WHERE m.role = 1
|
|
300
|
+
GROUP BY m.symbol_id
|
|
301
|
+
) mention_doc ON mention_doc.symbol_id = gs.id
|
|
302
|
+
WHERE 1 = 1
|
|
303
|
+
${e.symbolNoiseFor("gs")}`),n=new Map;for(let r of t){if(!r.relative_path||e.isIgnored(r.relative_path))continue;let i=T(r.symbol);if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.some(s=>s.symbolId===r.id)||o.push({symbol:r.symbol,symbolId:r.id,file:r.relative_path})}return n})}var Eb=/[A-Za-z_$][A-Za-z0-9_$]*/g,Db=/^[A-Za-z_$][A-Za-z0-9_$]*$/,_M=512;function Bo(e){let t=[],n=!1;for(let r of e)r&&(n=!0,Db.test(r)||t.push(r));return{candidateNames:e,hasUsableCandidate:n,nonIdentifierNames:t}}function oc(e,t){let n=AM(t)?t:Bo(t);if(n.candidateNames.size===0||!n.hasUsableCandidate)return!0;if(n.candidateNames.size<=_M){for(let i of n.candidateNames)if(i){if(Db.test(i)){if(LM(i).test(e))return!0;continue}if(e.includes(i))return!0}return!1}Eb.lastIndex=0;let r;for(;(r=Eb.exec(e))!==null;)if(n.candidateNames.has(r[0]))return!0;for(let i of n.nonIdentifierNames)if(e.includes(i))return!0;return!1}function AM(e){return"candidateNames"in e}function LM(e){return new RegExp(`(?<![A-Za-z_$0-9])${H(e)}(?![A-Za-z_$0-9])`)}var MM=$("source-import-paths-by-local-name",{clearGroups:["whole-project","source-file"]});function sc(e,t){let n=yn(t);return MM.get(e,n,()=>NM(e,n))}function NM(e,t){let n=new Map;for(let r of oe(e,t)){if(!r.sourcePath)continue;let i=r.localName??r.importedName;if(i&&Pb(n,i,r.sourcePath),r.kind==="namespace")for(let o of r.usedMembers)Pb(n,o,r.sourcePath)}return n}function Pb(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function ki(e,t,n){let r=kn(e).get(n);if(!r||r.length===0)return[];if(r.length===1)return[jo(r[0])];let i=r.filter(c=>c.file===t);if(i.length>0)return i.map(jo);let o=sc(e,t),s=o.get(n);if(s)for(let c of s){let l=r.filter(u=>gt(c,u.file));if(l.length>0)return l.map(jo)}let a=new Set;for(let c of o.values())for(let l of c)a.add(l);for(let c of a){let l=r.filter(u=>gt(c,u.file));if(l.length>0&&l.length===r.length)return l.map(jo)}return[]}function kb(e,t,n){let r=ki(e,t,n);if(r.length>0)return r;let i=kn(e).get(n);return!i||i.length===0?[]:i.map(jo)}function Tb(e,t,n={}){let r=OM(e,t);if(!r)return[];let i=Oo(e,t);if(n.semantic!==!1&&n.semanticEvidence){let s=n.semanticEvidence.references(e,{...i,leaf:r.identifier,parentTypeName:null,isFunctionLike:!1,isTypeLike:!1,kind:null,documentation:null,enclosingSymbol:null});if(s.length>0){let a=new Map;for(let c of s){let l=a.get(c.file)??[];l.push(c.line),a.set(c.file,l)}return ac(e,a)}}let o=new Map;for(let s of ct(e)){let a=BM(e,r,s);a.length>0&&o.set(s,a)}return ac(e,o)}function OM(e,t){let n=Oo(e,t);if(!n)return null;let r=T(n.symbol);return r?{symbolId:n.symbolId,relativePath:n.relativePath,startLine:n.startLine,endLine:n.endLine,identifier:r}:null}function BM(e,t,n){let r=k(e,n);return!r||r.indexOf(t.identifier)===-1?[]:n!==t.relativePath&&!ki(e,n,t.identifier).some(o=>o.symbolId===t.symbolId)?[]:tc(e,n,t.identifier,n===t.relativePath?{excludeStartLine:t.startLine,excludeEndLine:t.endLine}:{})}function Fb(e,t,n={}){let r=new Map;for(let c of t){if(!c.leaf)continue;let l=r.get(c.leaf)??[];l.push(c),r.set(c.leaf,l)}if(r.size===0)return new Map;let i=new Set(t.map(c=>c.symbolId)),o=new Set(r.keys()),s=Bo(o),a=new Map;for(let c of ct(e)){if(n.skipPath?.(c)||!oc(k(e,c),s))continue;let l=xb(e,c);if(l.size!==0){for(let u of l)if(r.has(u))for(let d of ki(e,c,u)){if(!i.has(d.symbolId)||c===d.relativePath)continue;let m=a.get(d.symbolId);m||(m=new Set,a.set(d.symbolId,m)),m.add(c)}}}return a}function jo(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function ac(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=ie(e,i);for(let a of o){let c=tn(s,a),l=`${i}|${a}|${c?.symbol??""}`;r.has(l)||(r.add(l),n.push({file:i,line:a,enclosingSymbol:c?.symbol??null}))}}return n}function Td(e,t){return Fd(e,[t]).get(t.symbolId)??[]}function Fd(e,t){let n=t.map(o=>({symbolId:o.symbolId,prelude:UM(e,o)})).filter(o=>o.prelude!==null),r=HM(e,n.map(o=>o.symbolId)),i=new Map;for(let{symbolId:o,prelude:s}of n){let a=$M(e,r.get(o)??new Map,s.match,s.identifier);i.set(o,ac(e,a))}return i}function nn(e,t,n={}){return jM(e,t,n).map(r=>({file:r.file,line:r.line,enclosingSymbol:r.enclosingSymbol}))}function jM(e,t,n={}){let r=Tb(e,t,{semantic:n.semantic,semanticEvidence:n.semanticEvidence}),i=r.length>0?_b(r,"source-attribution"):_b(Td(e,t),"scip-reference-chunk");return n.includeIgnored===!0?i:i.filter(o=>!e.isIgnored(o.file))}function _b(e,t){return e.map(n=>({...n,provenance:t}))}function $M(e,t,n,r){let i=new Map;for(let[o,s]of t)i.set(o,GM(e,o,s,n,r));return i}function HM(e,t){let n=new Map;for(let r of Pi(e,t)){if(e.isIgnored(r.relative_path))continue;let i=n.get(r.symbol_id);i||(i=new Map,n.set(r.symbol_id,i));let o=i.get(r.relative_path);o||(o=[],i.set(r.relative_path,o)),o.push({start_line:r.chunk_start,end_line:r.chunk_end})}return n}function GM(e,t,n,r,i){let o=t===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{},s=i?tc(e,t,i,o):[];return n.flatMap(a=>qM(s,a))}function qM(e,t){let n=e.filter(r=>r>=t.start_line&&r<=t.end_line);return n.length>0?n:[t.start_line]}function UM(e,t){let n=Oo(e,t);return n?{match:n,identifier:T(n.symbol)||null}:null}var Ab=Pr({kind:"file-dependency-graph",invalidation:re("file-dependency-graph"),serialize:e=>JSON.stringify(e),deserialize:XM}),VM=$("file-dep-graph",{clearGroups:["whole-project"]});function le(e,t,n={}){let r=n.scipEdges??"all-references",i=n.sourceEdges??"imports-only",o=KM(t,r,i);return VM.get(e,o,()=>{let s=new Set(L(e,{includeIgnored:!1})),a=We(e),c=0,l=0,u=null,d=!1,m=0,f=0;return D("file-dep-graph.product",()=>{if(a){let h=Ab.read(e,o,a);if(h){d=!0;let S=YM(h);return c=h.sourceFileCount,l=h.sourceEdgeCount,m=h.scipEdgeCount,f=S.size,u=h.sourceDependencyFingerprint,S}}let p=D("file-dep-graph.source-imports",()=>{let h=zM(e,s,t,i);return c=h.files.length,l=h.edges.length,u=h.fingerprint,h},()=>({scope:t??null,sourceEdges:i,files:c,edges:l})),g=new Map,y=(h,S)=>tN(e,g,s,h,S);D("file-dep-graph.scip-edges",()=>{for(let h of eN(e,t,r))m+=1,y(h.from_file,h.to_file)},()=>({scope:t??null,edges:m}));for(let h of p.edges)y(h.fromFile,h.toFile);return f=g.size,a&&Ab.write(e,o,a,{sourceDependencyFingerprint:p.fingerprint,sourceFileCount:p.files.length,sourceEdgeCount:p.edges.length,scipEdgeCount:m,graph:JM(g)}),g},()=>({scope:t??null,available:a!==null,hit:d,files:c,sourceEdges:l,sourceEdgeMode:i,scipEdges:m,graphFiles:f,sourceDependencyFingerprint:u}))})}function zM(e,t,n,r){let i=[],o=[];for(let s of t)if(!(n&&!s.includes(n))){i.push(s);for(let a of oe(e,s))a.sourcePath&&o.push({fromFile:s,toFile:a.sourcePath});if(r==="imports-and-reexports")for(let a of wn(e,s))a.sourcePath&&o.push({fromFile:s,toFile:a.sourcePath})}return{files:i,edges:o,fingerprint:WM(i,o)}}function WM(e,t){let n=t.map(r=>`${r.fromFile}\0${r.toFile}`).sort();return ke(JSON.stringify({files:e,edges:n}))}function KM(e,t,n){return`edge-mode-v3:${t}:${n}:${e??"<all>"}`}function JM(e){return[...e].map(([t,n])=>[t,[...n]])}function YM(e){return new Map(e.graph.map(([t,n])=>[t,new Set(n)]))}function XM(e){let t=JSON.parse(e);return QM(t)?t:null}function QM(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.sourceDependencyFingerprint=="string"&&typeof t.sourceFileCount=="number"&&typeof t.sourceEdgeCount=="number"&&typeof t.scipEdgeCount=="number"&&Array.isArray(t.graph)&&t.graph.every(ZM)}function ZM(e){return Array.isArray(e)&&e.length===2&&typeof e[0]=="string"&&Array.isArray(e[1])&&e[1].every(t=>typeof t=="string")}function eN(e,t,n){let r=t?"AND d1.relative_path LIKE ?":"",i=t?[`%${t}%`]:[],o=n==="imports-only"?"AND m.role = 2":"AND m.role != 1";return e.all(`SELECT DISTINCT
|
|
304
|
+
d1.relative_path AS from_file,
|
|
305
|
+
d2.relative_path AS to_file
|
|
306
|
+
FROM mentions m
|
|
307
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
308
|
+
JOIN documents d1 ON c.document_id = d1.id
|
|
309
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
310
|
+
JOIN (
|
|
311
|
+
SELECT m2.symbol_id, c2.document_id
|
|
312
|
+
FROM mentions m2
|
|
313
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
314
|
+
WHERE m2.role = 1
|
|
315
|
+
GROUP BY m2.symbol_id
|
|
316
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
317
|
+
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
318
|
+
WHERE d1.id != d2.id
|
|
319
|
+
${o}
|
|
320
|
+
${e.pathExclusionsFor("d1","d2")}
|
|
321
|
+
${r}`,...i)}function tN(e,t,n,r,i){if(r===i||e.isIgnored(r)||e.isIgnored(i)||!n.has(i))return;let o=t.get(r);o||(o=new Set,t.set(r,o)),o.add(i)}function cc(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath)??[];r.push(n),t.set(n.relativePath,r)}return t}function Lb(e){let t=new Map,n=rN(e),r=new Map;return i=>{let o=nN(i),s=r.get(o);if(s!==void 0)return s;if(!n.has(i.file))return r.set(o,i.symbol),i.symbol;let a=t.get(i.file);a||(a=iN(ie(e,i.file)),t.set(i.file,a));let c=oN(a,i);return r.set(o,c),c}}function nN(e){return`${e.file}\0${e.symbol}\0${e.line}`}function rN(e){return new Set(e.all("SELECT relative_path FROM documents").map(t=>t.relative_path))}function iN(e){let t=new Map,n=new Map;for(let r of e){let i=t.get(r.leaf);i?i.push(r):t.set(r.leaf,[r]);let o=n.get(r.startLine);o?o.push(r):n.set(r.startLine,[r])}return{definitions:e,byLeaf:t,byStartLine:n}}function oN(e,t){if(e.definitions.length===0)return t.symbol;let n=cN(t.symbol),r=sN(e.byLeaf,n),i=aN(r,t.line);if(i)return i.symbol;let o=e.byStartLine.get(t.line)??[];return o.length===1?o[0].symbol:t.symbol}function sN(e,t){let n=[],r=new Set;for(let i of t)for(let o of e.get(i)??[])r.has(o.symbolId)||(r.add(o.symbolId),n.push(o));return n}function aN(e,t){let n=null;for(let r of e)if(!(r.startLine>t||r.endLine<t)){if(r.startLine===t)return r;(!n||r.endLine-r.startLine<n.endLine-n.startLine)&&(n=r)}return n}function cN(e){let t=new Set([e]),r=e.split(/::|\.|#/).filter(Boolean).at(-1);return r&&t.add(r),t}function Mb(e,t){let r=oe(e,t).map(i=>uN(t,i));return{usage:r,positions:dN(e,t,r)}}function Nb(e,t){return{importUsage(n){let r=e.importUsageFacts(n);if(!t||r.positions.length===0)return r.usage;let i=t.importDefinitionsForFile(n,r.positions);return i.available?lN(r.usage,i.sourcePaths):r.usage}}}function lN(e,t){return e.map((n,r)=>{let i=t.get(String(r));return i?{...n,sourcePath:i}:n})}function uN(e,t){let n=t.isTypeOnly===!0,r=t.kind==="side-effect"||n||t.used;return{importer:e,sourcePath:t.sourcePath,importedName:t.importedName,localName:t.localName,kind:t.kind,isTypeOnly:n,isUsed:r,isTypeUsed:n,isValueUsed:t.kind==="side-effect"||!n&&t.used,references:[]}}function dN(e,t,n){let r=ne(e,t);if(!r)return[];let i=mN(r.rootNode),o=new Map;for(let a of i){let c=o.get(Ad(a.importedName,a.localName));c?c.push(a.position):o.set(Ad(a.importedName,a.localName),[a.position])}let s=[];return n.forEach((a,c)=>{let l=o.get(Ad(a.importedName,a.localName??a.importedName))?.shift();l&&s.push({...l,id:String(c),file:t})}),s}function mN(e){let t=[];for(let n of e.descendantsOfType("use_declaration")){let r=n.namedChildren.find(i=>i.type!=="visibility_modifier");r&&t.push(...lc(r,""))}return t.filter(n=>n.importedName!=="*")}function lc(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":return[{importedName:e.text,localName:e.text,position:_d(e,e.text)}];case"scoped_identifier":{let n=e.text.split("::").pop()??e.text;return[{importedName:n,localName:n,position:_d(e,n)}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=wi(t,n.text);return r.namedChildren.flatMap(o=>lc(o,i))}case"use_list":return e.namedChildren.flatMap(n=>lc(n,t));case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);return!n||!r?[]:lc(n,t).map(i=>({...i,localName:r.text}))}case"use_wildcard":{let n=e.namedChild(0),r="*";return[{importedName:r,localName:r,position:_d(n??e,r)}]}default:return[]}}function _d(e,t){let n=Math.max(0,e.text.lastIndexOf(t));return{id:"",file:"",line:e.startPosition.row,column:e.startPosition.column+n+fN(t)}}function fN(e){return Math.max(0,Math.min(e.length-1,1))}function Ad(e,t){return`${e}\0${t}`}import{spawnSync as Zd}from"child_process";import{existsSync as em}from"fs";import{fileURLToPath as CO}from"url";function er(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}import{execFileSync as Gb}from"child_process";import{createHash as SN}from"crypto";import{existsSync as uc,statSync as xN}from"fs";import{createRequire as RN}from"module";import{platform as CN}from"os";import{dirname as Hb,join as $o}from"path";import{execFileSync as Ob,spawnSync as pN}from"child_process";import{platform as gN}from"os";var Bb=gN()==="win32";function Vre(e,t=pN){try{return t(e,["--version"],{stdio:"ignore",timeout:1e4}).status===0}catch{return!1}}function jb(e){let t=Bb?"where":"which";try{return Ob(t,[e],{stdio:"pipe",timeout:1e4,killSignal:"SIGKILL"}),!0}catch{return!1}}var hN=/\.(?:c|m)?js$/i,yN=/\.(?:exe|com)$/i;function zre(e,t){return hN.test(e)?{binary:process.execPath,args:[e,...t]}:{binary:e,args:[...t]}}function bN(e,t){return Ob(e,t,{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4,killSignal:"SIGKILL"})}function $b(e,t={}){let n=t.isWindows??Bb,r=t.lookup??bN,i;try{i=r(n?"where":"which",[e])}catch{return null}let o=i.split(/\r?\n/).map(s=>s.trim()).filter(Boolean);return n?o.find(s=>yN.test(s))??null:o[0]??null}var vN=RN(import.meta.url),qb={language:"rust",indexerBinary:"rust-analyzer",installUrl:"https://github.com/rust-lang/rust-analyzer"};function Ld(e){return[e.indexerBinary,...e.binaryAliases??[]]}function IN(e){let t=Ld(e);return t.length===1?t[0]:t.join(" or ")}function Md(e){for(let t of Ld(e)){let n=$b(t);if(n)return n}return EN(e)}function rie(e){return Md(e)!==null||wN(e)}function wN(e){return Ub(e)!==null}function EN(e){let t=Ub(e);if(!t)return null;let r=JSON.parse(O(t,"indexer package manifest")).bin;if(!r)return null;if(typeof r=="string")return $o(Hb(t),r);for(let i of Ld(e)){let o=r[i];if(o)return $o(Hb(t),o)}return null}function Ub(e){if(!e.bundledNpmPackage)return null;try{return vN.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function DN(e,t){for(let n of e.projectLocalBinaries??[]){let r=$o(t,n);if(uc(r))return r}return null}function PN(e,t){for(let n of e.projectLocalBinaries??[]){let r=$o(t,n);if(uc(r))return Vb(t,n,r)}return null}function iie(e,t){let n=kN(e,t);if(!n||n.canonicalPath!==t.canonicalPath||n.sha256!==t.sha256||n.size!==t.size||n.mtimeMs!==t.mtimeMs||n.device!==t.device||n.inode!==t.inode||n.executable!==t.executable)throw new Error(`refusing changed project-local indexer ${t.relativePath}; review the current file and rerun with --trust-project-tools`)}function kN(e,t){try{return Vb(e,t.relativePath,t.configuredPath)}catch{return null}}function Vb(e,t,n){let r={maxBytes:268435456,inputKind:"project-local indexer"},i=bn(e,t,r),o=ba(e,t,r),s=xN(i.absolutePath);return{configuredPath:n,canonicalPath:i.absolutePath,relativePath:t,sha256:SN("sha256").update(o).digest("hex"),size:i.size,mtimeMs:i.mtimeMs,device:i.device,inode:i.inode,executable:(s.mode&73)!==0}}function TN(e,t,n={}){return(n.trustProjectTools?PN(e,t)?.canonicalPath:null)??Md(e)}function oie(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||Nd(n,t))return t;let r=Wb(n,t);return r?{...t,DOTNET_ROOT:r}:t}function zb(e,t,n={}){let r=IN(e),i=t?TN(e,t,n):Md(e);if(!i)return{language:e.language,binaryLabel:r,installed:!1,runnable:!1,resolvedBinary:null,installUrl:e.installUrl,...t&&DN(e,t)?{note:"project-local indexer available only with --trust-project-tools"}:{}};if(e.indexerBinary!=="scip-dotnet")return{language:e.language,binaryLabel:r,installed:!0,runnable:!0,resolvedBinary:i};let o=FN(i);return{language:e.language,binaryLabel:r,installed:!0,runnable:o.runnable,resolvedBinary:i,installUrl:e.installUrl,note:o.note}}function FN(e){if(Nd(e,process.env))return{runnable:!0};let t=Wb(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=Kb(process.env);return{runnable:!1,note:n.length>0?`.NET 9 runtime still unavailable after checking ${n.join(", ")}`:"binary is present, but scip-dotnet still needs a .NET 9 runtime"}}function Wb(e,t){for(let n of Kb(t))if(Nd(e,{...t,DOTNET_ROOT:n}))return n;return null}function Kb(e){let t=[],n=e.DOTNET_ROOT;if(n&&uc(n)&&t.push(n),CN()==="darwin"&&jb("brew"))try{let r=Gb("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e,timeout:1e4,killSignal:"SIGKILL"}).toString().trim(),i=$o(r,"libexec");uc(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function Nd(e,t){try{return Gb(e,["--version"],{stdio:"pipe",env:t,timeout:1e4,killSignal:"SIGKILL"}),!0}catch{return!1}}function dc(e){let t=zb(qb,e),n=t.runnable;return n?{available:!0,dependencyAvailable:n,resolvedBinary:t.resolvedBinary??void 0,note:"rust-analyzer semantic reference queries are enabled."}:{available:!1,dependencyAvailable:n,resolvedBinary:t.resolvedBinary??void 0,reason:"rust-analyzer is not runnable; Rust semantic checks will use SCIP/source evidence only."}}import{existsSync as aO,mkdtempSync as US,rmSync as Wd}from"fs";import{tmpdir as Yd}from"os";import{join as Kd}from"path";import{fileURLToPath as Zo,pathToFileURL as cO}from"url";import{SHARE_ENV as lO,Worker as uO}from"worker_threads";function Rt(e){try{return process.kill(e,0),!0}catch(t){return typeof t=="object"&&t!==null&&"code"in t&&t.code==="EPERM"}}import{execFileSync as AN}from"child_process";import{platform as LN}from"os";var _N=new Set(["aix","android","darwin","freebsd","haiku","linux","openbsd","sunos","win32","cygwin","netbsd"]);function Ct(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.version!==1||typeof t.pid!="number"||!Number.isSafeInteger(t.pid)||t.pid<=0||typeof t.platform!="string"||!_N.has(t.platform)||typeof t.startToken!="string"||t.startToken.trim()===""?null:{version:1,pid:t.pid,platform:t.platform,startToken:t.startToken}}function Ke(e,t){return e.version===t.version&&e.pid===t.pid&&e.platform===t.platform&&e.startToken===t.startToken}var MN=1e3,Jb=16*1024;function tt(e,t=BN){if(!Number.isSafeInteger(e)||e<=0)return null;try{let n=NN(e,t);return n?{version:1,pid:e,platform:t.platform,startToken:n}:null}catch{return null}}function NN(e,t){if(t.platform==="linux"||t.platform==="android")return ON(t.readFile(`/proc/${e}/stat`));if(t.platform==="win32"){let n=`([DateTimeOffset](Get-Process -Id ${e} -ErrorAction Stop).StartTime).ToUnixTimeMilliseconds()`;return Yb(t.run("powershell.exe",["-NoProfile","-NonInteractive","-Command",n]))}return t.platform==="darwin"||t.platform==="freebsd"||t.platform==="openbsd"||t.platform==="netbsd"?Yb(t.run("ps",["-p",String(e),"-o","lstart="])):null}function ON(e){let t=e.lastIndexOf(")");if(t<0)return null;let r=e.slice(t+1).trim().split(/\s+/)[19];return r&&/^\d+$/.test(r)?r:null}function Yb(e){let t=e.trim();return t===""?null:t}var BN={platform:LN(),readFile(e){return Bu(e,{maxBytes:Jb,inputKind:"process identity pseudo-file"})},run(e,t){return AN(e,[...t],{encoding:"utf8",timeout:MN,maxBuffer:Jb,env:{...process.env,LC_ALL:"C",LANG:"C"},stdio:["ignore","pipe","ignore"]})}};function tr(e,t,n=new Set){let r=new Map;for(let i of e)n.has(i.symbolId)||r.set(i.symbolId,t.get(i.symbolId)??[]);return r}function Br(e,t,n){let r=er(process.env.SCIP_RUST_SEMANTIC_BATCH_TIMEOUT_MS)??0;if(r>0)return r;let i=Math.max(1,Math.ceil(e/Math.max(1,n)));return Math.max(12e4,3e4+i*t)}import{spawn as B0}from"child_process";import{createHash as j0,randomUUID as $0}from"crypto";import{existsSync as DS,realpathSync as H0,rmSync as G0}from"fs";import{tmpdir as q0}from"os";import{resolve as Ni}from"path";function Ae(){return performance.now()}function Tn(e){return Array.isArray(e)?`[${e.map(Tn).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Tn(n)}`).join(",")}}`:JSON.stringify(e)}import{createHash as i0,randomUUID as aS}from"crypto";import{existsSync as Ai,lstatSync as Vo,readdirSync as _i,renameSync as cS,rmSync as rr}from"fs";import{basename as Od,dirname as o0,join as De}from"path";import{randomUUID as KN}from"crypto";import{closeSync as JN,existsSync as YN,fsyncSync as XN,linkSync as QN,mkdirSync as ZN,openSync as e0,renameSync as t0,unlinkSync as n0,writeSync as r0}from"fs";import{dirname as Zb}from"path";import{closeSync as jN,existsSync as $N,fsyncSync as HN,mkdirSync as GN,openSync as qN}from"fs";import{dirname as Xb}from"path";function jr(e,t,n,r){let i=0;for(;i<t.length;){let o=n.writeFile(e,t,i,t.length-i);if(!Number.isSafeInteger(o)||o<=0||o>t.length-i)throw new Error(`${r} write did not make valid forward progress`);i+=o}}function Ti(e,t){if(t!=="win32")return!1;let n=e.code;return n==="EACCES"||n==="EBADF"||n==="EINVAL"||n==="EISDIR"||n==="EPERM"}var $r=Object.freeze({platform:process.platform,pathExists:e=>$N(e),makeDirectory:e=>GN(e,{recursive:!0}),openFile:(e,t,n)=>qN(e,t,n),syncFile:e=>HN(e),closeFile:e=>jN(e)});function dt(e,t=$r){let n=[],r=e;for(;!t.pathExists(r);){n.push(r);let o=Xb(r);if(o===r)throw new Error(`Cannot establish a durable directory path without an existing ancestor: ${e}`);r=o}let i="synced";for(let o of n.reverse())t.makeDirectory(o),i=Be(i,ce(Xb(o),t));return i}function ce(e,t=$r){let n;try{n=t.openFile(e,"r")}catch(r){if(Ti(r,t.platform))return"unsupported";throw r}try{t.syncFile(n)}catch(r){try{t.closeFile(n)}catch{}if(Ti(r,t.platform))return"unsupported";throw r}return t.closeFile(n),"synced"}function Be(...e){return e.every(t=>t==="not-requested")?"not-requested":e.includes("unsupported")?"unsupported":"synced"}import{chmodSync as UN,constants as VN,copyFileSync as zN}from"fs";import{dirname as WN}from"path";var Qb=Object.freeze({...$r,copyFile:(e,t)=>zN(e,t,VN.COPYFILE_FICLONE),chmodFile:(e,t)=>UN(e,t)});function Ho(e,t,n={}){let r=n.runtime??Qb,i=WN(t),o=dt(i,r);r.copyFile(e,t),n.mode!==void 0&&r.chmodFile(t,n.mode);let s=r.openFile(t,"r");try{r.syncFile(s)}finally{r.closeFile(s)}return Be(o,ce(i,r))}var eS=Object.freeze({platform:process.platform,randomToken:()=>KN(),pathExists:e=>YN(e),makeDirectory:e=>ZN(e,{recursive:!0}),openFile:(e,t,n)=>e0(e,t,n),writeFile:(e,t,n,r)=>r0(e,t,n,r),syncFile:e=>XN(e),closeFile:e=>JN(e),renameFile:(e,t)=>t0(e,t),linkFile:(e,t)=>QN(e,t),removeFile:e=>n0(e)});function Go(e,t,n={}){let r=n.durability??"visibility",i=n.runtime??eS,o=Zb(e),s=r==="durable"?dt(o,i):(i.makeDirectory(o),"not-requested"),a=`${e}.tmp-${i.randomToken()}`,c=typeof t=="string"?Buffer.from(t):t,l,u=!1;try{l=i.openFile(a,"wx",n.mode??384),u=!0,jr(l,c,i,"atomic file"),r==="durable"&&i.syncFile(l),i.closeFile(l),l=void 0,i.renameFile(a,e),u=!1;let d=r==="durable"?Be(s,ce(o,i)):"not-requested";return tS(r,d)}finally{if(l!==void 0)try{i.closeFile(l)}catch{}if(u)try{i.removeFile(a)}catch{}}}function qo(e,t,n={}){let r=n.durability??"visibility",i=n.runtime??eS;if(!i.linkFile)throw new Error("Exclusive atomic file publication requires hard-link support.");let o=Zb(e),s=r==="durable"?dt(o,i):(i.makeDirectory(o),"not-requested"),a=`${e}.tmp-${i.randomToken()}`,c=typeof t=="string"?Buffer.from(t):t,l,u=!1;try{l=i.openFile(a,"wx",n.mode??384),u=!0,jr(l,c,i,"exclusive atomic file"),r==="durable"&&i.syncFile(l),i.closeFile(l),l=void 0,i.linkFile(a,e);let d=r==="durable"?ce(o,i):"not-requested";i.removeFile(a),u=!1;let m=r==="durable"?Be(s,d,ce(o,i)):"not-requested";return tS(r,m)}finally{if(l!==void 0)try{i.closeFile(l)}catch{}if(u)try{i.removeFile(a)}catch{}}}function tS(e,t){return{requestedDurability:e,achievedDurability:e==="visibility"?"visibility":t==="synced"?"directory-durable":"file-flushed",directorySync:t}}function nr(e,t,n={}){Go(e,nS(t,n),{durability:"visibility",runtime:n.runtime})}function vt(e,t,n={}){return Go(e,nS(t,n),{durability:"durable",runtime:n.runtime})}function nS(e,t){let n=JSON.stringify(e,null,t.spacing);return t.trailingNewline?`${n}
|
|
322
|
+
`:n}var ir=1,s0=Object.freeze({maxItems:1024,maxBytes:512*1024*1024,maxItemBytes:64*1024*1024,maxBatch:16,claimLeaseMs:5*6e4,responseRetentionMs:10*6e4,deadLetterRetentionMs:1440*6e4,temporaryRetentionMs:6e4,cleanupBatch:64}),Fi=class extends Error{constructor(n,r,i,o){let s=n==="item-too-large"?`request is ${o} bytes; per-item limit is ${i.maxItemBytes}`:n==="item-capacity"?`mailbox has ${r.totalItems} retained items; limit is ${i.maxItems}`:n==="byte-capacity"?`mailbox retains ${r.totalBytes} bytes and the request adds ${o}; limit is ${i.maxBytes}`:"another writer held the admission coordinator through the bounded wait";super(`Mailbox backpressure: ${s}. Retry after the service drains or expires retained work.`);this.code=n;this.status=r;this.limits=i;this.attemptedBytes=o;this.name="MailboxBackpressureError"}code;status;limits;attemptedBytes},a0=".owner.json",c0={isProcessAlive:()=>!0,readProcessIdentity:()=>null};function mc(e){return{rootDir:e,pendingDir:De(e,"pending"),inflightDir:De(e,"inflight"),responseDir:De(e,"responses"),deadLetterDir:De(e,"dead-letter"),legacyRequestDir:De(e,"requests")}}function l0(e={}){let t={...s0,...e};for(let[n,r]of Object.entries(t))if(!Number.isFinite(r)||r<=0||!Number.isInteger(r))throw new Error(`Mailbox limit ${n} must be a positive integer.`);return t}function lS(e){let t=[e.pendingDir,e.inflightDir,e.responseDir,e.deadLetterDir,e.legacyRequestDir].map(n=>dt(n));return Be(...t)}function Li(e,t){return i0("sha256").update(Tn({namespace:e,payload:t})).digest("hex")}function Hr(e){if(!/^[a-f0-9]{64}$/.test(e))throw new Error("Mailbox operation keys must be lowercase SHA-256 identities.");return`op-${e}`}function fc(e,t,n={}){let r=l0(n.limits),i=n.nowMs??Date.now(),o=lS(e);return y0(t),d0(e,r,n.admissionLockTimeoutMs??2e3,n.monotonicNow??Ae,()=>{u0(e,i,r);let s=De(e.pendingDir,`${t.id}.json`),a=De(e.responseDir,`${t.id}.json`),c=rS(e,t.id);if(c){let m=iS(c,t.operationKey,t.id);return{disposition:"duplicate",requestId:t.id,responsePath:a,authoritativeDeadlineAtMs:m.deadlineAtMs??t.deadlineAtMs}}let l=`${JSON.stringify(t)}
|
|
323
|
+
`,u=Buffer.byteLength(l),d=uS(e);if(u>r.maxItemBytes)throw new Fi("item-too-large",d,r,u);if(d.totalItems+1>r.maxItems)throw new Fi("item-capacity",d,r,u);if(d.totalBytes+u>r.maxBytes)throw new Fi("byte-capacity",d,r,u);n.onBeforePublish?.();try{let m=qo(s,l,{durability:"durable"}),f=Be(o,m.directorySync);return{disposition:"accepted",requestId:t.id,responsePath:a,authoritativeDeadlineAtMs:t.deadlineAtMs,achievedDurability:f==="synced"?"directory-durable":"file-flushed",directorySync:f}}catch(m){if(m.code!=="EEXIST")throw m;let f=rS(e,t.id);if(!f)throw m;let p=iS(f,t.operationKey,t.id);return{disposition:"duplicate",requestId:t.id,responsePath:a,authoritativeDeadlineAtMs:p.deadlineAtMs??t.deadlineAtMs}}})}function u0(e,t,n,r=c0){let i={reclaimed:0,completedClaimsRemoved:0,responsesRemoved:0,deadLettersRemoved:0,temporaryFilesRemoved:0},o=n.cleanupBatch;for(let s of jd(e.inflightDir)){if(o<=0)break;let a=De(e.responseDir,`${s.requestId}.json`);if(Ai(a)){rr(s.path,{force:!0}),i.completedClaimsRemoved++,o--;continue}if(s.claimExpiresAtMs>t||g0(e,s.ownerId,r)!=="dead")continue;let c=De(e.pendingDir,s.originalFile);try{cS(s.path,c),i.reclaimed++}catch(l){if(l.code!=="EEXIST")throw l;rr(s.path,{force:!0})}ce(o0(s.path)),ce(e.pendingDir),o--}o=oS(e.responseDir,o,(s,a)=>a+n.responseRetentionMs,t,()=>{i.responsesRemoved++}),o=oS(e.deadLetterDir,o,(s,a)=>a+n.deadLetterRetentionMs,t,()=>{i.deadLettersRemoved++});for(let s of[e.pendingDir,e.inflightDir,e.responseDir,e.deadLetterDir,e.legacyRequestDir]){if(o<=0)break;for(let a of dS(s)){if(o<=0)break;Od(a).includes(".tmp-")&&(Vo(a).mtimeMs+n.temporaryRetentionMs>t||(rr(a,{force:!0}),i.temporaryFilesRemoved++,o--))}}return b0(e.inflightDir),i}function uS(e){lS(e);let t=[...Uo(e.pendingDir).map(c=>({path:c,pending:!0})),...Uo(e.legacyRequestDir).map(c=>({path:c,pending:!0}))],n=jd(e.inflightDir).map(c=>({path:c.path,pending:!1})),r=Uo(e.responseDir).map(c=>({path:c,pending:!1})),i=Uo(e.deadLetterDir).map(c=>({path:c,pending:!1})),o=[...t,...n,...r,...i],s=0,a;for(let c of t){let l=$d(c.path);if(!l){s++;continue}let u=l.enqueuedAtMs??Vo(c.path).mtimeMs;a=a===void 0?u:Math.min(a,u)}return{pending:t.length,inflight:n.length,responses:r.length,deadLetters:i.length,invalid:s,totalItems:o.length,totalBytes:o.reduce((c,l)=>c+S0(l.path),0),...a===void 0?{}:{oldestPendingAt:new Date(a).toISOString()}}}function d0(e,t,n,r,i){let o=De(e.rootDir,".admission.lock"),s=`${process.pid}-${aS()}`,a=r()+Math.max(0,n);for(;!m0(e.rootDir,o,s);){if(f0(o),r()>=a)throw new Fi("admission-busy",uS(e),t,0);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,5)}try{return i()}finally{try{Bd(o).ownerToken===s&&(rr(o,{recursive:!0,force:!0}),ce(e.rootDir))}catch{}}}function m0(e,t,n){let r=`${JSON.stringify({ownerToken:n,pid:process.pid,acquiredAtMs:Date.now()})}
|
|
324
|
+
`;try{return qo(t,r,{durability:"durable"}),!0}catch(i){if(i.code==="EEXIST")return!1;try{Bd(t).ownerToken===n&&(rr(t,{force:!0}),ce(e))}catch{}throw i}}function f0(e){let t=null;try{let r=Bd(e);typeof r.ownerToken=="string"&&Number.isSafeInteger(r.pid)&&Number(r.pid)>0&&(t=Number(r.pid))}catch{}if(t===null||p0(t))return;let n=`${e}.stale-${aS()}`;try{cS(e,n)}catch(r){let i=r.code;if(i==="ENOENT"||i==="EEXIST")return;throw r}rr(n,{recursive:!0,force:!0})}function Bd(e){try{return JSON.parse(O(e,"mailbox lock record"))}catch(t){if(t.code!=="EISDIR"&&!(t instanceof Qt&&t.reason==="not-regular"))throw t;return JSON.parse(O(De(e,"owner.json"),"mailbox lock owner record"))}}function p0(e){try{return process.kill(e,0),!0}catch(t){let n=t.code;return n==="EPERM"||n!=="ESRCH"}}function g0(e,t,n){let r=h0(De(e.inflightDir,mS(t),a0));if(!r)return"unknown";if(!n.isProcessAlive(r.pid))return"dead";if(!r.processIdentity)return"live";let i=n.readProcessIdentity(r.pid);return i?Ke(r.processIdentity,i)?"live":"dead":"unknown"}function h0(e){try{let t=JSON.parse(O(e,"mailbox owner record"));if(t.version!==1||typeof t.ownerId!="string"||!t.ownerId||typeof t.pid!="number"||!Number.isSafeInteger(t.pid)||t.pid<=0)return null;let n=t.processIdentity===void 0?null:Ct(t.processIdentity);return t.processIdentity!==void 0&&(!n||n.pid!==t.pid)?null:{version:1,ownerId:t.ownerId,pid:t.pid,...n?{processIdentity:n}:{}}}catch{return null}}function rS(e,t){for(let n of[De(e.pendingDir,`${t}.json`),De(e.legacyRequestDir,`${t}.json`),De(e.responseDir,`${t}.json`)])if(Ai(n))return n;for(let n of jd(e.inflightDir))if(n.requestId===t)return n.path;return null}function iS(e,t,n){let r=$d(e);if(!r||r.operationKey!==t)throw new Error(`Mailbox operation ${n} conflicts with an existing retained record.`);return r}function y0(e){if(e.mailboxVersion!==ir||e.id!==Hr(e.operationKey)||!e.clientId.trim()||!Number.isFinite(e.enqueuedAtMs)||!Number.isFinite(e.deadlineAtMs)||e.deadlineAtMs<e.enqueuedAtMs)throw new Error("Mailbox request has an invalid lifecycle identity.")}function jd(e){if(!Ai(e))return[];let t=[];for(let n of _i(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let r=sS(n.name);if(r===null)continue;let i=De(e,n.name);for(let o of _i(i,{withFileTypes:!0})){if(!o.isFile()||!o.name.endsWith(".claim"))continue;let s=/^(.*)\.(\d+)\.claim$/.exec(o.name);if(!s)continue;let a=sS(s[1]),c=Number(s[2]);if(a===null||Od(a)!==a||!a.endsWith(".json")||!Number.isSafeInteger(c))continue;let l=De(i,o.name),u=$d(l)??{id:Od(a,".json")},d=Vo(l);t.push({requestId:u.id,ownerId:r,path:l,originalFile:a,claimedAtMs:d.mtimeMs,claimExpiresAtMs:c,byteLength:d.size,...u.operationKey?{operationKey:u.operationKey}:{},...u.clientId?{clientId:u.clientId}:{},...u.enqueuedAtMs===void 0?{}:{enqueuedAtMs:u.enqueuedAtMs},...u.deadlineAtMs===void 0?{}:{deadlineAtMs:u.deadlineAtMs},legacy:u.operationKey===void 0})}}return t.sort((n,r)=>n.claimedAtMs-r.claimedAtMs||n.path.localeCompare(r.path))}function $d(e){try{let t=JSON.parse(O(e,"mailbox record"));return typeof t.id!="string"||!t.id?null:{id:t.id,...typeof t.operationKey=="string"?{operationKey:t.operationKey}:{},...typeof t.clientId=="string"?{clientId:t.clientId}:{},...typeof t.enqueuedAtMs=="number"?{enqueuedAtMs:t.enqueuedAtMs}:{},...typeof t.deadlineAtMs=="number"?{deadlineAtMs:t.deadlineAtMs}:{}}}catch{return null}}function oS(e,t,n,r,i){for(let o of Uo(e)){if(t<=0)break;let s=Vo(o);n(o,s.mtimeMs)>r||(rr(o,{force:!0}),i(),t--)}return t}function Uo(e){return Ai(e)?_i(e,{withFileTypes:!0}).filter(t=>t.isFile()).map(t=>De(e,t.name)).sort():[]}function dS(e){if(!Ai(e))return[];let t=[];for(let n of _i(e,{withFileTypes:!0})){let r=De(e,n.name);n.isFile()?t.push(r):n.isDirectory()&&t.push(...dS(r))}return t.sort()}function b0(e){if(Ai(e))for(let t of _i(e,{withFileTypes:!0})){if(!t.isDirectory())continue;let n=De(e,t.name);_i(n).some(r=>r.endsWith(".claim"))||rr(n,{recursive:!0,force:!0})}}function S0(e){try{return Vo(e).size}catch{return 0}}function mS(e){return Buffer.from(e,"utf8").toString("base64url")}function sS(e){try{let t=Buffer.from(e,"base64url").toString("utf8");return mS(t)===e?t:null}catch{return null}}import{execFileSync as D0}from"child_process";import{existsSync as x0}from"fs";import{deserializeSCIP as R0,SymbolRole as C0}from"@c4312/scip";import{realpathSync as Jie}from"fs";import{basename as Xie,dirname as Qie,join as Zie,relative as eoe,sep as toe}from"path";import{fileURLToPath as roe,pathToFileURL as ioe}from"url";function pc(e){let t=new Map;for(let n of e)t.set(`${n.file}\0${n.line}\0${n.column}`,n);return[...t.values()].sort((n,r)=>{let i=n.file.localeCompare(r.file);return i!==0?i:n.line!==r.line?n.line-r.line:n.column-r.column})}var Hd=new WeakMap,v0="SCIP_RUST_SCIP_OCCURRENCE_REFERENCE_MODE";function fS(e,t){let n=new Map,r=gc(),i=t.filter(s=>hS(s,r));if(i.length===0)return n;let o=yS(e);if(!o)return n;for(let s of i){let a=gS(o,s);a!==null&&n.set(s.symbolId,a)}return n}function pS(e,t){if(!hS(t,gc()))return null;let n=yS(e);return n?gS(n,t):null}function gS(e,t){return e.referencesBySymbol.get(t.symbol)??[]}function hS(e,t="safe"){if(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||$e(e.symbol)||/impl#\[[^\]]+\]\[Default\]default\(\)\.$/.test(e.symbol))return!1;if(t==="all")return!0;let n=be(e.symbol);if(n==="method")return!0;if(n!=="term")return!1;let r=Te(e.symbol);return"kind"in r?!1:!I0(r)}function I0(e){for(let t=0;t<e.descriptors.length-1;t+=1)if(e.descriptors[t]?.suffix==="type")return!0;return!1}function yS(e){if(Hd.has(e))return Hd.get(e)??null;let t=w0(e);return Hd.set(e,t),t}function w0(e){if(!e.generation.indexPath||!x0(e.generation.indexPath))return null;try{let t=R0(Se(e.generation.indexPath,{inputKind:"SCIP occurrence-reference index",maxBytes:Me})),n=new Map;for(let r of t.documents??[]){let i=r.relativePath;if(!(!i||e.isIgnored(i)))for(let o of r.occurrences??[]){if(!o.symbol||(o.symbolRoles&C0.Definition)!==0)continue;let s=E0(i,o.range);if(!s)continue;let a=n.get(o.symbol)??[];a.push(s),n.set(o.symbol,a)}}for(let[r,i]of n)n.set(r,pc(i));return{referencesBySymbol:n}}catch{return null}}function E0(e,t){if(t.length<3)return null;let n=t[0],r=t[1];return!Number.isInteger(n)||!Number.isInteger(r)?null:{file:e,line:n,column:r}}function gc(){return process.env[v0]==="all"?"all":"safe"}var bS=new Map;function Gd(e){let n=dc(e).resolvedBinary??null;return{engine:"rust-analyzer",resolvedBinary:n,version:n?P0(e,n):"unavailable"}}function Gr(e){return{...Gd(e),scipOccurrenceReferenceMode:gc()}}function P0(e,t){let n=`${e}\0${t}`,r=bS.get(n);if(r)return r;let i;try{i=D0(t,["--version"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim()}catch{i="unknown"}return bS.set(n,i),i}import{createHash as k0}from"crypto";var T0=new Set(["Cargo.lock","Cargo.toml","rust-project.json","rust-toolchain","rust-toolchain.toml"]);function SS(e){let t=$u(e,{includePath:F0});return k0("sha256").update(JSON.stringify(t)).digest("hex")}function F0(e){let t=e.replaceAll("\\","/"),n=t.split("/").at(-1)??t;return t.endsWith(".rs")||T0.has(n)?!0:t===".cargo/config"||t===".cargo/config.toml"||t.endsWith("/.cargo/config")||t.endsWith("/.cargo/config.toml")}import{createHash as _0}from"crypto";import{resolve as A0}from"path";var Mi=3;function Ud(e){return _0("sha256").update(Tn({kind:"scip-query-durable-rust-mailbox",protocolVersion:Mi,sessionDir:A0(e)})).digest("hex")}function CS(e,t){return V(e)?e.protocolVersion!==Mi?RS(e.protocolVersion===void 0?"helper wrote a prior uncorrelated response protocol":`helper wrote unsupported response protocol ${String(e.protocolVersion)}`):e.mailboxVersion!==ir||e.id!==t.requestId||e.operationKey!==t.operationKey||e.sessionIdentity!==t.sessionIdentity||e.deadlineAtMs!==t.deadlineAtMs?RS("helper wrote an incompatible response identity"):typeof e.completedAtMs!="number"||!Number.isFinite(e.completedAtMs)||e.completedAtMs>t.deadlineAtMs||t.nowMs>t.deadlineAtMs?{ok:!1,code:"expired-request",error:"helper response arrived after the durable request deadline"}:e.ok===!1?typeof e.error!="string"||!O0(e.errorCode)?qd("helper wrote an invalid rejection response"):{ok:!1,code:e.errorCode,error:e.error}:e.ok!==!0||e.session!=="created"&&e.session!=="reused"&&e.session!=="invalidated"||!L0(e.response,t.requestKind)?qd("helper wrote an invalid success response"):{ok:!0,session:e.session,response:e.response}:qd("helper wrote an invalid response object")}function L0(e,t){return!V(e)||typeof e.available!="boolean"||e.available===!1&&(typeof e.reason!="string"||e.reason.length===0)||e.available===!0&&e.reason!==void 0?!1:t==="import-definitions"?Array.isArray(e.sourcePaths)&&e.sourcePaths.every(n=>Array.isArray(n)&&n.length===2&&typeof n[0]=="string"&&(n[1]===null||typeof n[1]=="string")):xS(e.references,M0)&&(e.incompleteReferenceSymbolIds===void 0||Array.isArray(e.incompleteReferenceSymbolIds)&&e.incompleteReferenceSymbolIds.every(n=>Number.isSafeInteger(n)))&&(e.callees===void 0||xS(e.callees,N0))&&(e.signatures===void 0||Array.isArray(e.signatures)&&e.signatures.every(n=>Array.isArray(n)&&n.length===2&&Number.isSafeInteger(n[0])&&(n[1]===null||typeof n[1]=="string")))}function xS(e,t){return Array.isArray(e)&&e.every(n=>Array.isArray(n)&&n.length===2&&Number.isSafeInteger(n[0])&&Array.isArray(n[1])&&n[1].every(t))}function M0(e){return V(e)&&typeof e.file=="string"&&B(e.line)&&B(e.column)}function N0(e){return V(e)&&typeof e.symbol=="string"&&typeof e.file=="string"&&B(e.line)}function O0(e){return e==="unsupported-protocol"||e==="malformed-request"||e==="expired-request"||e==="handler-error"}function qd(e){return{ok:!1,code:"malformed-response",error:e}}function RS(e){return{ok:!1,code:"incompatible-response",error:e}}var U0=5e3,PS=10,V0=3e4;function vS(e,t,n,r=_S){let i=r.engineIdentity(e),o={protocolVersion:Mi,projectRoot:r.canonicalProjectRoot(e),projectFingerprint:r.projectFingerprint(e),engine:{engine:i.engine,resolvedBinary:i.resolvedBinary,version:i.version},workerFingerprint:r.fileFingerprint(t),environment:kS(r.environment())};return{key:AS(Tn(o)),...o}}function zo(e,t,n,r){if(e.protocolVersion!==Mi||!n(e.pid))return!1;if(!e.processIdentity)return!0;let i=r?.(e.pid);return i!=null&&Ke(e.processIdentity,i)}function Vd(e,t,n){let r;try{r=Zt(t,{maxBytes:He,inputKind:"Rust semantic engine artifact"})}catch{r="missing"}let i=AS(Tn({projectRoot:Ni(e),serverPath:Ni(t),serverFingerprint:r})).slice(0,20);return Ni(n,`scip-query-rust-session-${i}`)}function IS(e){let t=e===void 0?Number.NaN:Number(e);return Number.isInteger(t)&&t>=0?t:0}function kS(e){return Object.fromEntries(Object.entries(e).filter(([t])=>FS(t)).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,n??null]))}function TS(e,t){let n=t.runtime??X0,r=t.identityRuntime??_S,i=Vd(e,t.serverPath,t.tempRoot??q0()),o=!1,s=(a,c)=>{if(o)throw new Error("Durable Rust semantic session was already disposed.");return W0(i,t.serverPath,t.semanticWorkerPath,a,c,n,t.mailboxLimits)};return{requestSemantic(a,c){let l=vS(e,t.semanticWorkerPath,a,r),{readinessDeadlineMs:u,...d}=a;return s({kind:"semantic",identityKey:l.key,workerEnvironment:ES(),request:{...d,referenceRetryTimeoutMs:z0(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,a.referenceRetryTimeoutMs),settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:IS(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},requestImportDefinitions(a,c){let l=vS(e,t.semanticWorkerPath,a,r),{readinessDeadlineMs:u,...d}=a;return s({kind:"import-definitions",identityKey:l.key,workerEnvironment:ES(),request:{...d,settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:IS(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},shutdown(){o=!0}}}function z0(e,t){return t!==void 0?t:e===void 0?V0:void 0}function W0(e,t,n,r,i,o,s={}){let a=o.now(),c=a+i,l=(o.monotonicNow??Ae)(),u=l+i,d=Li("rust-semantic-v3",r),m=Hr(d),f=mc(e),p=Ud(e),g=fc(f,{mailboxVersion:ir,protocolVersion:Mi,id:m,operationKey:d,clientId:o.randomId(),enqueuedAtMs:a,deadlineAtMs:c,sessionIdentity:p,request:r},{nowMs:a,limits:s});for(wS(e,t,n,u,o);(o.monotonicNow??Ae)()<=u;){if(DS(g.responsePath)){let h=K0(J(g.responsePath,{maxBytes:s.maxItemBytes??He,inputKind:"durable Rust semantic mailbox response"}),{requestId:m,operationKey:d,sessionIdentity:p,deadlineAtMs:g.authoritativeDeadlineAtMs,requestKind:r.kind,nowMs:o.now()});if(!h.ok)throw new Error(h.error);return W()&&zn({type:"span",name:"rust.semantic.durable-session.request",durationMs:(o.monotonicNow??Ae)()-l,ok:!0,session:h.session,kind:r.kind}),h.response}let y=Wo(e);(!y||!zo(y,o.now(),o.isProcessAlive,o.readProcessIdentity))&&wS(e,t,n,u,o),o.sleep(PS)}throw new Error(`Durable Rust semantic session timed out after ${(i/1e3).toFixed(0)}s.`)}function wS(e,t,n,r,i){let o=Wo(e);if(o&&zo(o,i.now(),i.isProcessAlive,i.readProcessIdentity))return;G0(Ni(e,"server.json"),{force:!0}),i.spawnServer(t,e,n);let s=i.monotonicNow??Ae,a=Math.min(r,s()+U0);for(;s()<=a;){let c=Wo(e);if(c&&zo(c,i.now(),i.isProcessAlive,i.readProcessIdentity))return;i.sleep(PS)}throw new Error("Durable Rust semantic session helper did not become ready within 5s.")}function Wo(e){try{let t=JSON.parse(J(Ni(e,"server.json"),{maxBytes:Ie,inputKind:"durable Rust session state"}));if(typeof t.protocolVersion!="number"||t.sessionIdentity!==void 0&&(typeof t.sessionIdentity!="string"||t.sessionIdentity!==Ud(e))||typeof t.pid!="number"||typeof t.heartbeatAtMs!="number"||t.busyUntilMs!==void 0&&typeof t.busyUntilMs!="number"||t.mailbox!==void 0&&!J0(t.mailbox))return null;let n=t.processIdentity===void 0?null:Ct(t.processIdentity);return t.processIdentity!==void 0&&(!n||n.pid!==t.pid)?null:{protocolVersion:t.protocolVersion,...t.sessionIdentity===void 0?{}:{sessionIdentity:t.sessionIdentity},pid:t.pid,...n?{processIdentity:n}:{},heartbeatAtMs:t.heartbeatAtMs,...t.busyUntilMs===void 0?{}:{busyUntilMs:t.busyUntilMs},...t.mailbox===void 0?{}:{mailbox:t.mailbox}}}catch{return null}}function K0(e,t){try{return CS(JSON.parse(e),t)}catch(n){return{ok:!1,code:"malformed-response",error:`helper wrote malformed JSON: ${n instanceof Error?n.message:String(n)}`}}}function J0(e){if(!e||typeof e!="object")return!1;let t=e;return B(t.pending)&&B(t.inflight)&&B(t.responses)&&B(t.deadLetters)&&B(t.invalid)&&B(t.totalItems)&&typeof t.totalBytes=="number"&&Number.isFinite(t.totalBytes)&&t.totalBytes>=0&&(t.oldestPendingAt===void 0||Number.isFinite(Date.parse(t.oldestPendingAt)))}function ES(){return Object.fromEntries(Object.entries(process.env).filter(([e])=>Y0(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t??null]))}function FS(e){return e==="HOME"||e==="PATH"||e.startsWith("CARGO_")||e.startsWith("RA_")||e.startsWith("RUST")}function Y0(e){return FS(e)||e.startsWith("SCIP_RUST_")||e==="SCIP_QUERY_PROFILE"||e==="SCIP_QUERY_PROFILE_CACHE_STATE"||e==="SCIP_QUERY_PROFILE_COMMAND"||e==="SCIP_QUERY_PROFILE_OUT"||e==="SCIP_QUERY_PROFILE_RUN_ID"||e==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY"||e==="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY_KIND"||e==="SCIP_QUERY_PROFILE_MIN_MS"}var _S={canonicalProjectRoot(e){try{return H0(e)}catch{return Ni(e)}},projectFingerprint(e){return SS(e)},engineIdentity:Gd,fileFingerprint(e){return Zt(e,{maxBytes:He,inputKind:"Rust semantic engine artifact"})},environment(){return kS(process.env)}},X0={now:Date.now,monotonicNow:Ae,randomId:$0,isProcessAlive:Rt,readProcessIdentity:tt,spawnServer(e,t,n){if(!DS(e))throw new Error(`Durable Rust semantic session helper was not found at ${e}. Run npm run build first.`);B0(process.execPath,[e,t,n],{detached:!0,stdio:"ignore"}).unref()},sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)}};function AS(e){return j0("sha256").update(e).digest("hex")}import{randomUUID as Yoe}from"crypto";import{readdirSync as tO,rmSync as Qoe,writeFileSync as Zoe}from"fs";import{join as nO}from"path";import{execFileSync as NS}from"child_process";import{platform as Q0}from"os";var OS=1e3,BS=2*1024*1024,Z0=25;function jS(e,t,n=GS){let r=n.readIdentity(e),i=new Map;return r&&i.set(e,r),{rootPid:e,rootIdentity:r,ownsProcessGroup:t,knownMembers:i}}async function hc(e,t,n=GS){if(!e.rootIdentity){let c=await Ko(e,t.gracefulMs+t.forceMs,n);return{reaped:c,reason:c?"terminated":"identity-unavailable",detail:c?void 0:`Could not establish the birth identity of process ${e.rootPid}.`}}let r=$S(e,n);if(r==="mismatch")return{reaped:!1,reason:"identity-mismatch",detail:`Process ${e.rootPid} no longer has the identity owned by this runner.`};if(r==="exited"&&!HS(e,n))return{reaped:!0,reason:"terminated"};if(n.platform==="win32"){try{n.terminateWindowsTree(e.rootPid)}catch(l){let u=await Ko(e,t.forceMs,n);return{reaped:u,reason:u?"terminated":"signal-failed",detail:u?void 0:zd(l)}}let c=await Ko(e,t.forceMs,n);return{reaped:c,reason:c?"terminated":"deadline"}}let i=LS(e,"SIGTERM",n);if(await Ko(e,t.gracefulMs,n))return{reaped:!0,reason:"terminated"};let s=LS(e,"SIGKILL",n);return await Ko(e,t.forceMs,n)?{reaped:!0,reason:"terminated"}:s?{reaped:!1,reason:s.reason,detail:s.detail}:i?{reaped:!1,reason:i.reason,detail:i.detail}:{reaped:!1,reason:"deadline",detail:`Process tree ${e.rootPid} did not exit before its termination deadline.`}}function $S(e,t){let n=t.readIdentity(e.rootPid);if(!n)return"exited";if(!e.rootIdentity||!Ke(e.rootIdentity,n))return"mismatch";e.knownMembers.set(e.rootPid,n);for(let r of t.listDescendantPids(e.rootPid)){let i=t.readIdentity(r);i&&e.knownMembers.set(r,i)}return"owned"}function LS(e,t,n){let r=$S(e,n);if(r==="mismatch")return{reason:"identity-mismatch",detail:`Process ${e.rootPid} changed identity before ${t}.`};if(r==="owned"&&e.ownsProcessGroup)try{return n.signal(-e.rootPid,t),null}catch(o){if(!MS(o))return{reason:"signal-failed",detail:zd(o)}}let i=null;for(let o of e.knownMembers.values()){let s=n.readIdentity(o.pid);if(!(!s||!Ke(o,s)))try{n.signal(o.pid,t)}catch(a){!MS(a)&&i===null&&(i=zd(a))}}return i===null?null:{reason:"signal-failed",detail:i}}async function Ko(e,t,n){let r=n.now()+t;for(;HS(e,n);){if(n.now()>=r)return!1;await n.sleep(Math.min(Z0,Math.max(1,r-n.now())))}return!0}function HS(e,t){if(!e.rootIdentity&&t.isProcessAlive(e.rootPid))return!0;for(let n of e.knownMembers.values()){let r=t.readIdentity(n.pid);if(r&&Ke(n,r))return!0}return!!(e.ownsProcessGroup&&t.isProcessGroupAlive(e.rootPid))}function eO(e){let t=NS("ps",["-axo","pid=,ppid="],{encoding:"utf8",timeout:OS,maxBuffer:BS,env:{...process.env,LC_ALL:"C",LANG:"C"},stdio:["ignore","pipe","ignore"]}),n=new Map;for(let s of t.split(/\r?\n/)){let a=/^\s*(\d+)\s+(\d+)\s*$/.exec(s);if(!a)continue;let c=Number(a[1]),l=Number(a[2]),u=n.get(l)??[];u.push(c),n.set(l,u)}let r=[],i=[...n.get(e)??[]],o=new Set;for(;i.length>0;){let s=i.pop();o.has(s)||(o.add(s),r.push(s),i.push(...n.get(s)??[]))}return r}function MS(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ESRCH"}function zd(e){return e instanceof Error?e.message:String(e)}var GS={platform:Q0(),now:Date.now,readIdentity:tt,isProcessAlive(e){try{return process.kill(e,0),!0}catch(t){return typeof t=="object"&&t!==null&&"code"in t&&t.code==="EPERM"}},isProcessGroupAlive(e){if(this.platform==="win32")return!1;try{return process.kill(-e,0),!0}catch(t){return typeof t=="object"&&t!==null&&"code"in t&&t.code==="EPERM"}},listDescendantPids(e){if(this.platform==="win32")return[];try{return eO(e)}catch{return[]}},signal(e,t){process.kill(e,t)},terminateWindowsTree(e){NS("taskkill.exe",["/PID",String(e),"/T","/F"],{timeout:OS,maxBuffer:BS,stdio:"ignore",windowsHide:!0})},async sleep(e){await new Promise(t=>setTimeout(t,e))}};var rO="rust-analyzer-owner-",iO=".json",oO=16*1024;async function qS(e,t){if(!e)return[];let n;try{n=tO(e)}catch{return[]}let r=n.filter(s=>s.startsWith(rO)&&s.endsWith(iO)).map(s=>nO(e,s)),i=[],o=[];for(let s of r){let a=sO(s);a?o.push(a):i.push({reaped:!1,reason:"identity-unavailable",detail:`Rust analyzer ownership record ${s} could not be validated.`})}return i.push(...await Promise.all(o.map(s=>hc(s,t)))),i}function sO(e){try{let t=J(e,{maxBytes:oO,inputKind:"rust-analyzer process ownership record"}),n=JSON.parse(t),r=Ct(n.rootIdentity);return n.version!==1||!r||typeof n.ownsProcessGroup!="boolean"?null:{rootPid:r.pid,rootIdentity:r,ownsProcessGroup:n.ownsProcessGroup,knownMembers:new Map([[r.pid,r]])}}catch{return null}}var VS=15e3,zS=8,KS=5e3,dO=64,mO=96,Xd=class{constructor(t,n,r={}){this.projectRoot=t;this.status=n;this.opts=r;this.requester=r.requester??gO(t,process.env.SCIP_RUST_SEMANTIC_DURABLE_SESSION)}projectRoot;status;opts;requester;referencesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:Yo(n),references:Xo(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!0});return{...Jo(r),resolvedBinary:n.resolvedBinary,references:tr(t,new Map(r.references),new Set(r.incompleteReferenceSymbolIds??[]))}}catch(r){return this.opts.fallbackReferenceResolver?.referencesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),references:Xo(t)}}}calleesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:Yo(n),callees:Qo(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!0});return{...Jo(r),resolvedBinary:n.resolvedBinary,callees:Jd(t,new Map(r.callees??[]))}}catch(r){return this.opts.fallbackCalleeResolver?.calleesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),callees:Qo(t)}}}referencesAndCalleesForDefinitions(t,n){let r=this.status(this.projectRoot);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:Yo(r),references:Xo(t),callees:Qo(n)};let i=[...t,...n];try{let o=this.requestSession(r.resolvedBinary,i,{includeReferences:t.length>0,includeCallees:n.length>0,referenceDefinitions:t,calleeDefinitions:n});return{...Jo(o),resolvedBinary:r.resolvedBinary,references:tr(t,new Map(o.references),new Set(o.incompleteReferenceSymbolIds??[])),callees:Jd(n,new Map(o.callees??[]))}}catch(o){return this.fallbackReferencesAndCallees(r,t,n,o)}}signaturesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:Yo(n),signatures:WS(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!1,includeSignatures:!0});return{...Jo(r),resolvedBinary:n.resolvedBinary,signatures:xO(t,new Map(r.signatures??[]))}}catch(r){return this.opts.fallbackSignatureResolver?.signaturesForDefinitions(t)??{available:!1,resolvedBinary:n.resolvedBinary,reason:r instanceof Error?r.message:String(r),signatures:WS(t)}}}importDefinitionsForFile(t,n){let r=this.status(this.projectRoot);if(n.length===0)return r.available?{available:!0,resolvedBinary:r.resolvedBinary,sourcePaths:new Map}:{available:!1,reason:r.reason,resolvedBinary:r.resolvedBinary,sourcePaths:new Map};if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:Yo(r),sourcePaths:new Map(n.map(i=>[i.id,null]))};try{let i=this.requestImportDefinitions(r.resolvedBinary,t,n);return{...Jo(i),resolvedBinary:r.resolvedBinary,sourcePaths:new Map(i.sourcePaths)}}catch(i){return{available:!1,resolvedBinary:r.resolvedBinary,reason:i instanceof Error?i.message:String(i),sourcePaths:new Map(n.map(o=>[o.id,null]))}}}dispose(){this.requester.shutdown()}requestSession(t,n,r){let i=yc(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,VS),o=bc(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),s=yc(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,zS),a=bc(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),c=r.referenceDefinitions?[...r.referenceDefinitions]:void 0,l=r.calleeDefinitions?[...r.calleeDefinitions]:void 0,u=r.signatureDefinitions?[...r.signatureDefinitions]:void 0,d=es(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,...r}),m={projectRoot:this.projectRoot,rustAnalyzerBinary:t,definitions:[...n],...c?{referenceDefinitions:c}:{},...l?{calleeDefinitions:l}:{},...u?{signatureDefinitions:u}:{},requestTimeoutMs:i,...r.includeReferences!==!1&&o>0?{referenceRetryTimeoutMs:o}:{},diagnosticsTimeoutMs:a,settleDelayMs:d,concurrency:s,includeReferences:r.includeReferences,includeCallees:r.includeCallees,includeSignatures:r.includeSignatures},f=RO(m);return D("rust.semantic.session.request",()=>this.requester.requestSemantic(m,Br(f,Qd(i,m.referenceRetryTimeoutMs),s)),()=>({definitions:n.length,operationDefinitions:f,referenceDefinitions:m.referenceDefinitions?.length,calleeDefinitions:m.calleeDefinitions?.length,signatureDefinitions:m.signatureDefinitions?.length,references:m.includeReferences!==!1,callees:m.includeCallees===!0,signatures:m.includeSignatures===!0,referenceRetryTimeoutMs:m.referenceRetryTimeoutMs}))}fallbackReferencesAndCallees(t,n,r,i){let o=n.length===0?{available:!0,resolvedBinary:t.resolvedBinary,references:Xo(n)}:this.opts.fallbackReferenceResolver?.referencesForDefinitions(n),s=r.length===0?{available:!0,resolvedBinary:t.resolvedBinary,callees:Qo(r)}:this.opts.fallbackCalleeResolver?.calleesForDefinitions(r);if(o&&s){let a={resolvedBinary:o.resolvedBinary??s.resolvedBinary??t.resolvedBinary,references:tr(n,o.references),callees:Jd(r,s.callees)};return o.available&&s.available?{available:!0,...a}:{available:!1,reason:(o.available?void 0:o.reason)??(s.available?void 0:s.reason)??"Rust semantic fallback was unavailable.",...a}}return{available:!1,resolvedBinary:t.resolvedBinary,reason:i instanceof Error?i.message:String(i),references:Xo(n),callees:Qo(r)}}requestImportDefinitions(t,n,r){let i=yc(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,VS),o=yc(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,zS),s=bc(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),a=bc(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,KS),c={projectRoot:this.projectRoot,rustAnalyzerBinary:t,file:n,positions:[...r],requestTimeoutMs:i,diagnosticsTimeoutMs:s,settleDelayMs:a,concurrency:o};return D("rust.semantic.import-definitions.session.request",()=>this.requester.requestImportDefinitions(c,Br(r.length,i,o)),()=>({file:n,positions:r.length}))}};function Jo(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function Yo(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function JS(e,t,n={}){return new Xd(e,t,n)}function es(e,t){let n=ZS(e);if(n!==null)return n;let r=t.includeReferences!==!1;return r&&t.includeCallees!==!0&&t.includeSignatures!==!0&&t.definitionCount<=dO||r&&t.includeCallees===!0&&t.includeSignatures!==!0&&t.definitionCount<=mO?0:KS}function YS(e){let t=e?.trim().toLowerCase(),n=t==="0"||t==="false"||t==="off"||t==="worker",r=t==="1"||t==="true"||t==="on"||t==="durable",i=t===void 0||t==="";return{transport:n||!i&&!r?"worker":"durable",source:i?"default":"environment",fallback:"worker",valid:i||n||r,optOut:"SCIP_RUST_SEMANTIC_DURABLE_SESSION=0"}}function fO(e){return YS(e).transport}function bse(e,t){let n=YS(t);if(n.transport==="worker")return{...n,state:"per-command"};let r=Zo(QS()),i=Vd(e,r,Yd()),o=Wo(i);return o?{...n,state:zo(o,Date.now(),Rt,tt)?"live":"stale",pid:o.pid,heartbeatAtMs:o.heartbeatAtMs,...o.busyUntilMs===void 0?{}:{busyUntilMs:o.busyUntilMs}}:{...n,state:"stopped"}}function pO(e,t){let n=null,r=!1,i=!1,o=!1,s=()=>n??=t(),a=()=>{i||(e.shutdown(),i=!0)},c=(u,d,m)=>{let f=SO(u);r=!0;try{a()}catch{}W()&&zn({type:"span",name:"rust.semantic.durable-session.request",durationMs:m,ok:!1,kind:d,session:"worker-fallback",reason:f})},l=(u,d,m)=>{if(o)throw new Error("Rust semantic failover session was already disposed.");if(r)return m(s());let f=performance.now();try{return d(e)}catch(p){c(p,u,performance.now()-f)}return m(s())};return{requestSemantic(u,d){return l("semantic",m=>m.requestSemantic(u,d),m=>m.requestSemantic(u,d))},requestImportDefinitions(u,d){return l("import-definitions",m=>m.requestImportDefinitions(u,d),m=>m.requestImportDefinitions(u,d))},shutdown(){if(o)return;o=!0;let u=[];try{a()}catch(d){u.push(d)}try{n?.shutdown()}catch(d){u.push(d)}if(u.length>0)throw u[0]}}}function gO(e,t,n={worker:()=>hO(),durable:()=>TS(e,{serverPath:Zo(QS()),semanticWorkerPath:Zo(XS())})}){return fO(t)==="durable"?pO(n.durable(),n.worker):n.worker()}function hO(e={}){let t=null,n=null,r=1,i=!1,o=null,s=null,a=d=>{d&&Wd(d,{recursive:!0,force:!0})},c=()=>{if(o)return;let d=t,m=n;t=null,n=null;let f=d?d.terminate():Promise.resolve(0);o=Promise.allSettled([f,qS(m,{gracefulMs:1e3,forceMs:1e3})]).then(([p,g])=>{let h=(g.status==="fulfilled"?g.value:[{reaped:!1,detail:String(g.reason)}]).filter(S=>!S.reaped);if(p.status==="rejected"||h.length>0){s=new Error(`Rust semantic worker cleanup did not complete; ownership evidence remains at ${m??"unknown"}.`);return}a(m)}).finally(()=>{o=null})},l=()=>{if(t)return t;if(o)throw new Error("The previous Rust semantic session worker is still terminating; retry the request.");if(s)throw s;let d=e.semanticWorkerPath?cO(e.semanticWorkerPath):XS();if(!aO(Zo(d)))throw new Error(`Rust semantic session worker was not found at ${Zo(d)}. Run npm run build before using built semantic Rust queries.`);return n=US(Kd(Yd(),"scip-query-rust-session-")),t=new uO(d,e.shareEnvironment?{env:lO}:void 0),t.unref(),t},u=()=>{let d=n??US(Kd(Yd(),"scip-query-rust-session-"));return n=d,Kd(d,`${r++}.json`)};return{requestSemantic(d,m){if(i)throw new Error("Rust semantic session was already disposed.");let f=l(),p=u(),g=new SharedArrayBuffer(4),y=new Int32Array(g);if(f.postMessage({kind:"semantic",request:d,responsePath:p,sharedBuffer:g}),Atomics.wait(y,0,0,m)==="timed-out")throw c(),new Error(`Rust semantic session worker timed out after ${(m/1e3).toFixed(0)}s`);try{let S=yO(J(p,{maxBytes:He,inputKind:"Rust semantic worker response"}));if(!S.ok)throw new Error(S.error);return S.response}finally{Wd(p,{force:!0})}},requestImportDefinitions(d,m){if(i)throw new Error("Rust semantic session was already disposed.");let f=l(),p=u(),g=new SharedArrayBuffer(4),y=new Int32Array(g);if(f.postMessage({kind:"import-definitions",request:d,responsePath:p,sharedBuffer:g}),Atomics.wait(y,0,0,m)==="timed-out")throw c(),new Error(`Rust semantic import-definition session worker timed out after ${(m/1e3).toFixed(0)}s`);try{let S=bO(J(p,{maxBytes:He,inputKind:"Rust import-definition worker response"}));if(!S.ok)throw new Error(S.error);return S.response}finally{Wd(p,{force:!0})}},shutdown(){if(i)return;if(i=!0,!t){a(n),n=null;return}let d=u(),m=new SharedArrayBuffer(4),f=new Int32Array(m);t.postMessage({kind:"shutdown",responsePath:d,sharedBuffer:m}),Atomics.wait(f,0,0,5e3),c()}}}function yO(e){let t=JSON.parse(e);if(!t||typeof t!="object")return{ok:!1,error:"Rust semantic session worker wrote a non-object response."};let n=t;return n.ok===!0&&"response"in n?{ok:!0,response:n.response}:{ok:!1,error:typeof t.error=="string"?t.error:"Rust semantic session worker failed."}}function bO(e){let t=JSON.parse(e);if(!t||typeof t!="object")return{ok:!1,error:"Rust semantic session worker wrote a non-object response."};let n=t;return n.ok===!0&&"response"in n?{ok:!0,response:n.response}:{ok:!1,error:typeof t.error=="string"?t.error:"Rust semantic session worker failed."}}function SO(e){let t=e instanceof Error?`${e.name} ${e.message}`.toLowerCase():String(e).toLowerCase();return t.includes("readiness")?"readiness":t.includes("timeout")||t.includes("timed out")?"timeout":t.includes("helper")?"helper":"request"}function Xo(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Qo(e){return new Map(e.map(t=>[t.symbolId,[]]))}function WS(e){return new Map(e.map(t=>[t.symbolId,null]))}function Jd(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??[]]))}function xO(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function RO(e){let t=0;return e.includeReferences!==!1&&(t+=(e.referenceDefinitions??e.definitions).length),e.includeCallees===!0&&(t+=(e.calleeDefinitions??e.definitions).length),e.includeSignatures===!0&&(t+=(e.signatureDefinitions??e.definitions).length),Math.max(1,t)}function Qd(e,t){return t&&t>0?Math.max(e,t):e}function XS(){return new URL("./rust-semantic-session-worker.js",import.meta.url)}function QS(){return new URL("./rust-semantic-session-server.js",import.meta.url)}function yc(e,t){return er(e)??t}function bc(e,t){return ZS(e)??t}function ZS(e){if(!e)return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var tm=15e3,nm=8;function rx(e,t={}){let n=t.status??dc,r=wO(e,n),i=EO(e,n),o=DO(e,n),s=t.referenceResolver||t.calleeResolver||t.signatureResolver||!vO(t)?null:JS(e,n,{fallbackReferenceResolver:r,fallbackCalleeResolver:i,fallbackSignatureResolver:o}),a=t.referenceResolver??s??r,c=t.calleeResolver??s??i,l=t.signatureResolver??s??o,u=t.importUsageResolver??Nb(t.sourceImportUsageResolver??IO(),t.importDefinitionResolver??s),d=t.calleeSymbolResolver,m=t.sourceZeroCalleeOracle,f=t.scipOccurrenceCalleeOracle,p=new Map,g=new Map,y=null,h=null,S=()=>(y??=n(e),y),b=()=>{let w=S();return w.dependencyAvailable?h??w:w},R=w=>{if(w.length===0)return new Map;let I=ns(w);try{let P=a.referencesForDefinitions(I),_=S();return h=Sc(_,P),P.available?new Map(P.references):tr(I,P.references)}catch(P){let _=S();return h=ts(_,P),qr(I)}},x=w=>{if(w.length===0)return new Map;let I=ns(w),P=I.filter(ex);if(P.length===0)return Ur(I);let _=new Map,se=nx(P,f),ee=[];for(let A of P)g.has(A.symbolId)?_.set(A.symbolId,g.get(A.symbolId)??[]):se.has(A.symbolId)?_.set(A.symbolId,se.get(A.symbolId)??[]):tx(A,m)?_.set(A.symbolId,[]):ee.push(A);if(ee.length===0)return Oi(I,_,void 0);try{let A=c.calleesForDefinitions(ee),ge=S();h=Sc(ge,A);let pe=Oi(ee,A.callees,d);for(let[Cr,uu]of pe)_.set(Cr,uu);return Oi(I,_,void 0)}catch(A){let ge=S();return h=ts(ge,A),Ur(I)}},v=(w,I)=>{let P=ns(w),_=ns(I),se=_.filter(ex),ee=new Map,A=nx(se,f),ge=[];for(let pe of se)A.has(pe.symbolId)?ee.set(pe.symbolId,A.get(pe.symbolId)??[]):tx(pe,m)?ee.set(pe.symbolId,[]):ge.push(pe);if(P.length===0&&ge.length===0)return{references:qr(P),callees:Oi(_,ee,void 0)};try{let pe=s?s.referencesAndCalleesForDefinitions(P,ge):FO(a,c,{referenceDefinitions:P,calleeDefinitions:ge}),Cr=S();h=Sc(Cr,pe);let uu=pe.available?new Map(pe.references):tr(P,pe.references);for(let[du,mu]of pe.callees)ee.set(du,mu);let Bg=Oi(_,ee,d);for(let[du,mu]of Bg)g.set(du,mu);return{references:uu,callees:Bg}}catch(pe){let Cr=S();return h=ts(Cr,pe),{references:qr(P),callees:Ur(_)}}},C=w=>{if(w.length===0)return new Map;let I=ns(w);try{let P=l.signaturesForDefinitions(I),_=S();return h=Sc(_,P),ix(I,P.signatures)}catch(P){let _=S();return h=ts(_,P),xc(I)}};return{language:"rust",availability:b,dispose:()=>{s?.dispose()},importUsage:w=>{let I=p.get(w);if(I)return I;try{let P=u.importUsage(w);return p.set(w,P),P}catch(P){let _=S();return h=ts(_,P),[]}},referencesFor:w=>R([w]).get(w.symbolId)??[],referencesForDefinitions:R,referencesAndCalleesForDefinitions:v,calleesFor:w=>x([w]).get(w.symbolId)??[],calleesForDefinitions:x,signatureFor:w=>C([w]).get(w.symbolId)??null}}function Sc(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 ts(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 vO(e){if(e.usePersistentSession!==void 0)return e.usePersistentSession;let t=process.env.SCIP_RUST_SEMANTIC_SESSION;return t!=="0"&&t!=="false"}function IO(){return{importUsageFacts:()=>({usage:[],positions:[]})}}function ns(e){return e.map(t=>{let n=t;return{...t,leaf:typeof n.leaf=="string"?n.leaf:T(t.symbol),parentTypeName:n.parentTypeName??null,isFunctionLike:typeof n.isFunctionLike=="boolean"?n.isFunctionLike:ae(t.symbol),isTypeLike:n.isTypeLike??!1,kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosingSymbol??null}})}function ex(e){return e.isFunctionLike}function tx(e,t){if(!t)return!1;try{return t(e)}catch{return!1}}function nx(e,t){if(!t||e.length===0)return new Map;try{return t(e)}catch{return new Map}}function wO(e,t){return{referencesForDefinitions:n=>PO(e,t,n)}}function EO(e,t){return{calleesForDefinitions:n=>kO(e,t,n)}}function DO(e,t){return{signaturesForDefinitions:n=>TO(e,t,n)}}function PO(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:om(r),references:qr(n)};let i=rm();if(!em(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,references:qr(n)};let o=Bi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,tm),s=Rc(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),a=Bi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,nm),c=Rc(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),l=es(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!0}),u={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,...s>0?{referenceRetryTimeoutMs:s}:{},diagnosticsTimeoutMs:c,settleDelayMs:l,concurrency:a},d=Zd(process.execPath,[i],{cwd:e,input:JSON.stringify(u),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Br(n.length,Qd(o,u.referenceRetryTimeoutMs),a)}),m=sm(d.stdout);if(m)return{...im(m),resolvedBinary:r.resolvedBinary,references:tr(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:r.resolvedBinary,reason:f,references:qr(n)}}function kO(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:om(r),callees:Ur(n)};let i=rm();if(!em(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,callees:Ur(n)};let o=Bi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,tm),s=Bi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,nm),a=Rc(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=es(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!0}),l={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:s,includeReferences:!1,includeCallees:!0},u=Zd(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Br(n.length,o,s)}),d=sm(u.stdout);if(d)return{...im(d),resolvedBinary:r.resolvedBinary,callees:Oi(n,new Map(d.callees??[]),void 0)};let m=u.error instanceof Error?u.error.message:u.stderr.trim()||`Rust semantic worker exited with status ${u.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:m,callees:Ur(n)}}function TO(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:om(r),signatures:xc(n)};let i=rm();if(!em(i))return{available:!1,resolvedBinary:r.resolvedBinary,reason:`Rust semantic worker was not found at ${i}. Run npm run build before using built semantic Rust queries.`,signatures:xc(n)};let o=Bi(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,tm),s=Bi(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,nm),a=Rc(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=es(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,includeReferences:!1,includeCallees:!1,includeSignatures:!0}),l={projectRoot:e,rustAnalyzerBinary:r.resolvedBinary,definitions:[...n],requestTimeoutMs:o,diagnosticsTimeoutMs:a,settleDelayMs:c,concurrency:s,includeReferences:!1,includeCallees:!1,includeSignatures:!0},u=Zd(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:Br(n.length,o,s)}),d=sm(u.stdout);if(d)return{...im(d),resolvedBinary:r.resolvedBinary,signatures:ix(n,new Map(d.signatures??[]))};let m=u.error instanceof Error?u.error.message:u.stderr.trim()||`Rust semantic worker exited with status ${u.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:m,signatures:xc(n)}}function FO(e,t,n){let r=n.referenceDefinitions.length>0?e.referencesForDefinitions(n.referenceDefinitions):{available:!0,references:qr(n.referenceDefinitions)},i=n.calleeDefinitions.length>0?t.calleesForDefinitions(n.calleeDefinitions):{available:!0,callees:Ur(n.calleeDefinitions)},o={resolvedBinary:r.resolvedBinary??i.resolvedBinary,references:r.references,callees:i.callees};return r.available&&i.available?{available:!0,...o}:{available:!1,reason:(r.available?void 0:r.reason)??(i.available?void 0:i.reason)??"Rust semantic resolution was unavailable.",...o}}function qr(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Ur(e){return new Map(e.map(t=>[t.symbolId,[]]))}function xc(e){return new Map(e.map(t=>[t.symbolId,null]))}function Oi(e,t,n){let r=0,i=0;return D("rust.semantic.callees.complete-map",()=>{let o=new Map;for(let s of e){let a=t.get(s.symbolId)??[];a.length>0&&(r+=1),i+=a.length,o.set(s.symbolId,a.map(c=>({...c,symbol:n?n(c):c.symbol})))}return o},()=>({definitions:e.length,rows:r,callees:i,resolveSymbols:!!n}))}function ix(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function rm(){return CO(new URL("./rust-semantic-worker.js",import.meta.url))}function im(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function om(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function sm(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;if(typeof n.available!="boolean"||!Array.isArray(n.references)||n.available===!1&&typeof n.reason!="string"||n.available===!0&&n.reason!==void 0)return null;let r={references:n.references,incompleteReferenceSymbolIds:Array.isArray(n.incompleteReferenceSymbolIds)?n.incompleteReferenceSymbolIds.filter(i=>typeof i=="number"):void 0,callees:Array.isArray(n.callees)?n.callees:void 0,signatures:Array.isArray(n.signatures)?n.signatures:void 0};return n.available===!0?{available:!0,...r}:{available:!1,reason:String(n.reason),...r}}catch{return null}}function Bi(e,t){return er(e)??t}function Rc(e,t){if(!e)return t;let n=Number(e);return Number.isInteger(n)&&n>=0?n:t}import{existsSync as _O}from"fs";import{deserializeSCIP as AO,SymbolRole as LO}from"@c4312/scip";var am=new WeakMap;function sx(e,t){let n=t.filter(MO);if(n.length===0)return new Map;let r=!1,i=0,o=0;return D("rust.scip-occurrence.callees",()=>{let s=BO(e);if(r=!!s,!s)return new Map;let a=new Map;for(let c of n){let l=NO(e,s,c);l!==null&&(a.set(c.symbolId,l),i+=1,o+=l.length)}return a},()=>({definitions:t.length,candidates:n.length,indexAvailable:r,resolvedDefinitions:i,resolvedCallees:o}))}function MO(e){return!(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||!e.isFunctionLike||e.leaf==="main"||$e(e.symbol))}function NO(e,t,n){let r=Y(e,n.relativePath);if(!r||r.language!=="rust")return null;let i=r.callables.find(l=>l.startLine!==n.startLine||l.endLine!==n.endLine?!1:l.name===n.leaf||n.leaf.endsWith(l.name)||l.name.endsWith(n.leaf));if(!i)return null;let o=r.callSites.filter(l=>l.line>=i.startLine&&l.line<=i.endLine);if(o.length===0)return null;let s=(t.occurrencesByFile.get(n.relativePath)??[]).filter(l=>l.line>=i.startLine&&l.line<=i.endLine&&l.callee.symbol!==n.symbol);if(s.some(l=>l.traitImplMember)||!OO(o,s))return null;let a=[],c=new Set;for(let l of s){let u=`${l.callee.symbol}\0${l.callee.file}\0${l.callee.line}`;c.has(u)||(c.add(u),a.push(l.callee))}return a}function OO(e,t){let n=ox(e),r=ox(t);if(n.size!==r.size)return!1;for(let[i,o]of n)if(r.get(i)!==o)return!1;return!0}function ox(e){let t=new Map;for(let n of e){let r=n.calleeLeaf??n.leaf;if(!r)continue;let i=`${n.line}\0${r}`;t.set(i,(t.get(i)??0)+1)}return t}function BO(e){if(am.has(e))return am.get(e)??null;let t=jO(e);return am.set(e,t),t}function jO(e){if(!e.generation.indexPath||!_O(e.generation.indexPath))return null;try{let t=Oe(e).filter(o=>o.symbol.startsWith("rust-analyzer ")&&o.relativePath.endsWith(".rs")&&o.isFunctionLike),n=new Map(t.map(o=>[o.symbol,o])),r=AO(Se(e.generation.indexPath,{inputKind:"SCIP occurrence-callee index",maxBytes:Me})),i=new Map;for(let o of r.documents??[]){let s=o.relativePath;if(!s||!s.endsWith(".rs")||e.isIgnored(s))continue;let a=[];for(let c of o.occurrences??[]){if(!c.symbol||(c.symbolRoles&LO.Definition)!==0)continue;let l=n.get(c.symbol);if(!l)continue;let u=c.range?.[0];Number.isInteger(u)&&a.push({line:u,leaf:l.leaf,traitImplMember:$e(l.symbol),callee:{symbol:l.symbol,file:l.relativePath,line:l.startLine}})}i.set(s,a)}return{occurrencesByFile:i}}catch{return null}}var Cc=class{sessions=new WeakMap;getOrCreate(t,n,r){let i=$O(t,n),o=this.sessions.get(t);o||(o=new Map,this.sessions.set(t,o));let s=o.get(i);if(s)return s.hits+=1,s.lastUsedAtMs=Date.now(),s.provider;let a=Date.now(),c=r();return o.set(i,{key:i,language:n,projectRoot:t.config.projectRoot,provider:c,createdAtMs:a,lastUsedAtMs:a,hits:1}),c}sessionsFor(t){return[...this.sessions.get(t)?.values()??[]]}clear(t){let n=this.sessions.get(t);if(n)for(let r of n.values())r.provider.dispose?.();this.sessions.delete(t)}};function $O(e,t){return`${e.config.projectRoot}:${t}-workspace`}import{randomUUID as aj}from"crypto";import{existsSync as cj}from"fs";import{dirname as lj}from"path";import{join as vc}from"path";var Use=5,Vse=5e3,HO="watch.lock",GO="watch-state.json",qO="watch-activity.json",UO="watch-refresh-requests";function ax(e){return{lockPath:vc(e,HO),statePath:vc(e,GO),activityPath:vc(e,qO),refreshRequestsPath:vc(e,UO)}}function cm(e){try{return VO(JSON.parse(O(e,"watch service state")))}catch{return null}}function VO(e){if(!e||typeof e!="object")return null;let t=e;if(t.version!==1||typeof t.protocolVersion!="number"||typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0||typeof t.projectRoot!="string"||t.worktreeId!==void 0&&(typeof t.worktreeId!="string"||t.worktreeId.length===0)||typeof t.cliVersion!="string"||!rt(t.startedAt)||!rt(t.heartbeatAt)||!rt(t.lastActivityAt)||!zO(t.watcher)||t.idleDeadlineAt!==void 0&&!rt(t.idleDeadlineAt))return null;if(t.processIdentity!==void 0){let n=Ct(t.processIdentity);if(!n||n.pid!==t.pid)return null;t.processIdentity=n}return t.indexGeneration!==void 0&&!/^[a-f0-9]{64}$/.test(t.indexGeneration)||t.lastError!==void 0&&!WO(t.lastError)||t.lastRefresh!==void 0&&!KO(t.lastRefresh)||t.reindexActivity!==void 0&&!JO(t.reindexActivity)||t.refreshRequests!==void 0&&!YO(t.refreshRequests)||t.typescriptSemantic!==void 0&&!XO(t.typescriptSemantic)||t.typescriptIndex!==void 0&&!QO(t.typescriptIndex)?null:t}function rt(e){return la(e)}function zO(e){if(!e||typeof e!="object"||!("state"in e))return!1;let t=e;switch(t.state){case"idle":return!0;case"waiting":return nt(t.changedFiles)&&nt(t.reindexAt);case"indexing":return nt(t.startedAt);case"cooldown":return nt(t.until)&&typeof t.dirty=="boolean";case"draining":return nt(t.startedAt)&&typeof t.reason=="string";default:return!1}}function WO(e){if(!e||typeof e!="object")return!1;let t=e;return rt(t.at)&&typeof t.message=="string"}function KO(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.trigger?.kind=="string"&&typeof t.result=="string"&&rt(t.startedAt)&&rt(t.completedAt)&&nt(t.durationMs)}function JO(e){if(!e||typeof e!="object")return!1;let t=e;return t.confidence!==void 0&&t.confidence!=="complete"&&t.confidence!=="partial"&&t.confidence!=="unavailable"||t.recordsRead!==void 0&&!B(t.recordsRead)||t.invalidRecords!==void 0&&!B(t.invalidRecords)||t.skippedRecords!==void 0&&!B(t.skippedRecords)||t.readErrors!==void 0&&!B(t.readErrors)||t.ignoredPartialTailBytes!==void 0&&!B(t.ignoredPartialTailBytes)||!rt(t.windowStartedAt)||!rt(t.windowEndedAt)||!B(t.runs)||!B(t.rebuilt)||!B(t.reused)||!B(t.failed)||!B(t.suppressed)||!nt(t.estimatedLogicalOutputBytes)||t.estimatedLogicalOutputBytes<0||!t.byTrigger||typeof t.byTrigger!="object"?!1:Object.values(t.byTrigger).every(n=>n===void 0||B(n))}function YO(e){if(!e||typeof e!="object")return!1;let t=e;return B(t.pending)&&B(t.claimed)&&B(t.completed)&&B(t.expired)&&B(t.invalid)&&(t.oldestPendingAt===void 0||rt(t.oldestPendingAt))}function XO(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.protocolVersion=="number"&&(t.state==="idle"||t.state==="ready"||t.state==="unavailable"||t.state==="error")&&nt(t.requests)&&nt(t.sessionsCreated)&&nt(t.sessionsReused)&&nt(t.sessionsRefreshed)&&nt(t.sessionsReplaced)&&nt(t.projectsCreated)&&(t.lastRequestAt===void 0||rt(t.lastRequestAt))&&(t.lastError===void 0||typeof t.lastError=="string")&&(t.busyUntil===void 0||rt(t.busyUntil))&&(t.mailbox===void 0||cx(t.mailbox))}function QO(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.protocolVersion=="number"&&(t.state==="idle"||t.state==="ready"||t.state==="unavailable"||t.state==="error")&&B(t.requests)&&B(t.sessionsCreated)&&B(t.sessionsReplaced)&&B(t.initializations)&&B(t.programUpdates)&&B(t.documentsEmitted)&&B(t.documentsRemoved)&&(t.lastRequestAt===void 0||rt(t.lastRequestAt))&&(t.lastDurationMs===void 0||nt(t.lastDurationMs)&&t.lastDurationMs>=0)&&(t.lastError===void 0||typeof t.lastError=="string")&&(t.busyUntil===void 0||rt(t.busyUntil))&&(t.mailbox===void 0||cx(t.mailbox))}function cx(e){if(!e||typeof e!="object")return!1;let t=e;return B(t.pending)&&B(t.inflight)&&B(t.responses)&&B(t.deadLetters)&&B(t.invalid)&&B(t.totalItems)&&nt(t.totalBytes)&&t.totalBytes>=0&&t.totalItems===t.pending+t.inflight+t.responses+t.deadLetters&&(t.oldestPendingAt===void 0||rt(t.oldestPendingAt))}function nt(e){return typeof e=="number"&&Number.isFinite(e)}function lx(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.available!="boolean"||t.dependencyAvailable!==void 0&&typeof t.dependencyAvailable!="boolean"||t.tsconfigPath!==void 0&&typeof t.tsconfigPath!="string"||t.tsconfigPaths!==void 0&&(!Array.isArray(t.tsconfigPaths)||!t.tsconfigPaths.every(n=>typeof n=="string"))||t.resolvedBinary!==void 0&&typeof t.resolvedBinary!="string"||t.note!==void 0&&typeof t.note!="string")return null;if(t.available===!0){if(t.reason!==void 0)return null}else if(typeof t.reason!="string"||t.reason.length===0)return null;return t}import{performance as K}from"perf_hooks";function Mt(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}import mx from"path";import{realpathSync as ux}from"fs";function ZO(e,t){return e.getReferences().map(n=>{let r=n.getNode();return Ic(r,t)})}function eB(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function fx(e,t,n,r){let i=[];for(let o of eB(e))for(let s of ZO(o,r))s.file===t.relativePath&&s.line>=t.startLine&&s.line<=t.endLine||i.push(s);for(let o of n)i.push(o);return ji(i)}function px(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();$i(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:Ic(a,r),node:a}))}return i}function Ic(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:$i(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function gx(e,t,n){let r=e.getSourceFile(),i=um(r,e),o=e.getText(),s=new RegExp(`\\b${H(o)}\\b`,"g"),a=r.getFullText().split(`
|
|
325
|
+
`),c=[];for(let l=0;l<a.length;l++){if(l===i)continue;let u=a[l]??"";s.lastIndex=0;let d;for(;(d=s.exec(u))!==null;)c.push({file:t,line:l,column:d.index})}return ji(c.filter(l=>$i(n,mx.join(n,l.file))===t))}function lm(e){for(let t=e;t;t=t.getParent()){let n=t.getKindName();if(n.includes("Type")||n==="InterfaceDeclaration"||n==="TypeAliasDeclaration")return!0;if(n==="CallExpression"||n==="NewExpression"||n==="ExpressionStatement")return!1}return!1}function um(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function ji(e){let t=new Set,n=[];for(let r of e){let i=`${r.file}:${r.line}:${r.column}`;t.has(i)||(t.add(i),n.push(r))}return n}function $i(e,t){let n=e||process.cwd(),r=dx(n,t);if(r)return r;try{return dx(ux(n),ux(t))}catch{return null}}function dx(e,t){let n=mx.relative(e,t).replace(/\\/g,"/");return!n||n===".."||n.startsWith("../")?null:n}function hx(e,t,n,r){let i=tB(t,r);return i.size===0?new Map:nB(e,n,i)}function tB(e,t){let n=new Map;for(let r of ie(e,t)){let i=T(r.symbol)??r.leaf;if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return n}function nB(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of rB(e,o)){let a=n.get(s);if(!a)continue;let c=um(t,o);for(let l of a){if(c<l.startLine-1||c>l.endLine+1)continue;let u=Math.abs(c-l.startLine),d=i.get(l.symbolId);d!==void 0&&d<=u||(i.set(l.symbolId,u),r.set(l.symbolId,o))}}}),r}function rB(e,t){let n=[],r=i=>{i&&!n.includes(i)&&n.push(i)};if("getNameNode"in t&&typeof t.getNameNode=="function"){let i=t.getNameNode();r(i?.getText())}if("getName"in t&&typeof t.getName=="function"){let i=t.getName();r(i)}return e.Node.isIdentifier(t)&&r(t.getText()),n}var iB=$("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function yx(e,t,n,r){let i=fm(e,t),o=dm(i.get(r)??[],n);if(o)return o;let s=[];for(let a of i.values())for(let c of a)((c.leaf||T(c.symbol)||"").includes(r)||c.symbol.includes(r))&&s.push(c);return dm(s,n)}function mm(e,t,n,r){return dm(fm(e,t).get(r)??[],n)}function bx(e,t){let n=new Map;for(let[r,i]of fm(e,t)){let o=i[0];o&&n.set(r,o)}return n}function fm(e,t){return iB.get(e,t,()=>{let n=new Map;for(let r of ie(e,t)){let i=r.leaf||T(r.symbol);if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push({...r,leaf:i})}for(let r of n.values())r.sort((i,o)=>i.startLine-o.startLine||i.endLine-o.endLine||i.symbolId-o.symbolId);return n})}function dm(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let i of e){let o=Math.abs(i.startLine-t);(o<r||o===r&&n&&i.startLine<n.startLine)&&(n=i,r=o)}return n}import oB from"path";import{realpathSync as sB}from"fs";var rs=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function rn(e){let t=e.toLowerCase();return rs.some(n=>t.endsWith(n))}function Sx(e,t){let n=new Map,r=null,i=null,o=()=>(i??=L(e,{extensions:rs}),i),s=()=>(r??=D("typescript.source-file-index",()=>aB(e.config.projectRoot,t,o()),()=>({projects:t.length,indexedDocuments:o().length})),r),a=c=>rn(c)?Mt(n,c,()=>{let l=xx(e.config.projectRoot,c);if(!l)return null;for(let{project:u,sourceFiles:d}of s()){let m=d.get(l)??null;if(m||(m=u.addSourceFileAtPathIfExists(l)??null,m&&pm(d,m)),m)return{project:u,sourceFile:m}}return null}):null;return{sourceFile:c=>a(c)?.sourceFile??null,sourceFileMatch:a,indexedTypeScriptLikeDocuments:o}}function aB(e,t,n){let r=t.map(({project:i})=>{let o=new Map;for(let s of i.getSourceFiles())pm(o,s);return{project:i,sourceFiles:o}});for(let i of n){let o=xx(e,i);if(o)for(let s of r){if(s.sourceFiles.has(o))break;let a=s.project.addSourceFileAtPathIfExists(o)??null;if(a){pm(s.sourceFiles,a);break}}}return r}function pm(e,t){let n=gm(t.getFilePath());e.set(n,t);try{e.set(gm(sB(n)),t)}catch(r){if(!we(r))throw r}}function xx(e,t){try{return gm(bn(e,t,{inputKind:"indexed TypeScript source file"}).absolutePath)}catch(n){if(!we(n))throw n;return null}}function gm(e){return oB.resolve(e)}function hm(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Rx(e){let t=`${e.relativeDir}/src`;return[`${t}/index.ts`,`${t}/index.tsx`,`${t}/index.mts`,`${t}/index.cts`]}import{existsSync as is}from"fs";import Je from"path";var ym=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function bm(e,t){let r=t?Je.dirname(Je.join(e,t)):e,i=Je.resolve(e);for(;r.startsWith(i);){for(let s of ym){let a=Je.join(r,s);if(is(a))return a}let o=Je.dirname(r);if(o===r)break;r=o}for(let o of ym){let s=Je.join(e,o);if(is(s))return s}return null}function Cx(e){let t=e.config.projectRoot,n=new Set(cB(t,e.config.semantic?.typescript?.tsconfigs)),r=L(e,{includeIgnored:!1,extensions:rs});for(let i of r){let o=bm(t,i);o&&n.add(Je.resolve(o))}if(n.size===0){let i=bm(t);i&&n.add(Je.resolve(i))}return[...n].filter(i=>!vx(t,i)).sort((i,o)=>i.localeCompare(o))}function cB(e,t=[]){let n=new Set;for(let r of t){let i=Je.isAbsolute(r)?r:Je.join(e,r);is(i)&&n.add(Je.resolve(i))}for(let r of lB(e))for(let i of ym){let o=Je.join(r,i);is(o)&&n.add(Je.resolve(o))}if(n.size===0){let r=bm(e);r&&n.add(Je.resolve(r))}return[...n].filter(r=>!vx(e,r)).sort((r,i)=>r.localeCompare(i))}function lB(e){let t=Je.join(e,"package.json");if(!is(t))return[];let n;try{n=JSON.parse(O(t,"project package manifest"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>nd(e,i))}function vx(e,t){let n=Je.relative(e,t).replace(/\\/g,"/");return n.startsWith("..")||n.includes("/node_modules/")||n.startsWith("node_modules/")||n.includes("/dist/")||n.startsWith("dist/")}import{createRequire as uB}from"module";var Ix=uB(import.meta.url),os,wc;function Sm(){if(os!==void 0)return os;try{os=Ix("ts-morph")}catch{os=null}return os}function Ec(){if(wc)return wc;let e=Sm();if(!e)return"ts-morph:unavailable";let t="unknown";try{t=Ix("ts-morph/package.json").version??"unknown"}catch{}return wc=`ts-morph:${t}:typescript:${e.ts.version}`,wc}function wx(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!0})}))}function Dc(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}function Pc(e,t){let n=new Map(e.map(i=>[i.symbol,i])),r=new Map(e.map(i=>[i.symbolId,[]]));for(let i of t.values())for(let o of i){let s=n.get(o.targetSymbol);s&&r.get(s.symbolId).push(o.location)}for(let[i,o]of r)r.set(i,dB(o));return r}function Px(e,t,n){let r=Dx(e,t),i=Dx(e,n),o=[...r].filter(d=>!i.has(d)).sort(),s=[...i].filter(d=>!r.has(d)).sort(),a=Ex(e,t),c=Ex(e,n),l=[...a].filter(d=>!c.has(d)).sort(),u=[...c].filter(d=>!a.has(d)).sort();return{passed:o.length===0&&s.length===0,expectedCount:r.size,actualCount:i.size,missing:o,extra:s,callerFiles:{passed:l.length===0&&u.length===0,expectedCount:a.size,actualCount:c.size,missing:l,extra:u}}}function Ex(e,t){let n=new Set;for(let r of e)for(let i of t.get(r.symbolId)??[])i.file!==r.relativePath&&n.add(`${r.symbol}\0${i.file}`);return n}function kx(e,t,n){let r=new Set(n),i=new Map(n.map(o=>[o,[]]));for(let o of e)for(let s of t.get(o.symbolId)??[])r.has(s.file)&&i.get(s.file).push({targetSymbol:o.symbol,location:s});for(let[o,s]of i)i.set(o,mB(s));return i}function Dx(e,t){let n=new Set;for(let r of e)for(let i of t.get(r.symbolId)??[])n.add(`${r.symbol}\0${i.file}\0${i.line}\0${i.column}`);return n}function dB(e){let t=new Map;for(let n of e)t.set(`${n.file}\0${n.line}\0${n.column}`,n);return[...t.values()].sort(Tx)}function mB(e){let t=new Map;for(let n of e){let{location:r}=n;t.set(`${n.targetSymbol}\0${r.file}\0${r.line}\0${r.column}`,n)}return[...t.values()].sort((n,r)=>n.targetSymbol.localeCompare(r.targetSymbol)||Tx(n.location,r.location))}function Tx(e,t){return e.file.localeCompare(t.file)||e.line-t.line||e.column-t.column}var fB=32;function Nx(e,t){let n=D("typescript.provider.load",()=>Sm());if(!n)return Dc("ts-morph is not installed");let r=D("typescript.provider.tsconfig-discovery",()=>Cx(e));if(r.length===0)return Dc("no tsconfig found");try{let i=D("typescript.provider.project-bundles",()=>wx(n,r),()=>({tsconfigs:r.length}));return pB(e,n,i)}catch(i){return Dc(i instanceof Error?i.message:String(i),r[0],r)}}function pB(e,t,n,r={}){return D("typescript.provider.construct",()=>new Rm(e,t,n),()=>({tsconfigs:n.length,reusedProjects:r.reusedProjects===!0}))}var Rm=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=Si(t.config.projectRoot),this.sourceFiles=Sx(t,r)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(t=>t.tsconfigPath)}}importUsage(t){return Mt(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let r=hB();return D("typescript.import-usage.file",()=>this.importUsageForSourceFile(t,n,r),()=>({file:t,...r}))})}referencesFor(t){return Mt(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);return this.referencesForDefinitionNode(t,n)})}referencesForDefinitions(t,n={}){let r=new Map,i=W(),o=[];for(let u of t){let d=this.referencesCache.get(u.symbolId);d?r.set(u.symbolId,d):o.push(u)}if(o.length===0)return r;let s=o,a=n.exact?[]:o.filter(u=>!_x(u));if(a.length>=fB){let u=this.referencesForDefinitionsBySymbolScan(a);for(let d of a){let m=u.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),r.set(d.symbolId,m)}if(s=o.filter(d=>_x(d)),s.length===0)return r}let c=new Map;for(let u of s){let d=c.get(u.relativePath);d?d.push(u):c.set(u.relativePath,[u])}let l=[];for(let[u,d]of c){let m=Ax();D("typescript.references-map.file",()=>{let f=this.definitionNodesForFile(u);for(let p of d){i&&(m.cacheMisses+=1);let g=f.get(p.symbolId)??null;i&&(g?m.nodeHits+=1:m.nodeMisses+=1);try{let y=this.referencesForDefinitionNode(p,g,i?m:void 0);this.referencesCache.set(p.symbolId,y),r.set(p.symbolId,y)}catch{m.preciseSearchFailures+=1,l.push(p)}}},()=>({relativePath:u,definitions:d.length,...Lx(m)}))}if(l.length>0){let u=this.referencesForDefinitionsBySymbolScan(l);for(let d of l){let m=u.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),r.set(d.symbolId,m)}}return r}referenceFragmentsForFiles(t){let n=Oe(this.db).filter(o=>rn(o.relativePath)),r=t.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(n,r);return kx(n,i,r)}referencesForDefinitionsBySymbolScan(t,n){let r=W(),i=Ax(),o=new Map,s=new Set(t.map(c=>c.symbolId)),a=new Map(t.map(c=>[c.symbolId,c]));for(let c of t)o.set(c.symbolId,[]);return D("typescript.references-map.inverted-scan",()=>{let c=r?K.now():0,l=n?this.packageImportReferencesForFiles(n):this.packageImportReferences();for(let y of t){let h=l.get(y.symbolId)??[];if(h.length>0){let S=o.get(y.symbolId)??[];S.push(...h),o.set(y.symbolId,S)}r&&(i.packageReferenceCount+=h.length)}r&&(i.packageRefsMs+=K.now()-c);let u=new Map,d=new Map,m=this.hierarchyTargetsForDefinitions(t),f=new Set(t.map(y=>y.leaf).filter(Boolean)),p=r?K.now():0;for(let y of n??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(y))continue;let h=this.sourceFiles.sourceFile(y);h&&(r&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(h,y,s,a,m,f,u,d,o,r?i:void 0))}r&&(i.scanMs+=K.now()-p);let g=r?K.now():0;this.addHierarchyMemberReferences(t,o,r?i:void 0),r&&(i.hierarchyMs+=K.now()-g);for(let[y,h]of o){let S=ji(h);o.set(y,S),r&&(i.referenceCount+=S.length)}},()=>({definitions:t.length,...Lx(i)})),o}addReferencesFromSourceFileScan(t,n,r,i,o,s,a,c,l,u){let d=this.compilerCheckerForSourceFile(t),m=t.compilerNode,f=SB(t),p=g=>{if(this.tsMorph.ts.isIdentifier(g)){if(u&&(u.identifiers+=1),!s.has(g.text)&&!f.has(g.text)){this.tsMorph.ts.forEachChild(g,p);return}let y=this.compilerReferenceSymbol(d,g,u);if(y){let h;a.has(y)?h=a.get(y)??null:(h=this.referenceDefinitionFromCompilerSymbol(y),a.set(y,h)),u&&(h?u.targetHits+=1:u.targetMisses+=1);let S=Mt(c,y,()=>this.compilerSymbolKeys(y)),b=null,R=null,x=h&&r.has(h.symbolId)?i.get(h.symbolId):void 0;if(x&&(b=xm(m,g),!Fx(x,n,b))){let v=m.getLineAndCharacterOfPosition(g.getStart(m));R={file:n,line:v.line,column:v.character};let C=l.get(x.symbolId)??[];C.push(R),l.set(x.symbolId,C),u&&(u.requestedHits+=1)}for(let v of S)for(let C of o.get(v)?.values()??[]){if(b??=xm(m,g),Fx(C,n,b))continue;if(!R){let I=m.getLineAndCharacterOfPosition(g.getStart(m));R={file:n,line:I.line,column:I.character}}let w=l.get(C.symbolId)??[];w.push(R),l.set(C.symbolId,w),u&&(u.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(g,p)};p(m)}hierarchyTargetsForDefinitions(t){let n=new Map;for(let r of t){let i=this.nodeForDefinition(r),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let s=o.parent;if(!this.isHierarchyContainer(s))continue;let a=this.compilerCheckerForSourceFile(i.getSourceFile()),c=a.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(a,s,c))for(let u of this.compilerSymbolKeys(l)){let d=n.get(u)??new Map;d.set(r.symbolId,r),n.set(u,d)}}return n}hierarchyMemberSymbols(t,n,r){let i=new Set,o=new Set,s=(a,c,l)=>{if(!o.has(a)){o.add(a),i.add(c);for(let u of l){let d=u.getProperty(r.name);d&&s(u,d,this.hierarchyAncestorTypesForType(t,u))}}};return s(t.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(t,n)),i}addHierarchyMemberReferences(t,n,r){let i=new Map;for(let o of t){let s=this.nodeForDefinition(o),a=s?.compilerNode;if(!a||!this.isHierarchyMethod(a))continue;let c=a.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(s.getSourceFile()),u=l.getSymbolAtLocation(a.name);if(!u)continue;let d=a.getSourceFile(),m=d.getLineAndCharacterOfPosition(a.name.getStart(d)),f={definition:o,location:{file:o.relativePath,line:m.line,column:m.character}},p=n.get(o.symbolId)??[];for(let y of this.hierarchyMemberSymbols(l,c,u))if(y!==u)for(let h of this.compilerSymbolLocations(y))p.push(h),r&&(r.hierarchyReferences+=1);n.set(o.symbolId,p);let g=this.hierarchyRootMemberSymbols(l,c,u);for(let y of g){let h=i.get(y)??new Map;h.set(o.symbolId,f),i.set(y,h)}r&&(r.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){r&&(r.hierarchyFamilies+=1);for(let{definition:s}of o.values()){let a=n.get(s.symbolId)??[];for(let c of o.values())c.definition.symbolId!==s.symbolId&&(a.push(c.location),r&&(r.hierarchyReferences+=1));n.set(s.symbolId,a)}}}hierarchyRootMemberSymbols(t,n,r){let i=new Set,o=new Set,s=(a,c,l)=>{if(o.has(a))return;o.add(a);let u=!1;for(let d of l){let m=d.getProperty(r.name);m&&(u=!0,s(d,m,this.hierarchyAncestorTypesForType(t,d)))}if(!u)for(let d of this.compilerSymbolKeys(c))i.add(d)};return s(t.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(t,n)),i}compilerSymbolKeys(t){return(t.declarations??[]).map(n=>{let r=n.getSourceFile();return`${r.fileName}\0${n.getStart(r)}\0${t.name}`})}compilerSymbolLocations(t){let n=[];for(let r of t.declarations??[]){let i=r.getSourceFile(),o=$i(this.db.config.projectRoot,i.fileName);if(!o)continue;let s=r.name,a=i.getLineAndCharacterOfPosition((s??r).getStart(i));n.push({file:o,line:a.line,column:a.character})}return n}baseTypes(t,n){try{return t.getBaseTypes(n)??[]}catch{return[]}}hierarchyAncestorTypes(t,n){let r=new Set(this.hierarchyAncestorTypesForType(t,t.getTypeAtLocation(n)));for(let i of n.heritageClauses??[])for(let o of i.types)r.add(t.getTypeAtLocation(o));return[...r]}hierarchyAncestorTypesForType(t,n){let r=new Set(this.baseTypes(t,n));for(let i of n.getSymbol()?.declarations??[])if(this.isHierarchyContainer(i))for(let o of i.heritageClauses??[])for(let s of o.types)r.add(t.getTypeAtLocation(s));return[...r]}isHierarchyMethod(t){return this.tsMorph.ts.isMethodDeclaration(t)||this.tsMorph.ts.isMethodSignature(t)}isHierarchyContainer(t){return this.tsMorph.ts.isClassDeclaration(t)||this.tsMorph.ts.isClassExpression(t)||this.tsMorph.ts.isInterfaceDeclaration(t)}compilerReferenceSymbol(t,n,r){r&&(r.symbolLookups+=1);let i=t.getSymbolAtLocation(n);if(i){if((i.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return i;try{return r&&(r.aliasResolutions+=1),t.getAliasedSymbol(i)}catch{return i}}}calleesFor(t){return Mt(this.calleesCache,t.symbolId,()=>Mt(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}calleesForDefinitions(t){let n=new Map,r=new Map;for(let i of t){let o=r.get(i.relativePath);o?o.push(i):r.set(i.relativePath,[i])}for(let[i,o]of r){let s=this.fileCalleesCache.get(i),a=new Set(o.map(l=>l.symbolId)),c=s??this.calleeMapForFile(i,a);for(let l of o){let u=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,u),n.set(l.symbolId,u)}}return n}referencesForDefinitionNode(t,n,r){let i=r?K.now():0,o=this.packageImportReferencesForDefinition(t);if(r&&(r.packageRefsMs+=K.now()-i,r.packageReferenceCount+=o.length),!n)return o;let s=r?K.now():0,a=fx(n,t,o,this.db.config.projectRoot);return r&&(r.semanticRefsMs+=K.now()-s,r.referenceCount+=a.length),a}signatureFor(t){return Mt(this.signatureCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);if(!n||!this.tsMorph.Node.isFunctionDeclaration(n)&&!this.tsMorph.Node.isMethodDeclaration(n)&&!this.tsMorph.Node.isArrowFunction(n)&&!this.tsMorph.Node.isFunctionExpression(n)&&!this.tsMorph.Node.isConstructorDeclaration(n))return null;let r=n.getType().getCallSignatures()[0];if(!r)return null;let i=r.getParameters().map(s=>{let a=s.getDeclarations()[0],c=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return Mx(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${Mx(o)}`})}importUsageForSourceFile(t,n,r){let i=[],o=new Map;for(let s of n.getImportDeclarations()){r.declarations+=1;let a=St(this.db,t,s.getModuleSpecifierValue()),c=s.getImportClause()?.isTypeOnly()??!1;for(let l of Cm(s)){r.entries+=1;let u=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(u?r.bindingSymbols+=1:r.missingBindingSymbols+=1);let d={sourcePath:a,entry:l,typeOnlyDeclaration:c,bindingSymbol:u,references:[]};if(i.push(d),c||!l.localName||!u)continue;let m=o.get(l.localName);m?m.push(d):o.set(l.localName,[d])}}return o.size>0&&n.forEachDescendant(s=>{if(s.getKindName()!=="Identifier")return;let a=o.get(s.getText());if(!a||yB(s))return;r.scannedIdentifiers+=1;let c=s.getSymbol()?.compilerSymbol;if(r.symbolLookups+=1,!!c){for(let l of a)if(l.bindingSymbol===c){l.references.push({location:Ic(s,this.db.config.projectRoot),node:s}),r.matchedReferences+=1;break}}}),i.map(s=>s.typeOnlyDeclaration?gB(t,s.sourcePath,s.entry):s.entry.identifier&&!s.bindingSymbol?(r.fallbackEntries+=1,this.valueImportUsageForEntry(t,s.sourcePath,s.entry)):this.valueImportUsageFromLocations(t,s.sourcePath,s.entry,s.references))}valueImportUsageForEntry(t,n,r){let i=r.identifier?r.identifier.findReferences():[],o=[];for(let s of i)for(let a of px(s,t,r.identifier,this.db.config.projectRoot))o.push(a);return this.valueImportUsageFromLocations(t,n,r,o)}valueImportUsageFromLocations(t,n,r,i){let o=i.some(c=>!lm(c.node)),s=i.some(c=>lm(c.node)),a=r.isTypeOnly;return{importer:t,sourcePath:n,importedName:r.importedName,localName:r.localName,kind:r.kind,isTypeOnly:a,isUsed:a||i.length>0,isTypeUsed:a||s,isValueUsed:o,references:i.map(c=>c.location)}}packageImportReferencesForDefinition(t){return this.packageImportReferences().get(t.symbolId)??[]}packageImportReferencesForFiles(t){let n=new Map,r=new Set;for(let o of t){let s=this.sourceFiles.sourceFile(o);if(s)for(let a of s.getImportDeclarations()){let c=hm(this.workspacePackages,a.getModuleSpecifierValue());c&&r.add(c)}}if(r.size===0)return n;let i=this.packageExportsForNames(r);for(let o of t)this.addPackageImportReferencesForDocument(n,i,o);for(let[o,s]of n)n.set(o,ji(s));return n}packageImportReferences(){if(this.packageImportReferenceIndex)return this.packageImportReferenceIndex;let t=new Map,n=this.packageExports();for(let r of this.sourceFiles.indexedTypeScriptLikeDocuments())this.addPackageImportReferencesForDocument(t,n,r);for(let[r,i]of t)t.set(r,ji(i));return this.packageImportReferenceIndex=t,t}addPackageImportReferencesForDocument(t,n,r){if(this.db.isIgnored(r))return;let i=this.sourceFiles.sourceFileMatch(r);if(i)for(let o of i.sourceFile.getImportDeclarations())this.addPackageImportReferencesForDeclaration(t,n,r,o)}addPackageImportReferencesForDeclaration(t,n,r,i){let o=hm(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of Cm(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=gx(a.identifier,r,this.db.config.projectRoot);l.length>0&&vB(t,c,l)}}packageExports(){return this.packageExportIndex?this.packageExportIndex:(this.packageExportIndex=this.packageExportsForNames(new Set(this.workspacePackages.map(t=>t.name))),this.packageExportIndex)}packageExportsForNames(t){let n=new Map;for(let r of this.workspacePackages){if(!t.has(r.name))continue;let i=new Map;for(let o of Rx(r))this.collectPackageExports(r,o,i,new Set);i.size>0&&n.set(r.name,i)}return n}collectPackageExports(t,n,r,i){if(i.has(n))return;i.add(n);let o=this.sourceFiles.sourceFile(n);if(o)for(let s of o.getExportDeclarations()){let a=s.getModuleSpecifierValue(),c=a?St(this.db,n,a):n;if(!c||!c.startsWith(`${t.relativeDir}/src/`))continue;let l=s.getNamedExports();if(l.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(t,c,r,i);continue}for(let u of l){let d=u.getNameNode().getText(),m=u.getAliasNode()?.getText()??d,f=this.indexedDefinitionByLeaf(c,d);if(!f)continue;let p=r.get(m);p||(p=new Set,r.set(m,p)),p.add(f.symbolId)}}}indexedDefinitionByLeaf(t,n){return Mt(this.indexedDefinitionLeafCache,t,()=>bx(this.db,t)).get(n)??null}nodeForDefinition(t){return Mt(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return Mt(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?hx(this.tsMorph,this.db,n,t):new Map})}referenceDefinitionFromCompilerSymbol(t){return this.definitionFromCompilerSymbol(t,void 0,!0)}definitionFromCompilerSymbol(t,n,r=!1){let i=t.name,o=n?K.now():0,s=t.declarations??[];n&&(n.declarationsMs+=K.now()-o,n.declarationChecks+=s.length);for(let a of s){let c=n?K.now():0,l=a.getSourceFile(),u=$i(this.db.config.projectRoot,l.fileName),d=l.getLineAndCharacterOfPosition(a.getStart(l)).line;if(n&&(n.declarationLocationMs+=K.now()-c),!u||this.db.isIgnored(u))continue;let m=n?K.now():0,f=this.compilerDeclarationName(a),p=r?mm(this.db,u,d,i)??(f&&f!==i?mm(this.db,u,d,f):null):yx(this.db,u,d,i);if(n&&(n.indexedLookupMs+=K.now()-m),p)return{symbolId:p.symbolId,symbol:p.symbol,file:p.relativePath,line:p.startLine}}return null}compilerDeclarationName(t){let n=t.name;return n&&this.tsMorph.ts.isIdentifier(n)?n.text:null}calleeMapForFile(t,n){let r=W(),i=0,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=r?RB():void 0;return D("typescript.callee-map.file",()=>{let f=r?K.now():0,p=this.sourceFiles.sourceFile(t);if(r&&(c=Math.round(K.now()-f)),!p)return new Map;let g=r?K.now():0,y=ie(this.db,t).sort((w,I)=>w.startLine-I.startLine||I.endLine-w.endLine);if(r&&(l=Math.round(K.now()-g)),i=y.length,y.length===0)return new Map;let h=new Map,S=r?K.now():0,b=this.compilerCheckerForSourceFile(p),R=p.compilerNode;r&&(u=Math.round(K.now()-S));let x=new Map,v=w=>{if(this.tsMorph.ts.isCallExpression(w)||this.tsMorph.ts.isNewExpression(w)){r&&(o+=1);let I=this.semanticCalleeForCallNode(b,R,y,w,x,n,m);I&&(r&&(s+=1),bB(h,I.callerId,I.target))}this.tsMorph.ts.forEachChild(w,v)},C=r?K.now():0;v(R),r&&(d=Math.round(K.now()-C));for(let[w,I]of h)h.set(w,IB(I));return a=h.size,h},()=>({relativePath:t,definitions:i,callNodes:o,resolvedCallees:s,outputRows:a,requestedDefinitions:n?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:u,traversalMs:d,...m?CB(m):{}}))}semanticCalleeForCallNode(t,n,r,i,o,s,a){let c=a?K.now():0,l=xB(r,xm(n,i));if(a&&(a.callerLookupMs+=K.now()-c),!l)return null;if(s&&!s.has(l.symbolId))return a&&(a.skippedUnrequestedCallers+=1),null;let u=i.expression,d=this.compilerSymbolForExpression(t,u,a),m=null;if(d)if(a&&(a.targetSymbolHits+=1),o.has(d))a&&(a.compilerSymbolCacheHits+=1),m=o.get(d)??null;else{a&&(a.compilerSymbolCacheMisses+=1);let f=a?K.now():0;m=this.definitionFromCompilerSymbol(d,a),a&&(a.targetLookupMs+=K.now()-f),o.set(d,m)}else a&&(a.targetMisses+=1);return m?{callerId:l.symbolId,target:{symbol:m.symbol,file:m.file,line:m.line}}:null}compilerSymbolForExpression(t,n,r){let i=r?K.now():0,o=t.getSymbolAtLocation(n);if(r&&(r.expressionSymbolMs+=K.now()-i),o)return o;r&&(r.typeFallbacks+=1);let s=r?K.now():0,a=t.getTypeAtLocation(n).getSymbol();return r&&(r.typeSymbolMs+=K.now()-s),a}compilerCheckerForSourceFile(t){let n=t.getProject(),r=this.compilerCheckerCache.get(n);return r||(r=n.getTypeChecker().compilerObject,this.compilerCheckerCache.set(n,r)),r}};function Cm(e){let t=[],n=e.getDefaultImport();n&&t.push({identifier:n,importedName:"default",localName:n.getText(),kind:"default",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});let r=e.getNamespaceImport();r&&t.push({identifier:r,importedName:"*",localName:r.getText(),kind:"namespace",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});for(let i of e.getNamedImports()){let o=i.getNameNode(),a=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);t.push({identifier:a,importedName:o.getText(),localName:a?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(e.getImportClause()?.isTypeOnly()??!1)})}return t.length===0&&t.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),t}function gB(e,t,n){return{importer:e,sourcePath:t,importedName:n.importedName,localName:n.localName,kind:n.kind,isTypeOnly:!0,isUsed:!0,isTypeUsed:!0,isValueUsed:!1,references:[]}}function hB(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function yB(e){for(let t=e;t;t=t.getParent())if(t.getKindName()==="ImportDeclaration")return!0;return!1}function bB(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function SB(e){let t=new Set;for(let n of e.getImportDeclarations())for(let r of Cm(n))r.localName&&t.add(r.localName);return t}function xB(e,t){let n=null;for(let r of e)t<r.startLine||t>r.endLine||(!n||r.startLine>=n.startLine)&&(n=r);return n}function xm(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line}function Fx(e,t,n){return t===e.relativePath&&n>=e.startLine&&n<=e.endLine}function _x(e){return e.symbol.includes("#")?be(e.symbol)==="type"&&e.relativePath.endsWith(".d.ts"):!1}function RB(){return{callerLookupMs:0,expressionSymbolMs:0,typeSymbolMs:0,targetLookupMs:0,declarationsMs:0,declarationLocationMs:0,indexedLookupMs:0,compilerSymbolCacheHits:0,compilerSymbolCacheMisses:0,targetSymbolHits:0,targetMisses:0,typeFallbacks:0,declarationChecks:0,skippedUnrequestedCallers:0}}function CB(e){return{...e,callerLookupMs:Math.round(e.callerLookupMs),expressionSymbolMs:Math.round(e.expressionSymbolMs),typeSymbolMs:Math.round(e.typeSymbolMs),targetLookupMs:Math.round(e.targetLookupMs),declarationsMs:Math.round(e.declarationsMs),declarationLocationMs:Math.round(e.declarationLocationMs),indexedLookupMs:Math.round(e.indexedLookupMs)}}function Ax(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}function Lx(e){return{...e,scanMs:Math.round(e.scanMs),packageRefsMs:Math.round(e.packageRefsMs),semanticRefsMs:Math.round(e.semanticRefsMs),hierarchyMs:Math.round(e.hierarchyMs)}}function vB(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function IB(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}|${r.line}`;t.has(i)||(t.add(i),n.push(r))}return n}function Mx(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}import{join as oj}from"path";import{createHash as qB,randomUUID as UB}from"crypto";import{existsSync as qi,mkdirSync as VB,readdirSync as zB,rmSync as Ux,statSync as Vx}from"fs";import{basename as WB,dirname as Tc,join as It}from"path";import{join as BB}from"path";import{randomUUID as wB}from"crypto";import{closeSync as EB,fsyncSync as DB,linkSync as PB,mkdirSync as kB,openSync as TB,statSync as FB,unlinkSync as _B,writeSync as AB}from"fs";import{dirname as Dm}from"path";var Im="scip-query-process-lock",wm=1;var kc=Object.freeze({wallNow:()=>Date.now(),isProcessAlive:Rt,readProcessIdentity:tt,randomToken:()=>wB(),makeDirectory:e=>kB(e,{recursive:!0}),openFile:(e,t,n)=>TB(e,t,n),writeFile:(e,t,n,r)=>AB(e,t,n,r),syncFile:e=>DB(e),closeFile:e=>EB(e),linkFile:(e,t)=>PB(e,t),readFile:e=>O(e,"process lock record"),statFile:e=>{let t=FB(e);return{dev:t.dev,ino:t.ino,size:t.size,mtimeMs:t.mtimeMs}},removeFile:e=>_B(e)});function Gi(e,t){let n=t.runtime??kc;n.makeDirectory(Dm(e));let r;for(let i=0;i<2;i+=1)try{return{kind:"acquired",lock:Bx(e,t,n),...r?{reclaimed:r}:{}}}catch(o){if(o.code!=="EEXIST")throw o;let s=Hi(e,{parseLegacy:t.parseLegacy,runtime:n});if(i===0&&MB(e,s,{creationGraceMs:t.creationGraceMs,parseLegacy:t.parseLegacy,runtime:n})){r=s;continue}return{kind:"contended",observation:s}}return{kind:"contended",observation:Hi(e,{parseLegacy:t.parseLegacy,runtime:n})}}function Hi(e,t={}){let n=t.runtime??kc,r,i;try{r=n.statFile(e),i=n.readFile(e)}catch(c){return c.code==="ENOENT"?{state:"missing"}:{state:"malformed"}}let o;try{o=JSON.parse(i)}catch{return{state:"malformed",raw:i,identity:r}}let s=LB(o);if(s)return{state:"valid",raw:i,identity:r,record:s,owner:OB(s),parsed:o};let a=t.parseLegacy?.(o)??null;return a?{state:"legacy",raw:i,identity:r,owner:a,parsed:o}:{state:"malformed",raw:i,identity:r,parsed:o}}function LB(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.protocol!==Im||t.version!==wm||typeof t.kind!="string"||t.kind.trim()===""||typeof t.pid!="number"||!Number.isSafeInteger(t.pid)||t.pid<=0||typeof t.token!="string"||t.token.trim()===""||typeof t.startedAt!="string"||!Number.isFinite(Date.parse(t.startedAt))||t.detail!==void 0&&(typeof t.detail!="object"||t.detail===null||Array.isArray(t.detail)))return null;let n=t.processIdentity===void 0?null:Ct(t.processIdentity);return t.processIdentity!==void 0&&(!n||n.pid!==t.pid)?null:{protocol:Im,version:wm,kind:t.kind,pid:t.pid,token:t.token,...n?{processIdentity:n}:{},startedAt:t.startedAt,...t.detail?{detail:t.detail}:{}}}function MB(e,t,n={}){let r=n.runtime??kc;if(!Em(t,r))return!1;let i=NB(`${e}.reclaim`,r);if(!i)return!1;try{let o=Hi(e,{parseLegacy:n.parseLegacy,runtime:r});return!jx(t,o)||!Em(o,r)?!1:Pm(e,r)}finally{i.release()}}function Bx(e,t,n){let r=t.pid??process.pid,i=n.randomToken(),o=t.processIdentity===void 0?n.readProcessIdentity(r):t.processIdentity,s={protocol:Im,version:wm,kind:t.kind,pid:r,token:i,...o?{processIdentity:o}:{},startedAt:new Date(n.wallNow()).toISOString(),...t.detail?{detail:t.detail}:{}},a=`${e}.${i}.candidate`,c=n.openFile(a,"wx",384),l;try{jr(c,Buffer.from(`${JSON.stringify(s)}
|
|
326
|
+
`),n,"process lock"),n.syncFile(c)}catch(d){l=d}try{n.closeFile(c)}catch(d){l??=d}if(l!==void 0)throw vm(a,n),l;try{n.linkFile(a,e)}catch(d){throw vm(a,n),d}vm(a,n);try{$x(Dm(e),n)}catch(d){throw Ox(e,s,n),d}let u=!1;return{path:e,record:s,release:()=>u?!1:(u=!0,Ox(e,s,n))}}function Ox(e,t,n=kc){let r=Hi(e,{runtime:n});return r.state!=="valid"||!r.record||r.record.pid!==t.pid||r.record.token!==t.token||t.processIdentity&&(!r.record.processIdentity||!Ke(t.processIdentity,r.record.processIdentity))?!1:Pm(e,n)}function NB(e,t){for(let n=0;n<2;n+=1)try{return Bx(e,{kind:"reclaim-guard",runtime:t},t)}catch(r){if(r.code!=="EEXIST")return null;let i=Hi(e,{runtime:t});if(n>0||!Em(i,t))return null;let o=Hi(e,{runtime:t});if(!jx(i,o)||!Pm(e,t))return null}return null}function Em(e,t){if(e.state==="missing")return!1;if(e.owner){if(!t.isProcessAlive(e.owner.pid))return!0;if(!e.owner.processIdentity)return!1;let n=t.readProcessIdentity(e.owner.pid);return n!==null&&!Ke(e.owner.processIdentity,n)}return!1}function jx(e,t){return e.state===t.state&&e.raw===t.raw&&e.identity!==void 0&&t.identity!==void 0&&e.identity.dev===t.identity.dev&&e.identity.ino===t.identity.ino&&e.identity.size===t.identity.size&&e.identity.mtimeMs===t.identity.mtimeMs}function OB(e){return{pid:e.pid,...e.processIdentity?{processIdentity:e.processIdentity}:{}}}function $x(e,t){let n;try{n=t.openFile(e,"r")}catch(r){if(Ti(r,process.platform))return;throw r}try{t.syncFile(n)}catch(r){if(!Ti(r,process.platform))throw r}finally{t.closeFile(n)}}function Pm(e,t){try{return t.removeFile(e),$x(Dm(e),t),!0}catch{return!1}}function vm(e,t){try{t.removeFile(e)}catch{}}var jB=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.pid;return typeof t=="number"&&Number.isSafeInteger(t)&&t>0?{pid:t}:null};function Tm(e,t={}){return or(BB(e,"gc.lock"),t)}function or(e,t={}){let n=t.waitMs??0,r=t.pollMs??10,i=t.now??Ae,o=i()+n;do{let s=Hx(e);if(s)return Gx(s);let a=o-i();if(a<=0)return null;$B(Math.min(r,a))}while(i()<=o);return null}async function tce(e,t={}){let n=t.waitMs??0,r=t.pollMs??10,i=t.now??Ae,o=i()+n;do{GB(t.signal);let s=Hx(e);if(s)return Gx(s);let a=o-i();if(a<=0)return null;await HB(Math.min(r,a),t.signal)}while(i()<=o);return null}function Hx(e){let t=Gi(e,{kind:"generic",parseLegacy:jB});return t.kind==="acquired"?t.lock:null}function Gx(e){return{release:()=>{e.release()}}}function $B(e){let t=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));Atomics.wait(t,0,0,e)}function HB(e,t){return t?.aborted?Promise.reject(km(t)):new Promise((n,r)=>{let i=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e),o=()=>{clearTimeout(i),t?.removeEventListener("abort",o),r(t?km(t):new Error("Lock acquisition was aborted."))};t?.addEventListener("abort",o,{once:!0})})}function GB(e){if(e?.aborted)throw km(e)}function km(e){return e.reason instanceof Error?e.reason:new Error("Lock acquisition was aborted.")}var Vr=1,Lm=1,as=".scipquery-generations",Fc="manifest.json",zx="readers",KB="gc.lock",JB=128,ss=new Map,Wx={pid:process.pid,now:()=>new Date,randomToken:()=>UB(),isProcessAlive:Rt,readProcessIdentity:tt};function Le(e){return It(Tc(e),as)}function _c(e){return It(Le(e),KB)}function Kx(e,t=Wx){let n=or(_c(e.dbPath),{waitMs:5e3});if(!n)throw new Error("SQLite generation retention is busy; retry opening the index.");let r;try{let i=Nm(e);if(i.source!=="immutable")return{generation:i,release(){}};let o=t.randomToken();if(!/^[A-Za-z0-9._-]+$/.test(o))throw new Error("SQLite generation reader token is unsafe.");let s=It(Le(e.dbPath),zx);VB(s,{recursive:!0}),r=It(s,`${t.pid}-${o}.json`);let a=t.readProcessIdentity(t.pid);nr(r,{version:1,token:o,generationIdentity:i.identity,pid:t.pid,...a?{processIdentity:a}:{},acquiredAt:t.now().toISOString()},{spacing:2,trailingNewline:!0});let c=!1;return{generation:i,release(){c||!r||(c=!0,Ux(r,{force:!0}))}}}finally{n.release()}}function Mm(e,t,n=Wx,r={}){let i=It(Le(e),zx);if(!qi(i))return{protectedGenerations:new Set,activeLeases:0,staleLeasesRemoved:0,malformedLeases:0};let o=new Set,s=0,a=0,c=0;for(let l of zB(i,{withFileTypes:!0})){if(!l.isFile()||!l.name.endsWith(".json"))continue;let u=It(i,l.name),d;try{d=YB(JSON.parse(O(u,"SQLite generation reader lease")))}catch{d=null}if(!d){c+=1;for(let m of t)o.add(m);continue}if(!XB(d,n)){r.removeStale!==!1&&(Ux(u,{force:!0}),a+=1);continue}s+=1,o.add(d.generationIdentity)}return{protectedGenerations:o,activeLeases:s,staleLeasesRemoved:a,malformedLeases:c}}function YB(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,n=t.processIdentity===void 0?null:Ct(t.processIdentity);return t.version!==1||typeof t.token!="string"||t.token.trim()===""||typeof t.generationIdentity!="string"||!/^[a-f0-9]{64}$/.test(t.generationIdentity)||typeof t.pid!="number"||!Number.isSafeInteger(t.pid)||t.pid<=0||typeof t.acquiredAt!="string"||!Number.isFinite(Date.parse(t.acquiredAt))||t.processIdentity!==void 0&&(!n||n.pid!==t.pid)?null:{version:1,token:t.token,generationIdentity:t.generationIdentity,pid:t.pid,...n?{processIdentity:n}:{},acquiredAt:t.acquiredAt}}function XB(e,t){if(!t.isProcessAlive(e.pid))return!1;if(!e.processIdentity)return!0;let n=t.readProcessIdentity(e.pid);return n===null||Ke(e.processIdentity,n)}function sr(e){try{let t=JSON.parse(O(It(Le(e),"state.json"),"SQLite generation state"));return tj(t)?t:null}catch{return null}}function Ac(e,t){return cs(Le(e),t)}function cs(e,t){try{let n=JSON.parse(O(It(e,t,Fc),"SQLite generation manifest"));return ej(n,t)?n:null}catch{return null}}function Nm(e){let t=sr(e.dbPath);if(t){let n=QB(e,t.currentGeneration);if(n)return n;if(t.artifactSet==="immutable-v1")throw new Error(`Published SQLite generation ${t.currentGeneration} is missing or invalid.`)}if(qi(It(Tc(e.dbPath),"index.lock")))throw new Error("Legacy SQLite publication is in progress; retry after the reindex lock is released.");return ZB(e,t?.currentGeneration)}function Jx(e){let t=sr(e);if(t)return t.currentGeneration;try{let n=It(Tc(e),"meta.json"),r=qi(n)?O(n,"reindex metadata"):void 0;return Yx(e,r)}catch{return null}}function ar(e){return zg(Jt(e))??e}function QB(e,t){try{let n=It(Le(e.dbPath),t),r=Ac(e.dbPath,t);if(!r)return null;let i=Fm(n,r.database),o=r.index?Fm(n,r.index):void 0,s=r.metadata?Fm(n,r.metadata):void 0;return!_m(i,r.database)||r.index&&(!o||!_m(o,r.index))||r.metadata&&(!s||!_m(s,r.metadata))?null:{identity:t,databasePath:i,...o?{indexPath:o}:{},...s?{metadataPath:s,metadataRaw:O(s,"reindex metadata")}:{},source:"immutable"}}catch{return null}}function ZB(e,t){let n=Fn(e.dbPath),r=It(Tc(e.dbPath),"meta.json"),i=qi(r)?O(r,"reindex metadata"):void 0,o=qi(e.indexPath)?e.indexPath:void 0;return{identity:t??Yx(e.dbPath,i),databasePath:e.dbPath,...o?{indexPath:o}:{},...i===void 0?{}:{metadataPath:r,metadataRaw:i},source:"legacy",databaseFileIdentity:n}}function Yx(e,t){let n=qB("sha256").update("sqlite-generation-legacy-v1\0");return t!==void 0&&n.update(ar(t)),n.update(`\0${Fn(e)}`),n.digest("hex")}function Fn(e){let t=Vx(e);return`${t.dev}:${t.ino}:${t.size}:${t.mtimeMs}`}function Fm(e,t){if(WB(t.file)!==t.file||t.file==="."||t.file==="..")throw new Error("SQLite generation manifest contains an unsafe artifact path");return It(e,t.file)}function _m(e,t){if(!qi(e))return!1;let n=qx(e);if(!n||n.size!==t.size)return!1;let r=`${e}\0${t.sha256}\0${n.identity}`;if(ss.has(r))return!0;let i=Zt(e,{inputKind:"immutable SQLite generation artifact",maxBytes:t.size}),o=qx(e);if(!o||o.identity!==n.identity||i!==t.sha256)return!1;for(ss.set(r,!0);ss.size>JB;){let s=ss.keys().next().value;if(s===void 0)break;ss.delete(s)}return!0}function qx(e){let t=Vx(e,{bigint:!0});return t.isFile()?{identity:`${t.dev}:${t.ino}:${t.size}:${t.mtimeNs}:${t.ctimeNs}`,size:Number(t.size)}:null}function ej(e,t){return e.version===Lm&&e.identity===t&&Am(e.database)&&(e.index===void 0||Am(e.index))&&(e.metadata===void 0||Am(e.metadata))}function Am(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.file=="string"&&!!t.file&&Number.isSafeInteger(t.size)&&(t.size??-1)>=0&&typeof t.sha256=="string"&&/^[a-f0-9]{64}$/.test(t.sha256)}function tj(e){return e.version===Vr&&typeof e.currentGeneration=="string"&&!!e.currentGeneration&&typeof e.publishedAt=="string"&&Number.isFinite(Date.parse(e.publishedAt))&&(e.artifactSet===void 0||e.artifactSet==="immutable-v1")&&nj(e.stableMirrors)&&rj(e.previousGeneration)&&ij(e.publication)}function nj(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e;return typeof t.databaseFileIdentity=="string"&&!!t.databaseFileIdentity&&(t.indexFileIdentity===void 0||typeof t.indexFileIdentity=="string"&&!!t.indexFileIdentity)}function rj(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e;return typeof t.generationIdentity=="string"&&!!t.generationIdentity&&typeof t.databasePath=="string"&&!!t.databasePath&&(t.metadataPath===void 0||typeof t.metadataPath=="string"&&!!t.metadataPath)}function ij(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e,n=[t.converterDurationMs,t.affectedDocumentCount,t.changedDocumentCount,t.producerDurationMs,t.materializationDurationMs,t.patchDurationMs].filter(r=>r!==void 0);return(t.mode==="incremental"||t.mode==="full")&&t.validation==="passed"&&t.converterDurationMs!==void 0&&n.every(r=>typeof r=="number"&&Number.isFinite(r)&&r>=0)&&(t.scipCompanion===void 0||t.scipCompanion==="current"||t.scipCompanion==="deferred")&&(t.typescriptOverlayGeneration===void 0||typeof t.typescriptOverlayGeneration=="string"&&!!t.typescriptOverlayGeneration)&&(t.scipCompanion!=="deferred"||!!t.typescriptOverlayGeneration)&&(t.fallbackReason===void 0||typeof t.fallbackReason=="string")}var Lc=3;var sj="typescript-semantic";function Xx(e){let t=oj(e,sj),n=mc(t);return{...n,requestDir:n.legacyRequestDir}}function Qx(e){return Jx(e)}var uj=12e4,dj=5;function tR(e,t,n={}){let r=new Om(e,n),i=null,o=null,s=process.env.SCIP_QUERY_SKIP_WATCH_SERVICE==="1",a=()=>(i??=Nx(e,t),i),c=(d,m,f)=>{if(s)return f();try{return m(r.request(d))}catch{return s=!0,f()}},l=(d,m)=>c({kind:"references",definitions:[...d],...m?.exact?{exact:!0}:{}},f=>eR(f),()=>a().referencesForDefinitions?.(d,m)??new Map(d.map(f=>[f.symbolId,a().referencesFor(f)]))),u=d=>c({kind:"callees",definitions:[...d]},m=>eR(m),()=>a().calleesForDefinitions?.(d)??new Map(d.map(m=>[m.symbolId,a().calleesFor(m)])));return{language:"typescript",availability:()=>(o??=c({kind:"availability"},pj,()=>a().availability()),o),importUsage:d=>c({kind:"import-usage",file:d},m=>m,()=>a().importUsage(d)),referencesFor:d=>l([d]).get(d.symbolId)??[],referencesForDefinitions:l,referenceFragmentsForFiles:d=>c({kind:"reference-fragments",files:[...d]},m=>fj(m),()=>a().referenceFragmentsForFiles?.(d)??new Map),calleesFor:d=>u([d]).get(d.symbolId)??[],calleesForDefinitions:u,signatureFor:d=>c({kind:"signature",definition:d},gj,()=>a().signatureFor(d)),dispose:()=>i?.dispose?.()}}var Om=class{constructor(t,n={}){this.db=t;this.runtime=n.runtime??yj,this.timeoutMs=n.timeoutMs??hj(),this.mailboxLimits=n.mailboxLimits??{},this.cacheDir=lj(t.config.dbPath),this.projectRoot=Yt(t.config.projectRoot)}db;runtime;timeoutMs;cacheDir;projectRoot;mailboxLimits;request(t){let n=ax(this.cacheDir),r=Xx(this.cacheDir),i=cm(n.statePath);if(!Zx(i,this.projectRoot,this.runtime))throw new Error("Compatible TypeScript semantic service is not running.");let o=this.db.generation.identity;if(!o)throw new Error("Published TypeScript generation identity is unavailable.");let s=this.runtime.now(),a=s+this.timeoutMs,c=(this.runtime.monotonicNow??Ae)()+this.timeoutMs,l=bh(),u=Li("typescript-semantic-v3",{generation:o,profileEnvironment:l,request:t}),d=Hr(u),m=fc(r,{mailboxVersion:ir,operationKey:u,clientId:this.runtime.randomId(),enqueuedAtMs:s,deadlineAtMs:a,protocolVersion:Lc,id:d,generation:o,profileEnvironment:l,request:t},{nowMs:s,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??Ae)()<=c;){if(cj(m.responsePath))return mj(J(m.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript semantic mailbox response"}),d,o,u);let f=cm(n.statePath);if(!Zx(f,this.projectRoot,this.runtime))throw new Error("TypeScript semantic service stopped while processing a request.");this.runtime.sleep(dj)}throw new Error(`TypeScript semantic service timed out after ${this.timeoutMs}ms.`)}};function Zx(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptSemantic?.protocolVersion===Lc&&n.isProcessAlive(e.pid)&&(!e.processIdentity||r!=null&&Ke(e.processIdentity,r))}function mj(e,t,n,r){let i=JSON.parse(e);if(i.protocolVersion!==Lc||i.id!==t||i.operationKey!==r||i.ok===!0&&i.generation!==n)throw new Error("TypeScript semantic service wrote an incompatible response.");if(i.ok===!0)return i.response;throw new Error(typeof i.error=="string"?i.error:"TypeScript semantic service request failed.")}function eR(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid numeric map.");return new Map(e)}function fj(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid string map.");return new Map(e)}function pj(e){let t=lx(e);if(!t)throw new Error("TypeScript semantic service wrote invalid availability.");return t}function gj(e){if(e!==null&&typeof e!="string")throw new Error("TypeScript semantic service wrote an invalid signature.");return e}function hj(){let e=Number(process.env.SCIP_TYPESCRIPT_SEMANTIC_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:uj}var yj={now:Date.now,monotonicNow:Ae,randomId:aj,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:Rt,readProcessIdentity:tt};var nR=new Cc;Un({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>nR.clear(e)});function zr(e,t){let n=qe(t)??"typescript";return nR.getOrCreate(e,n,()=>n==="rust"?rx(e.config.projectRoot,{sourceImportUsageResolver:{importUsageFacts:r=>Mb(e,r)},calleeSymbolResolver:Lb(e),sourceZeroCalleeOracle:r=>bj(e,r),scipOccurrenceCalleeOracle:r=>sx(e,r)}):tR(e,t))}function qe(e){return e?N(e)==="rust"?"rust":rn(e)?"typescript":null:"typescript"}function bj(e,t){let n=Y(e,t.relativePath);if(!n||n.language!=="rust")return!1;let r=n.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine&&i.name===t.leaf)??n.callables.find(i=>i.startLine===t.startLine&&i.endLine===t.endLine);return r?!n.callSites.some(i=>i.line>=r.startLine&&i.line<=r.endLine):!1}var Sj=/^[A-Za-z_][A-Za-z0-9_]*$/,rR=/\bDefault::default\b/g,xj=/^\.\.\s*Default::default\b/;function iR(e,t){let n=new Map,r=new Map;for(let i of t){let o=Bm(e,i,r);o!==null&&n.set(i.symbolId,o)}return n}function Bm(e,t,n=new Map){let r=Cj(t.symbol);if(!r)return null;let i=Pi(e,[t.symbolId]);if(i.length===0)return null;let o=new RegExp(`(^|[^A-Za-z0-9_])${H(r)}::default\\b`,"g"),s=new RegExp(`(^|[^A-Za-z0-9_])${H(r)}\\s*$`),a=Rj(e,t.symbolId),c=[];for(let l of i){let u=vj(e,l.relative_path,n);if(u===null)return null;let d=u.split(/\r?\n/),m=0,f=[],p=0;for(let g=l.chunk_start;g<=l.chunk_end&&g<d.length;g+=1){let h=d[g]??"",S=new Set;o.lastIndex=0;let b;for(;b=o.exec(h);)c.push({file:l.relative_path,line:g,column:b.index+b[1].length+r.length+2}),p+=1;for(let R=0;R<h.length;R+=1){let x=xj.exec(h.slice(R));if(x){if(a&&f.includes(m)){let C=R+x[0].lastIndexOf("default");c.push({file:l.relative_path,line:g,column:C}),S.add(C),p+=1}R+=x[0].length-1;continue}let v=h[R];if(v==="{"){let C=s.test(h.slice(0,R));m+=1,C&&f.push(m);continue}if(v==="}")for(m=Math.max(0,m-1);f.length>0&&f[f.length-1]>m;)f.pop()}for(rR.lastIndex=0;b=rR.exec(h);){let R=b.index+9;if(!S.has(R))return null}}if(p===0)return null}return pc(c)}function Rj(e,t){return e.get("SELECT 1 AS present FROM mentions WHERE symbol_id = ? AND role = 1 LIMIT 1",t)?.present===1}function Cj(e){let t=/impl#\[([^\]]+)\]\[Default\]default\(\)\./.exec(e)?.[1]??null;return!t||!Sj.test(t)?null:t}function vj(e,t,n){if(n.has(t))return n.get(t)??null;let r=e.get("SELECT text FROM documents WHERE relative_path = ?",t),i=typeof r?.text=="string"?r.text:Ij(e,t);return n.set(t,i),i}function Ij(e,t){try{return de(e.config.projectRoot,t,{inputKind:"indexed Rust source file"})}catch(n){if(!we(n))throw n;return null}}function Nc(e){let t=Mc(e.projectFiles),n=new Set(t),r=new Map(e.snapshot.files.map(d=>[d.path,d])),i=e.snapshot.files.filter(d=>{let m=fu(d.path,["typescript"]);return m==="config"||m==="ambient"}).map(d=>d.path),o=Mc([...t,...i]),s=o.find(d=>!r.has(d)),a=new Set(e.snapshot.files.map(d=>d.path)).size!==e.snapshot.files.length,c=!s&&o.some(d=>oR(r.get(d))),l=ke(JSON.stringify({pnpmWorkspaces:e.snapshot.pnpmWorkspaces,typescriptProjectMode:e.snapshot.typescriptProjectMode,typescriptProjects:Mc(e.snapshot.typescriptProjects),membership:t})),u=new Map;return{identityFor(d,m){if(!n.has(d))return Ui("target-outside-project");if(a)return Ui("duplicate-input-path");if(s)return Ui("missing-input-fingerprint");if(c)return Ui("unreadable-input");let f=[],p,g;if(e.graph===null)f.push("dependency-graph-unavailable"),g="whole-project",p=o;else{let S=Ej(d,e.graph,u);if(S.find(R=>!r.has(R)))return Ui("missing-input-fingerprint");if(p=Mc([...S,...i]),p.some(R=>oR(r.get(R))))return Ui("unreadable-input");g="dependency-closure"}let y=p.map(S=>Dj(r.get(S)));return{version:1,key:ke(JSON.stringify({version:1,engineIdentity:e.engineIdentity,schemaVersion:m,projectIdentity:l,inputs:y})),mode:g,inputFiles:p,reasons:f}}}}function wj(e,t){let n=new Set,r=[e];for(let i=0;i<r.length;i+=1){let o=r[i];if(!(o===void 0||n.has(o))){n.add(o);for(let s of[...t.get(o)??[]].sort())n.has(s)||r.push(s)}}return[...n].sort()}function Ej(e,t,n){let r=n.get(e);if(r)return r;let i=wj(e,t);return n.set(e,i),i}function Dj(e){return{path:e.path,size:e.size,hash:e.hash}}function oR(e){return e.size<0||e.hash==="unreadable"}function Ui(e){return{version:1,key:null,mode:"unkeyed",inputFiles:[],reasons:[e]}}function Mc(e){return[...new Set(e)].sort()}var Pj=z("typescript-semantic-identity-context",{clearGroups:["whole-project"]});function cr(e,t,n){let r=Pj.get(e,()=>kj(e));if(!r)return null;let i=`${n}\0${t}`,o=r.identities.get(i);if(o)return o;let s=r.builder.identityFor(t,n);return r.identities.set(i,s),s}function ls(e){return L(e,{includeIgnored:!1}).filter(rn).sort()}function kj(e){try{if(!e.generation.metadataRaw)return null;let t=Jt(e.generation.metadataRaw);if(t.kind!=="legacy"&&t.kind!=="supported"||!t.capabilities.usableForEvidenceCache)return null;let n=qg(t.metadata.fingerprint);return n?{builder:Nc({projectFiles:ls(e),snapshot:n,graph:le(e),engineIdentity:Ec()}),identities:new Map}:null}catch{return null}}var jm="typescript-reference-fragment-v2",Bc=me({kind:"typescript-reference-fragments",invalidation:re("typescript-reference-fragments"),serialize:e=>JSON.stringify(e),deserialize:Fj});function gle(e,t,n,r=e){let i=ls(e),o=Nc({projectFiles:i,snapshot:t,graph:le(e),engineIdentity:Ec()}),s=[...n].map(([a,c])=>({relativePath:a,contentHash:o.identityFor(a,jm).key,value:[...c]}));if(s.some(a=>a.contentHash===null))throw new Error("TypeScript reference fragment identity is unavailable for an affected document.");return Bc.writeBatch(r,s.map(a=>({...a,contentHash:a.contentHash}))),s.length}function $m(e,t,n,r){let i=t.filter(s=>rn(s.relativePath));if(i.length===0)return Oc("no TypeScript definitions");let o=Oc("shadow did not run");return D("typescript.reference-fragments.shadow",()=>{try{let s=r(i[0].relativePath);if(!s.availability().available||!s.referenceFragmentsForFiles)return o=Oc("TypeScript reference fragment provider is unavailable"),o;let a=ls(e),c=new Set(a),l=s.referenceFragmentsForFiles(a),u=Pc(i,l),d=Px(i,Tj(n,c),u);if(!d.passed)return o={state:"failing",files:a.length,keyedFiles:0,writtenFiles:0,...d},o;let m=[];for(let f of a){let p=cr(e,f,jm);p?.key&&m.push({relativePath:f,contentHash:p.key,value:l.get(f)??[]})}return Bc.writeBatch(e,m),o={state:"passing",files:a.length,keyedFiles:m.length,writtenFiles:m.length,...d},o}catch(s){return o=Oc(s instanceof Error?s.message:String(s)),o}},()=>({...o}))}function Tj(e,t){return new Map([...e].map(([n,r])=>[n,r.filter(i=>t.has(i.file))]))}function Hm(e,t,n){if(t.length===0)return{references:new Map,files:0,cacheHits:0,cacheMisses:0,computedFiles:0};let r="fallback",i=0,o=0,s=0,a=0;return D("typescript.reference-fragments.materialize",()=>{try{let c=ls(e);i=c.length;let l=new Map,u=new Map,d=[];for(let p of c){let g=cr(e,p,jm);if(!g?.key)return null;l.set(p,g.key);let y=Bc.read(e,p,g.key);y===null?(s+=1,d.push(p)):(o+=1,u.set(p,y))}if(s===0)return r="hit",{references:Pc(t,u),files:i,cacheHits:o,cacheMisses:s,computedFiles:a};let m=n(t[0].relativePath);if(!m.availability().available||!m.referenceFragmentsForFiles)return null;let f=m.referenceFragmentsForFiles(d);if(d.some(p=>!f.has(p)))return null;a=f.size,Bc.writeBatch(e,d.map(p=>({relativePath:p,contentHash:l.get(p),value:f.get(p)??[]})));for(let[p,g]of f)u.set(p,g);return r="computed",{references:Pc(t,u),files:i,cacheHits:o,cacheMisses:s,computedFiles:a}}catch{return null}},()=>({state:r,files:i,cacheHits:o,cacheMisses:s,computedFiles:a}))}function Oc(e){return{state:"unavailable",files:0,keyedFiles:0,writtenFiles:0,expectedCount:0,actualCount:0,missing:[],extra:[],reason:e}}function Fj(e){try{let t=JSON.parse(e);return!Array.isArray(t)||!t.every(_j)?null:t}catch{return null}}function _j(e){if(!e||typeof e!="object")return!1;let t=e,n=t.location;return typeof t.targetSymbol=="string"&&!!n&&typeof n.file=="string"&&typeof n.line=="number"&&typeof n.column=="number"}var Aj="typescript-import-usage-v1",Lj="typescript-signatures-v1",Gm=z("semantic-prefetched-callees",{clearGroups:["whole-project","source-file","semantic-provider"]}),sR=Pr({kind:"semantic-import-usage",invalidation:re("semantic-import-usage"),serialize:e=>JSON.stringify(e),deserialize:yR}),aR=Pr({kind:"semantic-signatures",invalidation:re("semantic-signatures"),serialize:e=>JSON.stringify(e),deserialize:qj}),cR=me({kind:"typescript-import-usage",invalidation:re("typescript-import-usage"),serialize:e=>JSON.stringify(e),deserialize:yR}),lR=me({kind:"typescript-signatures",invalidation:re("typescript-signatures"),serialize:e=>JSON.stringify(e),deserialize:Uj});function mt(e){let t=new Map,n=new Set;return{capability:(r,i)=>bR(e,r,i),importUsage:r=>Nj(e,r),references:r=>mR(e,r),materializeReferences:(r,i)=>pR(e,r,t,n,i),callerMap:r=>Oj(e,r,t,n),calleeMap:r=>$j(e,r),signature:r=>Hj(e,r)}}function Mj(e,t){if(t.size===0)return;let n=Gm.get(e,()=>new Map);for(let[r,i]of t)n.set(r,[...i])}function dR(e,t){if(!Gm.has(e))return{hits:[],misses:[...t]};let n=Gm.get(e,()=>new Map),r=[],i=[];for(let o of t)n.has(o.symbolId)?r.push({definition:o,callees:n.get(o.symbolId)??[]}):i.push(o);return{hits:r,misses:i}}function ds(e,t){return mt(e).importUsage(t)}function Nj(e,t){if(qe(t)==="typescript"){let o="fallback",s=0,a=0,c=0,l=0;return D("typescript.import-usage.materialize",()=>{let u=cr(e,t,Aj);if(u?.key){s=1;let m=cR.read(e,t,u.key);if(m)return o="hit",a=1,m;c=1;let f=on(e,t);if(!f)return o="unavailable",[];let p=f.importUsage(t);return cR.write(e,t,u.key,p),o="computed",p}l=1;let d=on(e,t);return d?(o="direct-fallback",d.importUsage(t)):(o="unavailable",[])},()=>({state:o,eligible:s,cacheHits:a,cacheMisses:c,fallbacks:l}))}let n=hR(e,"semantic-import-usage",t);if(n){let o=sR.read(e,t,n);if(o)return o}let r=on(e,t);if(!r)return[];let i=r.importUsage(t);return n&&sR.write(e,t,n,i),i}function jc(e,t){return mt(e).references(t)}function mR(e,t){let n=Bm(e,t);if(n)return n;let r=pS(e,t);if(r)return r;let i=on(e,t.relativePath);return i?i.referencesFor(t):[]}function lr(e,t){return mt(e).callerMap(t)}function fR(e,t){let n=new Map,r=new Map;for(let i of t){if(qe(i.relativePath)==="typescript"){let o=on(e,i.relativePath);if(!o)continue;let s=r.get(o)??[];s.push(i),r.set(o,s);continue}qm(e,n,i,mR(e,i))}for(let[i,o]of r){let s=Hm(e,o,c=>zr(e,c)),a=s?.references??(i.referencesForDefinitions?i.referencesForDefinitions(o,{exact:!0}):new Map(o.map(c=>[c.symbolId,i.referencesFor(c)])));!s&&W()&&$m(e,o,a,c=>zr(e,c));for(let c of o)qm(e,n,c,a.get(c.symbolId)??[])}return n}function Oj(e,t,n=new Map,r=new Set){let i=new Map,o=pR(e,t,n,r),s=0;return D("semantic.callers.from-references",()=>{for(let a of t)s+=qm(e,i,a,n.get(a.symbolId)??[])},()=>({definitions:t.length,materialized:o.definitions,inMemoryHits:o.inMemoryHits,incompleteInMemoryHits:o.incompleteInMemoryHits,resultRows:i.size,callerFiles:s})),i}function pR(e,t,n,r,i={}){let o=We(e),s=[],a=[],c=[],l=0,u=0,d=0,m=0,f=0,p=0,g=0,y=0,h=0,S=0,b=0,R=0,x=[],v=new Map,C=t.filter(I=>qe(I.relativePath)==="typescript"&&!n.has(I.symbolId)&&!r.has(I.symbolId)),w=Hm(e,C,I=>zr(e,I));if(w){h=C.length,S=w.cacheHits,b=w.cacheMisses,R=w.computedFiles;for(let I of C)n.set(I.symbolId,w.references.get(I.symbolId)??[])}if(D("semantic.references.cache-scan",()=>{for(let[I,P]of cc(t)){let _=[];for(let A of P)n.has(A.symbolId)?u+=1:r.has(A.symbolId)?y+=1:_.push(A);if(_.length===0){g+=1;continue}let se=Bj(e,o,I);if(!se){for(let A of _)qe(A.relativePath)||(l+=1),c.push(A);continue}p+=1;let ee=nh(e,I,se);for(let A of _){let ge=ee.get(A.symbol)??null;if(ge!==null){let pe=jj(ge);if(pe){d+=1,n.set(A.symbolId,pe);continue}m+=1}a.push({definition:A,cacheFingerprint:se})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:l,cacheHits:d,parseFailures:m,misses:a.length,unkeyed:c.length,inMemoryHits:u,incompleteInMemoryHits:y,fullyInMemoryFiles:g,cacheReadFiles:p})),a.length>0||c.length>0){x=[...c,...a.map(I=>I.definition)],v=D("semantic.references.compute-misses",()=>{let I=Um(e,x,i);return f=I.size,I},()=>({definitions:x.length,misses:a.length,unkeyed:c.length,rows:f}));for(let I of x)v.has(I.symbolId)?(n.set(I.symbolId,v.get(I.symbolId)??[]),r.delete(I.symbolId)):r.add(I.symbolId);for(let{definition:I,cacheFingerprint:P}of a)v.has(I.symbolId)&&bR(e,"semantic-references",I.relativePath).available&&s.push({relativePath:I.relativePath,symbol:I.symbol,projectFingerprint:P,payload:JSON.stringify(v.get(I.symbolId)??[])})}return s.length>0&&D("semantic.references.cache-write",()=>ih(e,s),()=>({entries:s.length})),v.size>0&&$m(e,x,v,I=>zr(e,I)),{definitions:t.length,inMemoryHits:u,incompleteInMemoryHits:y,cacheHits:d,misses:a.length,unkeyed:c.length,skippedUnsupportedLanguage:l,parseFailures:m,computed:f,incomplete:r.size,cacheWrites:s.length,fragmentDefinitions:h,fragmentCacheHits:S,fragmentCacheMisses:b,fragmentComputedFiles:R}}function Bj(e,t,n){if(!t)return null;let r=qe(n);return r==="typescript"?t:r==="rust"?ke(JSON.stringify({kind:"semantic-references",language:r,engine:Gr(e.config.projectRoot),projectFingerprint:t})):null}function Um(e,t,n={}){let r=W(),i=new Map,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=0,f=0;return D("semantic.references.provider-loop",()=>{let p=iR(e,t),g=fS(e,t),y=new Map,h=n.prefetchCallees?new Map:null,S=[];for(let R of t){let x,v=()=>(x??=on(e,R.relativePath),x);if(h){let P=v();if(P?.referencesAndCalleesForDefinitions){let _=h.get(P);_?_.push(R):h.set(P,[R]),f+=1}}let C=p.get(R.symbolId);if(C){a+=1,c+=C.length,us(i,R.symbolId,C,r,P=>{d+=1,m+=P});continue}let w=g.get(R.symbolId);if(w){l+=1,u+=w.length,us(i,R.symbolId,w,r,P=>{d+=1,m+=P});continue}let I=v();if(!I){r&&(s+=1);continue}if(r&&(o+=1),I.referencesForDefinitions){let P=y.get(I);P?P.push(R):y.set(I,[R])}else S.push({provider:I,definition:R})}let b=new Set;if(h)for(let[R,x]of h){if(!R.referencesAndCalleesForDefinitions)continue;let v=y.get(R)??[],C=R.referencesAndCalleesForDefinitions(v,x);b.add(R),Mj(e,C.callees);for(let w of v){if(!C.references.has(w.symbolId))continue;let I=C.references.get(w.symbolId)??[];us(i,w.symbolId,I,r,P=>{d+=1,m+=P})}}for(let[R,x]of y){if(b.has(R))continue;let v=R.referencesForDefinitions(x);for(let C of x){if(!v.has(C.symbolId))continue;let w=v.get(C.symbolId)??[];us(i,C.symbolId,w,r,I=>{d+=1,m+=I})}}for(let{provider:R,definition:x}of S){let v=R.referencesFor(x);us(i,x.symbolId,v,r,C=>{d+=1,m+=C})}return i},()=>({definitions:t.length,providerHits:o,providerMisses:s,rustDefaultFastPathRows:a,rustDefaultFastPathReferences:c,rustScipOccurrenceFastPathRows:l,rustScipOccurrenceFastPathReferences:u,prefetchCalleeDefinitions:f,definitionsWithReferences:d,referenceCount:m,rows:i.size}))}function us(e,t,n,r,i){e.set(t,n),r&&n.length>0&&i(n.length)}function qm(e,t,n,r){let i=0;for(let o of r){if(o.file===n.relativePath||e.isIgnored(o.file))continue;let s=t.get(n.symbolId);s||(s=new Set,t.set(n.symbolId,s));let a=s.size;s.add(o.file),s.size!==a&&(i+=1)}return i}function jj(e){try{return JSON.parse(e)}catch{return null}}function $c(e,t){return mt(e).calleeMap(t)}function $j(e,t){let n=W(),r=new Map,i=0,o=0,s=0,a=0;return D("semantic.callees.provider-loop",()=>{let c=new Map,l=[];for(let u of t){let d=on(e,u.relativePath);if(!d){n&&(o+=1);continue}n&&(i+=1);let m=u;if(d.calleesForDefinitions){let f=c.get(d);f?f.push(m):c.set(d,[m])}else l.push({provider:d,definition:m})}for(let[u,d]of c){let m=u.calleesForDefinitions(d);for(let f of d){let p=m.get(f.symbolId)??[];uR(r,f.symbolId,p,n,g=>{s+=1,a+=g})}}for(let{provider:u,definition:d}of l){let m=u.calleesFor(d);uR(r,d.symbolId,m,n,f=>{s+=1,a+=f})}return r},()=>({definitions:t.length,providerHits:i,providerMisses:o,definitionsWithCallees:s,calleeCount:a,rows:r.size}))}function uR(e,t,n,r,i){n.length>0&&(e.set(t,n),r&&i(n.length))}function gR(e,t){return mt(e).signature(t)}function Hj(e,t){if(qe(t.relativePath)==="typescript"){let s="fallback",a=0,c=0,l=0,u=0;return D("typescript.signature.materialize",()=>{let d=cr(e,t.relativePath,Lj);if(d?.key){a=1;let f=lR.read(e,t.relativePath,d.key)??{};if(Object.prototype.hasOwnProperty.call(f,t.symbol))return s="hit",c=1,f[t.symbol]??null;l=1;let p=on(e,t.relativePath);if(!p)return s="unavailable",null;let g=p.signatureFor(t);return lR.write(e,t.relativePath,d.key,{...f,[t.symbol]:g}),s="computed",g}u=1;let m=on(e,t.relativePath);return m?(s="direct-fallback",m.signatureFor(t)):(s="unavailable",null)},()=>({state:s,eligible:a,cacheHits:c,cacheMisses:l,fallbacks:u}))}let n=hR(e,"semantic-signatures",t.relativePath),r=Gj(t);if(n){let s=aR.read(e,r,n);if(s)return s.signature}let i=on(e,t.relativePath);if(!i)return null;let o=i.signatureFor(t);return n&&aR.write(e,r,n,{signature:o}),o}function hR(e,t,n){let r=We(e);if(!r)return null;let i=qe(n);return i!=="rust"?null:ke(JSON.stringify({kind:t,language:i,engine:Gr(e.config.projectRoot),projectFingerprint:r}))}function Gj(e){return`${e.relativePath}\0${e.symbol}`}function yR(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:null}catch{return null}}function qj(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 Uj(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 bR(e,t,n){let r=qe(n);if(!r)return{slot:t,language:"typescript",available:!1,reason:"semantic evidence is only available for TypeScript or Rust files"};try{return{slot:t,language:r,...zr(e,n).availability()}}catch(i){return{slot:t,language:r,available:!1,reason:i instanceof Error?i.message:String(i)}}}function on(e,t){if(!qe(t))return null;let n=zr(e,t);return n.availability().available?n:null}var q={references:jc,referenceMap:Um,callerMap:(e,t)=>mt(e).callerMap(t),calleeMap:Vm};function Vm(e,t){let n=W(),r=new Map,i=dR(e,t),o=[],s=[],a=0,c=0,l=0,u=0,d=0,m=0,f=0;for(let{definition:b,callees:R}of i.hits)d+=1,R.length>0&&(m+=1,f+=R.length,r.set(b.symbolId,R));let p=Vj(e,i.hits);if(p.entries.length>0&&D("semantic.callees.prefetch-cache-write",()=>vu(e,p.entries),()=>({entries:p.entries.length,sourceMissing:p.sourceMissing,skippedUnsupportedLanguage:p.skippedUnsupportedLanguage})),D("semantic.callees.cache-scan",()=>{for(let[b,R]of cc(i.misses)){if(!qe(b)){n&&(a+=R.length);continue}let x=k(e,b);if(!x){n&&(c+=R.length),s.push(...R);continue}let v=he(e,b,x),C=SR(e,b);if(!C){s.push(...R);continue}let w=th(e,b,v,C);for(let I of R){let P=w.get(I.symbol)??null;if(P!==null){let _=Wj(P);if(_){n&&(l+=1),_.length>0&&r.set(I.symbolId,_);continue}n&&(u+=1)}o.push({def:I,contentHash:v,depsDigest:C})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:a,sourceMissing:c,cacheHits:l,parseFailures:u,misses:o.length,unkeyed:s.length,inMemoryHits:d,inMemoryRows:m,inMemoryCalleeCount:f,resultRows:r.size})),o.length===0&&s.length===0)return r;let g=[...s,...o.map(b=>b.def)],y=0,h=D("semantic.callees.compute-misses",()=>{let b=$c(e,g);return y=b.size,b},()=>({definitions:g.length,misses:o.length,unkeyed:s.length,rows:y}));for(let[b,R]of h)r.set(b,R);let S=o.filter(b=>mt(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(h.get(b.def.symbolId)??[])}));return S.length>0?D("semantic.callees.cache-write",()=>vu(e,S),()=>({entries:S.length})):D("semantic.callees.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",misses:o.length})),r}function Vj(e,t){let n=[],r=new Map,i=0,o=0;for(let{definition:s,callees:a}of t){if(!qe(s.relativePath)){o+=1;continue}if(!r.has(s.relativePath)){let l=k(e,s.relativePath),u=l?SR(e,s.relativePath):null;r.set(s.relativePath,l&&u?{contentHash:he(e,s.relativePath,l),depsDigest:u}:null)}let c=r.get(s.relativePath);if(!c){i+=1;continue}n.push({relativePath:s.relativePath,symbol:s.symbol,contentHash:c.contentHash,depsDigest:c.depsDigest,payload:JSON.stringify(a)})}return{entries:n,sourceMissing:i,skippedUnsupportedLanguage:o}}var zj="typescript-callees-v1";function SR(e,t){let n=qe(t);if(n==="typescript")return cr(e,t,zj)?.key??null;let r=Jj(e,t);return n==="rust"?ke(JSON.stringify({kind:"semantic-callees",language:n,engine:Gr(e.config.projectRoot),positionMapping:"nearby-leaf-v1",depsDigest:r})):r}function Wj(e){try{return JSON.parse(e)}catch{return null}}var Kj=$("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function Jj(e,t){return Kj.get(e,t,()=>{let r=[...le(e).get(t)??[]].sort().map(i=>`${i}:${he(e,i,k(e,i))}`);return ke(r.join("|"))})}function zle(e,t,n={}){let r=G(e,t);if(!r)return[];let o=!ae(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine}]:[],s=nn(e,r,{semantic:n.semantic,semanticEvidence:q}).map(u=>({relativePath:u.file,line:u.line})),a=Yj(e,r),c=new Set,l=[];for(let u of[...o,...s,...a]){let d=`${u.relativePath}:${u.line}`;c.has(d)||(c.add(d),l.push(u))}return l}function Yj(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=Xj(t.symbol);if(n.length===0)return[];let r=[];for(let i of L(e,{extensions:[".rb"],includeIgnored:!1})){let o=k(e,i);if(!o)continue;let s=o.split(`
|
|
327
|
+
`);for(let a=0;a<s.length;a++){let c=s[a]??"";n.some(l=>new RegExp(`@${l}\\b|\\b${l}:`).test(c))&&r.push({relativePath:i,line:a})}}return r}function Xj(e){let n=(e.split(":").pop()??e).replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),r=n.split("_").filter(Boolean),i=new Set;return n&&i.add(n),r.length>=1&&i.add(r[r.length-1]),r.length>=2&&i.add(r.slice(-2).join("_")),[...i]}import{existsSync as Qj}from"fs";import{isAbsolute as Zj,join as e$}from"path";function it(e,t){let n=xR(e,t,{allowMultiple:!1})[0]?.relativePath;return n||t$(e,t)}function Vi(e,t){return xR(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function t$(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=Zj(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=e$(e.config.projectRoot,r);return Qj(i)?r:null}function xR(e,t,n){let r=Ta(e,t,n);if(r.length===0){let i=G(e,t);return!i||e.isIgnored(i.relativePath)?[]:[{relativePath:i.relativePath,score:700}]}return r}function nue(e,t){let n=Vi(e,t),r=Ya(e,n,{sort:!0});if(r.length===0)return[];let i=r.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 i)o.set(a.symbol,a);let s=[];for(let a=0;a<r.length;a++){let c=r[a],l=i[a];if(c.enclosingSymbol&&o.has(c.enclosingSymbol)){o.get(c.enclosingSymbol).children.push(l);continue}let u=null,d=1/0;for(let m of i)if(m!==l&&m.startLine<=l.startLine&&m.endLine>=l.endLine){if(m.startLine===l.startLine&&m.endLine===l.endLine&&!Ih(m.symbol,l.symbol))continue;let p=m.endLine-m.startLine;p<d&&(d=p,u=m)}u?u.children.push(l):s.push(l)}return s}import{extname as n$}from"path";function due(e,t,n={}){let{context:r=0}=n,i=r$(t);if(i)return o$(e,i.filePath,i.startLine,i.endLine,r);let o=G(e,t);return o?i$(e,o,r):null}function r$(e){let t=e.match(/^(.+\.\w+):(\d+)-(\d+)$/);if(!t)return null;let n=Number(t[2]),r=Number(t[3]);if(!Number.isSafeInteger(n)||n<1)throw new RangeError(`Source range start line must be a positive integer, got "${t[2]}".`);if(!Number.isSafeInteger(r)||r<n)throw new RangeError(`Source range end line must be an integer at or after ${n}, got "${t[3]}".`);return{filePath:t[1],startLine:n,endLine:r}}function i$(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i;try{i=de(e.config.projectRoot,t.relativePath,{inputKind:"indexed source file"})}catch(l){if(!we(l))throw l;return null}let o=i.split(`
|
|
328
|
+
`),s=Math.max(0,t.startLine-n),a=Math.min(o.length-1,t.endLine+n),c=o.slice(s,a+1).join(`
|
|
329
|
+
`);return{symbol:t.symbol,shortName:E(t.symbol),relativePath:t.relativePath,startLine:s,endLine:a,language:r?.language??RR(t.relativePath),source:c}}function o$(e,t,n,r,i){let o=it(e,t);if(!o)return null;let s=e.get("SELECT relative_path, language FROM documents WHERE relative_path = ?",o);if(!s)return null;let a;try{a=de(e.config.projectRoot,s.relative_path,{inputKind:"indexed source file"})}catch(m){if(!we(m))throw m;return null}let c=a.split(`
|
|
330
|
+
`),l=Math.max(0,n-1-i),u=Math.min(c.length-1,r-1+i),d=c.slice(l,u+1).join(`
|
|
331
|
+
`);return{symbol:`${s.relative_path}:${n}-${r}`,shortName:`${s.relative_path}:${n}-${r}`,relativePath:s.relative_path,startLine:l,endLine:u,language:s.language??RR(s.relative_path),source:d}}function RR(e){switch(n$(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}}import{createRequire as s$}from"module";var a$=s$(import.meta.url),wt=c$().version;function c$(){for(let e of["../package.json","../../package.json"])try{return a$(e)}catch{}return{version:"0.0.0"}}import{existsSync as Bf,statSync as nG}from"fs";import{join as rG}from"path";import{createHash as Km,randomUUID as l$}from"crypto";import{chmodSync as IR,existsSync as zi,linkSync as u$,lstatSync as Gc,readdirSync as Jm,realpathSync as Nt,unlinkSync as d$,writeSync as m$}from"fs";import{homedir as f$}from"os";import{basename as p$,dirname as qc,isAbsolute as CR,join as Et,resolve as Uc}from"path";var wR=1,fs=".scip-query-cache-owner.json",g$=16*1024,ER=Object.freeze({...$r,randomToken:()=>l$(),linkFile:(e,t)=>u$(e,t),removeFile:e=>d$(e),writeFile:(e,t,n,r)=>m$(e,t,n,r)});function Hc(e,t){return Object.assign(new Error(`refusing unsafe project dbPath ${JSON.stringify(e)} (${t}); use a repository-relative directory that remains inside the checkout`),{name:"UnsafeCachePathError",code:"SCIP_QUERY_UNSAFE_CACHE_PATH",configuredPath:e,reason:t})}function Vt(e,t){return Object.assign(new Error(`refusing unowned cache directory ${JSON.stringify(e)} (${t}); move unrelated data elsewhere or choose a new empty dbPath`),{name:"CacheOwnershipError",code:"SCIP_QUERY_CACHE_OWNERSHIP",cacheDir:e,reason:t})}function h$(e,t){let n=Nt(e),r=process.env.SCIP_QUERY_CACHE_DIR;return r?zm(n,Uc(r)):t?.dbPath?zm(n,b$(n,t.dbPath)):zm(n,Vc(n))}function DR(){let e=process.env.XDG_CACHE_HOME;return Et(e||Et(f$(),".cache"),"scip-query")}function Vc(e){let t=Uc(e);try{t=Nt(t)}catch{}let n=Km("sha256").update(t).digest("hex").slice(0,12);return Et(DR(),"projects",n)}function ps(e){if(!/^[a-f0-9]{24}$/.test(e))throw new Error(`invalid repository cache identity: ${e}`);let t=Et(DR(),"repositories",e);return FR(t),Nt(t)}function Ym(e){return process.env.SCIP_QUERY_SHARED_CACHE!=="0"&&!process.env.SCIP_QUERY_CACHE_DIR&&!process.env.SCIP_QUERY_INDEX_DB&&!e?.dbPath}function PR(e,t){let n=h$(e,t);return{cacheDir:n,dbPath:Et(n,"index.db"),indexPath:Et(n,"index.scip"),metaPath:Et(n,"meta.json")}}function zm(e,t,n=ER){return y$(e,t,n).cacheDir}function y$(e,t,n=ER){let r=Nt(e),i=zi(t)?"synced":FR(t,n),o=Nt(t),s=Et(o,fs);if(zi(s))return Wm(r,o),Xm(s),ms(o),{kind:"existing",cacheDir:o};vR(o),C$(o),vR(o);let c=`${JSON.stringify({schemaVersion:wR,canonicalProjectRoot:r,canonicalCacheDir:o,creatorVersion:wt},null,2)}
|
|
332
|
+
`;try{let l=v$(s,c,n),u=Be(i,l);return{kind:"published",cacheDir:o,achievedDurability:u==="synced"?"directory-durable":"file-flushed",directorySync:u}}catch(l){if(I$(l))return Wm(r,o),{kind:"existing",cacheDir:o};throw l}}function Wm(e,t){let n=Nt(e),r=Nt(t);return kR(r,n,r)}function Iue(e,t,n,r){let i=Nt(e),o=Nt(t),s=_R(n),a=kR(o,i,s);if(r&&a.ownerSha256!==r)throw Vt(t,"ownership record changed after the cache was moved");return a}function wue(e,t){return zi(Et(t,fs))?(Wm(e,t),TR(t),!0):!1}function b$(e,t){let n;try{n=ht(t)}catch(s){throw s instanceof Ze?Hc(t,s.reason):s}let r=Uc(e,...n.split("/"));if(r===e||!fi(e,r))throw Hc(t,"outside-project");let i=S$(r),o=Nt(i);if(!fi(e,o)&&o!==e)throw Hc(t,"symlink-escape");return r}function S$(e){let t=e;for(;!zi(t);){let n=qc(t);if(n===t)throw Hc(e,"no-existing-ancestor");t=n}return t}function kR(e,t,n){let r=Et(e,fs);if(!zi(r)||Gc(r).isSymbolicLink())throw Vt(e,"missing regular ownership record");let i=Gc(r);if(!i.isFile()||i.size>g$)throw Vt(e,"invalid ownership record file");let o=O(r,"cache ownership record"),s=x$(o,e);if(s.canonicalProjectRoot!==t)throw Vt(e,"ownership record belongs to a different project");if(s.canonicalCacheDir!==n)throw Vt(e,"ownership record names a different cache directory");return{record:s,ownerSha256:Km("sha256").update(o).digest("hex"),physicalCacheDir:e}}function x$(e,t){try{let n=JSON.parse(e);if(n.schemaVersion!==wR||typeof n.canonicalProjectRoot!="string"||typeof n.canonicalCacheDir!="string"||typeof n.creatorVersion!="string"||!CR(n.canonicalProjectRoot)||!CR(n.canonicalCacheDir))throw new Error("invalid fields");return n}catch(n){throw Vt(t,`malformed ownership record: ${n instanceof Error?n.message:String(n)}`)}}function vR(e){let t=Jm(e).filter(n=>n!==fs&&!R$(n));if(t.length>0)throw Vt(e,`unrecognized existing entries: ${t.slice(0,3).join(", ")}`)}function R$(e){return e.startsWith(`${fs}.tmp-`)||[".scipquery-generations","affected-shadow-latest.json","affected-shadow.jsonl","agent-hooks","augment-vue-meta.json","cache-lifecycle.lock","evidence.db","evidence.db-shm","evidence.db-wal","health-report-cache.json","index.db","index.db-shm","index.db-wal","index.lock","index.scip","language-indexes","meta.json","reindex-activity.jsonl","shared-cache.json","typescript-index","typescript-scip-fragments","typescript-scip-overlays","typescript-semantic","watch-activity.json","watch-refresh-requests","watch-state.json","watch.lock"].includes(e)?!0:/^(?:reindex-|rust-|typescript-)/.test(e)}function C$(e){for(let t of Jm(e)){let n=Et(e,t),r=Gc(n);if(r.isSymbolicLink())throw Vt(e,`legacy cache entry ${t} is a symlink`);if(r.isDirectory())ms(n);else if(r.isFile())Xm(n);else throw Vt(e,`legacy cache entry ${t} is not a file or directory`)}ms(e)}function TR(e){let t=Gc(e);if(t.isSymbolicLink())throw Vt(e,"managed cache tree contains a symlink");if(t.isFile()){Xm(e);return}if(!t.isDirectory())throw Vt(e,"managed cache tree contains a special file");ms(e);for(let n of Jm(e))TR(Et(e,n))}function FR(e,t=$r){let n=dt(e,t);return ms(e),n}function v$(e,t,n){let r=`${e}.tmp-${process.pid}-${n.randomToken()}`,i,o=!1;try{i=n.openFile(r,"wx",384),o=!0,jr(i,Buffer.from(t),n,"cache ownership record"),n.syncFile(i),n.closeFile(i),i=void 0,n.linkFile(r,e);let s=ce(qc(e),n);return n.removeFile(r),o=!1,Be(s,ce(qc(e),n))}finally{if(i!==void 0)try{n.closeFile(i)}catch{}if(o)try{n.removeFile(r)}catch{}}}function ms(e){process.platform!=="win32"&&IR(e,448)}function Xm(e){process.platform!=="win32"&&IR(e,384)}function _R(e){if(zi(e))return Nt(e);let t=Nt(qc(e));return Et(t,p$(e))}function Eue(e){let t=zc(e);return Km("sha256").update(t).digest("hex")}function zc(e){return _R(Uc(e))}function I$(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}import w$ from"better-sqlite3";var E$=["busy_timeout = 5000","query_only = ON","temp_store = MEMORY","cache_size = -64000","mmap_size = 268435456"],Qm=class{constructor(t,n){this.connection=t;this.releaseGenerationReader=n}connection;releaseGenerationReader;active=!0;initialize(t){try{for(let n of E$)this.connection.pragma(n);t(this.connection)}catch(n){try{this.close()}catch(r){throw new AggregateError([n,r],"SQLite initialization and rollback both failed.",{cause:r})}throw n}}close(){if(!this.active)return;this.active=!1;let t,n;try{this.connection.close()}catch(r){t=r}try{this.releaseGenerationReader()}catch(r){n=r}if(t!==void 0&&n!==void 0)throw new AggregateError([t,n],"SQLite connection close and generation-reader release both failed.");if(t!==void 0)throw t;if(n!==void 0)throw n}},D$=["node_modules",".git","dist","build","out","coverage","target",".next",".nuxt",".cache",".turbo",".nbb",".cpcache",".shadow-cljs",".scipquery-cache","__pycache__",".venv","venv"],Wc=class{db;config;generation;pathFilter;connection;connectionOwnership;statementCache=new Map;constructor(t,n){this.config=t,this.pathFilter=n??null;let r=F$(t),i=new Qm(r.db,r.release);try{i.initialize(T$),this.generation=r.generation,this.connection=r.db,this.connectionOwnership=i,this.db=P$(r.db)}catch(o){try{i.close()}catch(s){throw new AggregateError([o,s],"SQLite construction and rollback both failed.",{cause:s})}throw o}}isIgnored(t){return this.pathFilter?.isIgnored(t)??!1}get localSymbolPredicate(){return`(
|
|
333
|
+
EXISTS (
|
|
334
|
+
SELECT 1
|
|
335
|
+
FROM defn_enclosing_ranges local_der
|
|
336
|
+
JOIN documents local_d ON local_der.document_id = local_d.id
|
|
337
|
+
WHERE local_der.symbol_id = gs.id
|
|
338
|
+
${this.pathExclusionsFor("local_d").trimStart()}
|
|
339
|
+
)
|
|
340
|
+
OR EXISTS (
|
|
341
|
+
SELECT 1
|
|
342
|
+
FROM mentions local_m
|
|
343
|
+
JOIN chunks local_c ON local_m.chunk_id = local_c.id
|
|
344
|
+
JOIN documents local_d ON local_c.document_id = local_d.id
|
|
345
|
+
WHERE local_m.symbol_id = gs.id
|
|
346
|
+
AND local_m.role = 1
|
|
347
|
+
${this.pathExclusionsFor("local_d").trimStart()}
|
|
348
|
+
)
|
|
349
|
+
)`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>D$.flatMap(r=>[`AND ${n}.relative_path NOT LIKE '${r}/%'`,`AND ${n}.relative_path NOT LIKE '%/${r}/%'`])).join(`
|
|
350
|
+
`)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.statement(t).all(...n)}get(t,...n){return this.statement(t).get(...n)}close(){this.statementCache.clear(),this.connectionOwnership.close()}statement(t){let n=this.statementCache.get(t);return n||(n=this.connection.prepare(t),this.statementCache.set(t,n)),n}};function P$(e){return Object.freeze({prepare(t){let n=e.prepare(t);if(!n.readonly||!n.reader)throw new Error("ScipDatabase.db only permits read-only statements that return rows.");return k$(n)}})}function k$(e){let t={get:(...n)=>e.get(...n),all:(...n)=>e.all(...n),iterate:(...n)=>e.iterate(...n),pluck(n){return n===void 0?e.pluck():e.pluck(n),t},expand(n){return n===void 0?e.expand():e.expand(n),t},raw(n){return n===void 0?e.raw():e.raw(n),t},bind(...n){return e.bind(...n),t},columns:()=>e.columns(),safeIntegers(n){return n===void 0?e.safeIntegers():e.safeIntegers(n),t}};return Object.freeze(t)}function T$(e){if(!e.prepare("SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = 'documents'").get())return;let n=e.prepare("SELECT relative_path FROM documents").iterate();for(let r of n)ht(r.relative_path)}function F$(e){for(let t=0;t<4;t+=1){let n=Kx(e),r=n.generation,i;try{i=new w$(r.databasePath,{readonly:!0,fileMustExist:!0})}catch(o){throw n.release(),o}if(r.source==="immutable")return{db:i,generation:r,release:n.release};try{let o=Nm(e);if(r.databaseFileIdentity===Fn(r.databasePath)&&o.source==="legacy"&&o.identity===r.identity&&o.databaseFileIdentity===r.databaseFileIdentity&&o.metadataRaw===r.metadataRaw)return{db:i,generation:r,release:n.release}}catch(o){throw i.close(),n.release(),o}i.close(),n.release()}throw new Error("SQLite index publication changed repeatedly while opening a coherent generation.")}import _$ from"ignore";import{existsSync as AR,readdirSync as A$}from"fs";import{dirname as Zm,isAbsolute as LR,join as Kc,relative as L$,resolve as M$}from"path";function MR(e){let t=_$();return N$(e,t)||t.add(j$),{isIgnored:r=>ef(t,e,r),filter:r=>r.filter(i=>!ef(t,e,i))}}function N$(e,t){let n=new Set,r=(s,a)=>{if(!(n.has(s)||!AR(s)))try{let c=J(s,{maxBytes:Ie,inputKind:"gitignore file"});t.add(a?O$(c,a):c),n.add(s)}catch{}},i=Zm(e),o=0;for(;i!==Zm(i)&&o<5&&(r(Kc(i,".gitignore"),""),!AR(Kc(i,".git")));)i=Zm(i),o++;return NR(e,"",t,r),n.size>0}function NR(e,t,n,r){let i=t?Kc(e,t):e;r(Kc(i,".gitignore"),t);let o;try{o=A$(i,{withFileTypes:!0})}catch{return}for(let s of o){if(!s.isDirectory()||s.name===".git")continue;let a=t?`${t}/${s.name}`:s.name;ef(n,e,`${a}/`)||NR(e,a,n,r)}}function O$(e,t){let n=t.replaceAll("\\","/").replace(/\/+$/,"");return e.split(/\r?\n/).map(r=>B$(r,n)).join(`
|
|
351
|
+
`)}function B$(e,t){let n=e.trimStart();if(!n||n.startsWith("#"))return e;let r=e.slice(0,e.length-n.length),i=n.startsWith("!"),o=i?n.slice(1):n;if(!o||o.startsWith("#"))return e;let s=o.startsWith("/"),a=s?o.slice(1):o,u=(a.endsWith("/")?a.slice(0,-1):a).includes("/")||s?`${t}/${a}`:`${t}/**/${a}`;return`${r}${i?"!":""}${u}`}var j$=`
|
|
352
|
+
# Dependencies
|
|
353
|
+
node_modules/
|
|
354
|
+
vendor/
|
|
355
|
+
.bundle/
|
|
356
|
+
|
|
357
|
+
# Build output
|
|
358
|
+
dist/
|
|
359
|
+
build/
|
|
360
|
+
out/
|
|
361
|
+
target/
|
|
362
|
+
bin/
|
|
363
|
+
obj/
|
|
364
|
+
|
|
365
|
+
# Python
|
|
366
|
+
__pycache__/
|
|
367
|
+
*.pyc
|
|
368
|
+
*.pyo
|
|
369
|
+
.venv/
|
|
370
|
+
venv/
|
|
371
|
+
.env/
|
|
372
|
+
env/
|
|
373
|
+
*.egg-info/
|
|
374
|
+
|
|
375
|
+
# Rust
|
|
376
|
+
target/
|
|
377
|
+
|
|
378
|
+
# Java / Kotlin / Scala
|
|
379
|
+
*.class
|
|
380
|
+
.gradle/
|
|
381
|
+
.mvn/
|
|
382
|
+
|
|
383
|
+
# C# / .NET
|
|
384
|
+
bin/
|
|
385
|
+
obj/
|
|
386
|
+
packages/
|
|
387
|
+
|
|
388
|
+
# Go
|
|
389
|
+
vendor/
|
|
390
|
+
|
|
391
|
+
# Dart
|
|
392
|
+
.dart_tool/
|
|
393
|
+
build/
|
|
394
|
+
|
|
395
|
+
# PHP
|
|
396
|
+
vendor/
|
|
397
|
+
|
|
398
|
+
# IDE / OS
|
|
399
|
+
.idea/
|
|
400
|
+
.vscode/
|
|
401
|
+
*.swp
|
|
402
|
+
*.swo
|
|
403
|
+
.DS_Store
|
|
404
|
+
Thumbs.db
|
|
405
|
+
|
|
406
|
+
# Type definitions (often noise in queries)
|
|
407
|
+
*.d.ts
|
|
408
|
+
`;function ef(e,t,n){let r=$$(t,n);if(!r)return!1;try{return e.ignores(r)}catch{return!1}}function $$(e,t){if(!t||t===".")return null;if(!LR(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=LR(t)?t:M$(e,t),r=L$(e,n).replaceAll("\\","/");return!r||r==="."||r.startsWith("..")?null:r}import{existsSync as Wr}from"fs";import{isAbsolute as VR,join as mr,relative as zR,resolve as WR}from"path";var ur=1,dr=2,H$="./node_modules/scip-query/docs/schemas/project-config.schema.json";function tf(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(a){return{kind:"malformed",reason:`invalid JSON: ${a instanceof Error?a.message:String(a)}`}}if(!V(t))return{kind:"malformed",reason:"project config must be a JSON object"};let n=t.schemaVersion;if(n!==void 0&&!Number.isInteger(n))return{kind:"malformed",reason:"schemaVersion must be an integer"};let r=n===void 0?ur:n;if(r!==ur&&r!==dr)return{kind:"unsupported",schemaVersion:r,direction:r<ur?"older":"future"};let i=t.$schema;if(i!==void 0&&(typeof i!="string"||i.trim()===""))return{kind:"malformed",reason:"$schema must be a non-empty string when present"};let o=Jc(t),s=r!==dr||typeof t.$schema!="string";return r===ur?{kind:"legacy",sourceVersion:ur,config:o,needsMigration:s}:{kind:"supported",sourceVersion:dr,config:o,needsMigration:s}}function Jc(e){let t=e,{$schema:n,schemaVersion:r,...i}=t;return{$schema:typeof n=="string"&&n.trim()!==""?n:H$,schemaVersion:dr,...i}}function OR(e){return`${JSON.stringify(Jc(e),null,2)}
|
|
409
|
+
`}function BR(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.schemaVersion===1&&(t.authorityKind==="index-worktree"||t.authorityKind==="index-only"||t.authorityKind==="worktree-only"||t.authorityKind==="process-local")&&typeof t.observedAt=="string"&&!Number.isNaN(Date.parse(t.observedAt))&&gs(t.projectIdentity)&&(t.index===void 0||gs(t.index.generationIdentity)&&(t.index.source==="immutable"||t.index.source==="legacy")&&(t.index.alignment==="not-certified"||t.index.alignment==="leased"))&&(t.worktree===void 0||gs(t.worktree.identity)&&typeof t.worktree.clean=="boolean"&&(t.worktree.headCommit===void 0||gs(t.worktree.headCommit))&&(t.worktree.treeOid===void 0||gs(t.worktree.treeOid)))&&G$(t)}function G$(e){return e.authorityKind==="index-worktree"?e.index!==void 0&&e.worktree!==void 0:e.authorityKind==="index-only"?e.index!==void 0&&e.worktree===void 0:e.authorityKind==="worktree-only"?e.index===void 0&&e.worktree!==void 0:e.authorityKind==="process-local"&&e.index===void 0&&e.worktree===void 0}function gs(e){return typeof e=="string"&&e.length>0&&e.length<=256&&!/[\0\r\n]/u.test(e)}var q$=100,U$=25,V$=.9;function Yc(e,t){return e>q$||t>=U$&&e/t>V$}function Xc(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.kind==="automated-adjudication"&&t.policyVersion===1&&(t.decidedBy==="agent"||t.decidedBy==="human")&&gu.includes(t.reasonCode)&&Array.isArray(t.evidence)&&t.evidence.length>0&&t.evidence.every(J$)&&(t.observation===void 0||BR(t.observation))&&!!t.invalidateOn&&typeof t.invalidateOn=="object"&&typeof t.invalidateOn.targetContentChange=="boolean"&&typeof t.invalidateOn.detectorMajorChange=="boolean"}function jR(e,t,n){if(e.expiresAt&&Date.parse(e.expiresAt)<=n.now)return{kind:"expired",reasons:["suppression-expired"]};let r=[];e.id!==t.id&&r.push("exact-finding-id-required");let i=e.decision;if(!i)return{kind:"escalated",reasons:[...r,"legacy-unadjudicated"]};i.kind!=="automated-adjudication"&&r.push("unsupported-decision-kind"),i.policyVersion!==1&&r.push("unsupported-policy-version"),gu.includes(i.reasonCode)||r.push("unsupported-reason-code"),i.evidence.length===0&&r.push("counterevidence-required"),i.invalidateOn.detectorMajorChange||r.push("detector-change-invalidation-required");let o=i.evidence.filter(z$);i.invalidateOn.targetContentChange&&o.length===0&&r.push("content-invalidation-evidence-required");let s=[];for(let a of o){if(!a.contentHash){r.push(`counterevidence-content-hash-required:${a.referent}`);continue}let c=n.contentHash(a.referent);(!c||c!==a.contentHash)&&s.push(`counterevidence-content-changed:${a.referent}`)}return s.length>0?{kind:"invalidated",reasons:s}:(K$(t)&&!i.evidence.some(W$)&&r.push("direct-counterevidence-required"),r.length===0?{kind:"accepted"}:{kind:"escalated",reasons:[...new Set(r)]})}function z$(e){return e.kind==="source"||e.kind==="config"||e.kind==="test"}function W$(e){return e.kind==="source"||e.kind==="config"||e.kind==="graph"}function K$(e){return e.actionTier==="direct"||e.evidence==="graph-fact"||e.evidence==="change-graph"||e.evidence==="baseline"}function J$(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return(t.kind==="source"||t.kind==="config"||t.kind==="test"||t.kind==="graph")&&typeof t.referent=="string"&&t.referent.trim()!==""&&typeof t.claim=="string"&&t.claim.trim()!==""&&(t.contentHash===void 0||/^[a-f0-9]{64}$/u.test(t.contentHash))&&(t.generation===void 0||typeof t.generation=="string"&&t.generation.length>0)}var Qc=class extends Error{constructor(n,r,i){super(`${n} is ${r} characters; the safety limit is ${i} characters`);this.inputKind=n;this.observedCharacters=r;this.limitCharacters=i;this.name="RegExpPatternBudgetError"}inputKind;observedCharacters;limitCharacters;code="SCIP_QUERY_REGEXP_PATTERN_BUDGET"};function hs(e,t,n,r=4096){if(!Number.isSafeInteger(r)||r<0)throw new RangeError(`maxCharacters must be a non-negative safe integer; received ${r}`);if(e.length>r)throw new Qc(t,e.length,r);return new RegExp(e,n)}import{createHash as $R}from"crypto";import{closeSync as Y$,fstatSync as HR,openSync as X$,rmSync as Q$}from"fs";import{dirname as Z$}from"path";var e1=2e3,t1=10,n1=3,el=class extends Error{constructor(n,r,i){super(`Concurrent edit detected for ${n}; expected revision ${qR(r)}, but found ${qR(i)}. The latest file was left untouched.`);this.path=n;this.original=r;this.latest=i;this.name="FileRevisionConflictError"}path;original;latest},ys=class extends Error{constructor(n,r){super(`Concurrent edit detected for ${n}: ${r} changed since it was read. The latest file was left untouched; reload it and retry.`);this.path=n;this.field=r;this.name="FileContentConflictError"}path;field};function tl(e,t,n={}){let r=r1(e,n.lockTimeoutMs??e1,n.monotonicNow??Ae);try{let i=Math.max(0,Math.floor(n.maxRetries??n1));for(let o=0;;o+=1){let s=Zc(e),a=t(s,o);if(a.kind==="unchanged")return{changed:!1,attempts:o+1,previous:s,current:s};n.onBeforeCommit?.({attempt:o,snapshot:s,mutation:a});let c=Zc(e);if(!o1(s.revision,c.revision)){if(o<i)continue;throw new el(e,s.revision,c.revision)}try{i1(e,a,s.revision)}catch(l){if(l.code==="EEXIST"){let u=Zc(e);if(o<i)continue;throw new el(e,s.revision,u.revision)}throw l}return{changed:!0,attempts:o+1,previous:s,current:Zc(e)}}}finally{r.release()}}function Zc(e){for(let t=0;t<4;t+=1){let n;try{n=X$(e,"r");let r=GR(HR(n)),i=Ou(n,{maxBytes:He,inputKind:"revisioned text file"}),o=GR(HR(n));if(!UR(r,o))continue;return{path:e,text:i,revision:{exists:!0,hash:$R("sha256").update(i).digest("hex"),identity:o}}}catch(r){if(r.code==="ENOENT")return{path:e,text:"",revision:{exists:!1,hash:$R("sha256").update("").digest("hex")}};throw r}finally{n!==void 0&&Y$(n)}}throw new Error(`Could not read a stable revision of ${e}; the file is changing continuously.`)}function r1(e,t,n){let r=`${e}.scip-query-write.lock`,i=n()+Math.max(0,t);for(;;){let o=Gi(r,{kind:"revisioned-file-mutation",detail:{target:e}});if(o.kind==="acquired")return o.lock;if(n()>=i)throw new Error(`Timed out after ${t}ms waiting to update ${e}; the file was left untouched.`);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t1)}}function i1(e,t,n){if(t.kind==="delete"){if(!n.exists)return;Q$(e),ce(Z$(e));return}let r=t.mode??n.identity?.mode;n.exists?Go(e,t.text,{durability:"durable",mode:r}):qo(e,t.text,{durability:"durable",mode:r})}function o1(e,t){return e.exists===t.exists&&e.hash===t.hash&&(e.identity===void 0?t.identity===void 0:t.identity!==void 0&&UR(e.identity,t.identity))}function GR(e){return{dev:e.dev,ino:e.ino,size:e.size,mtimeMs:e.mtimeMs,mode:e.mode&511}}function UR(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.mode===t.mode}function qR(e){return e.exists?e.hash.slice(0,12):"<absent>"}var Kr=".scipquery.json",YR=250,XR=5e3,QR=10*6e4,s1={enabled:!1,debounceMs:YR,cooldownMs:XR,gitPollMs:2e3,idleTimeoutMs:QR,autoRefresh:!0,ignore:[]};var a1=new Set(["$schema","schemaVersion","languages","indexerConcurrency","watch","hooks","indexer","dbPath","entryRoots","semantic","suppressions","declaredCouplings","locality","architecture","coverageContracts","docs"]),c1=new Set(["enabled","debounceMs","cooldownMs","gitPollMs","idleTimeoutMs","autoRefresh","ignore"]),l1=new Set(["router"]),u1=new Set(["pathPrefixes","files","symbolPatterns","qualifiedVars"]),d1=new Set(["typescript","rust"]),m1=new Set(["tsconfigs"]),f1=new Set(["rustAnalyzerPath"]),KR=new Set(yo),p1=new Set(["pnpmWorkspaces","projectMode","projects","configPath"]),g1=new Set(["architecturalBoundarySegments"]),h1=new Set(["boundaries","allowedDependencies","requireCompletePolicy","requireAcyclic","requireResolvedBoundaries","requireMinimalPolicy","maxBoundaryFanOut","maxBoundaryFiles","testPaths"]),y1=new Set(["name","paths","subUnits","maxFiles"]),b1=new Set(["snapshotPaths"]),S1=new Set(["name","files","reason"]),x1=new Set(["id","check","file","reason","expiresAt","createdAt","decision"]),R1=new Set(["kind","reasonCode","decidedBy","policyVersion","observation","evidence","invalidateOn"]),C1=new Set(["kind","referent","claim","contentHash","generation"]),v1=new Set(["targetContentChange","detectorMajorChange"]),I1=new Set(["name","file","keys","mustEqual","allowExtra"]),w1=new Set(["type","identifier","marker"]),E1=new Set(["type","path","pattern"]),D1=new Set(["object-literal-keys","string-array","markdown-list"]),P1=new Set(["top-level-dirs","file-glob","registered-commands","builtin-skills"]);function ZR(e){let t=mr(e,Kr);if(!Wr(t))return{};let n;try{n=J(t,{maxBytes:Ie,inputKind:"scip-query project config"})}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`unable to read ${Kr} at ${t}: ${i}`,{cause:r})}return nC(tf(n),t,"read").config}function ude(e,t={}){let n=[];A1(e,n);let r=e;r.schemaVersion!==void 0&&r.schemaVersion!==dr&&n.push({level:"error",path:"schemaVersion",message:`Must be ${dr}; unversioned and v${ur} files are migrated while loading.`}),r.$schema!==void 0&&(typeof r.$schema!="string"||r.$schema.trim()==="")&&n.push({level:"error",path:"$schema",message:"Must be a non-empty string."});let i=new Set(yo);for(let[l,u]of(e.languages??[]).entries())i.has(u)||n.push({level:"error",path:`languages[${l}]`,message:`Unsupported language: ${u}`});for(let[l,u]of(e.entryRoots?.symbolPatterns??[]).entries())try{hs(u,`entryRoots.symbolPatterns[${l}]`)}catch(d){n.push({level:"error",path:`entryRoots.symbolPatterns[${l}]`,message:d instanceof Error?d.message:String(d)})}e.indexerConcurrency!==void 0&&(!Number.isInteger(e.indexerConcurrency)||e.indexerConcurrency<=0)&&n.push({level:"error",path:"indexerConcurrency",message:"Must be a positive integer."}),e.watch?.debounceMs!==void 0&&e.watch.debounceMs<=0&&n.push({level:"error",path:"watch.debounceMs",message:"Must be greater than 0."}),e.watch?.cooldownMs!==void 0&&(!Number.isInteger(e.watch.cooldownMs)||e.watch.cooldownMs<0)&&n.push({level:"error",path:"watch.cooldownMs",message:"Must be a non-negative integer; 0 disables cooldown spacing."}),e.watch?.gitPollMs!==void 0&&e.watch.gitPollMs<=0&&n.push({level:"error",path:"watch.gitPollMs",message:"Must be greater than 0."}),e.watch?.idleTimeoutMs!==void 0&&(!Number.isInteger(e.watch.idleTimeoutMs)||e.watch.idleTimeoutMs<0)&&n.push({level:"error",path:"watch.idleTimeoutMs",message:"Must be a non-negative integer; 0 disables idle shutdown."}),e.watch?.autoRefresh!==void 0&&typeof e.watch.autoRefresh!="boolean"&&n.push({level:"error",path:"watch.autoRefresh",message:"Must be a boolean."}),e.hooks?.router!==void 0&&e.hooks.router!=="off"&&e.hooks.router!=="single"&&n.push({level:"error",path:"hooks.router",message:'Must be "off" or "single".'});let o=e.indexer?.typescript;if(o?.projectMode!==void 0&&o.projectMode!=="single"&&o.projectMode!=="workspace"&&n.push({level:"error",path:"indexer.typescript.projectMode",message:'Must be "single" or "workspace".'}),o?.projects!==void 0)if(!Array.isArray(o.projects))n.push({level:"error",path:"indexer.typescript.projects",message:"Must be an array."});else for(let[l,u]of o.projects.entries()){let d=`indexer.typescript.projects[${l}]`;if(typeof u!="string"||u.trim()==="")n.push({level:"error",path:d,message:"Project path must be a non-empty string."});else if(t.projectRoot){let m=WR(t.projectRoot,u),f=zR(t.projectRoot,m);f.startsWith("..")||VR(f)?n.push({level:"error",path:d,message:"Project path must stay inside the project root."}):Wr(m)||n.push({level:"warning",path:d,message:`TypeScript project path does not exist: ${u}`})}}o?.projectMode==="workspace"&&o.pnpmWorkspaces===!0&&n.push({level:"warning",path:"indexer.typescript.pnpmWorkspaces",message:'Ignored when projectMode is "workspace"; explicit TypeScript projects are indexed directly.'});let s=e.semantic?.rust;s?.rustAnalyzerPath!==void 0&&(typeof s.rustAnalyzerPath!="string"||s.rustAnalyzerPath.trim()==="")&&n.push({level:"error",path:"semantic.rust.rustAnalyzerPath",message:"Rust analyzer path must be a non-empty string."});let a=e.indexer?.clojure;if(a?.configPath!==void 0){let l="indexer.clojure.configPath";if(typeof a.configPath!="string"||a.configPath.trim()==="")n.push({level:"error",path:l,message:"Config path must be a non-empty string."});else if(t.projectRoot){let u=WR(t.projectRoot,a.configPath),d=zR(t.projectRoot,u);d.startsWith("..")||VR(d)?n.push({level:"error",path:l,message:"Config path must stay inside the project root."}):Wr(u)||n.push({level:"warning",path:l,message:`Clojure indexer config path does not exist: ${a.configPath}`})}}if(e.locality!==void 0)if(!V(e.locality))n.push({level:"error",path:"locality",message:"Must be an object."});else{let l=e.locality.architecturalBoundarySegments;if(l!==void 0)if(!Array.isArray(l))n.push({level:"error",path:"locality.architecturalBoundarySegments",message:"Must be an array."});else for(let[u,d]of l.entries()){let m=`locality.architecturalBoundarySegments[${u}]`;typeof d!="string"||d.trim()===""?n.push({level:"error",path:m,message:"Boundary segment must be a non-empty string."}):(d.includes("/")||d.includes("\\"))&&n.push({level:"error",path:m,message:"Boundary segment must be a single folder name, not a path."})}}if(k1(e,n),e.declaredCouplings!==void 0&&!Array.isArray(e.declaredCouplings))n.push({level:"error",path:"declaredCouplings",message:"Must be an array."});else for(let[l,u]of(e.declaredCouplings??[]).entries()){let d=`declaredCouplings[${l}]`;if((!u.name||u.name.trim()==="")&&n.push({level:"error",path:`${d}.name`,message:"Declared coupling name is required."}),!Array.isArray(u.files)||u.files.length<2)n.push({level:"error",path:`${d}.files`,message:"Declared coupling needs at least two files."});else for(let[m,f]of u.files.entries())!f||f.trim()===""?n.push({level:"error",path:`${d}.files[${m}]`,message:"Declared coupling file path is required."}):t.projectRoot&&!Wr(mr(t.projectRoot,f))&&n.push({level:"warning",path:`${d}.files[${m}]`,message:`Declared coupling file does not exist: ${f}`});u.reason!==void 0&&u.reason.trim()===""&&n.push({level:"error",path:`${d}.reason`,message:"Declared coupling reason cannot be blank."})}let c=t.now??new Date;e.suppressions!==void 0&&!Array.isArray(e.suppressions)&&n.push({level:"error",path:"suppressions",message:"Must be an array."});for(let[l,u]of(Array.isArray(e.suppressions)?e.suppressions:[]).entries()){let d=`suppressions[${l}]`;if(!V(u)){n.push({level:"error",path:d,message:"Suppression must be an object."});continue}if((!u.reason||u.reason.trim()==="")&&n.push({level:"error",path:`${d}.reason`,message:"Suppression reason is required."}),u.id!==void 0&&u.id.trim()===""&&n.push({level:"error",path:`${d}.id`,message:"Suppression id cannot be blank."}),u.check!==void 0&&u.check.trim()===""&&n.push({level:"error",path:`${d}.check`,message:"Suppression check cannot be blank."}),!u.id&&(!u.check||!u.file)?n.push({level:"error",path:d,message:"Suppression must include id or both check and file."}):!u.id&&u.check&&u.file&&n.push({level:"warning",path:d,message:"Check+file suppressions waive every matching finding in that file; prefer a stable id when available."}),u.file!==void 0&&(u.file.trim()===""?n.push({level:"error",path:`${d}.file`,message:"Suppression file path cannot be blank."}):t.projectRoot&&!Wr(mr(t.projectRoot,u.file))&&n.push({level:"warning",path:`${d}.file`,message:`Suppression file does not exist: ${u.file}`})),u.expiresAt){let m=Date.parse(u.expiresAt);Number.isNaN(m)?n.push({level:"error",path:`${d}.expiresAt`,message:"Must be an ISO date string."}):m<=c.getTime()&&n.push({level:"warning",path:`${d}.expiresAt`,message:"Suppression has expired."})}if(u.decision!==void 0&&!Xc(u.decision))n.push({level:"error",path:`${d}.decision`,message:"Must be a valid automated-adjudication decision with reason code, evidence, and invalidation rules."});else if(u.decision&&t.projectRoot)for(let[m,f]of u.decision.evidence.entries())f.kind!=="graph"&&!Wr(mr(t.projectRoot,f.referent))&&n.push({level:"error",path:`${d}.decision.evidence[${m}].referent`,message:`Suppression counterevidence does not exist: ${f.referent}`})}return _1(e,n,t),F1(e,n),n}function k1(e,t){if(e.architecture===void 0)return;if(!V(e.architecture)){t.push({level:"error",path:"architecture",message:"Must be an object."});return}let n=e.architecture.boundaries;if(!Array.isArray(n)||n.length===0){t.push({level:"error",path:"architecture.boundaries",message:"Must be a non-empty array."});return}let r=new Set,i=new Set;for(let[a,c]of n.entries()){let l=`architecture.boundaries[${a}]`;if(!V(c)){t.push({level:"error",path:l,message:"Architecture boundary must be an object."});continue}let u=c.name;typeof u!="string"||u.trim()===""?t.push({level:"error",path:`${l}.name`,message:"Boundary name is required."}):r.has(u)?t.push({level:"error",path:`${l}.name`,message:`Duplicate boundary name: ${u}`}):r.add(u);let d=c.subUnits;d!==void 0&&d!=="directory"&&d!=="file"&&t.push({level:"error",path:`${l}.subUnits`,message:"Must be 'directory' or 'file'."});let m=c.maxFiles;m!==void 0&&(typeof m!="number"||!Number.isInteger(m)||m<0)&&t.push({level:"error",path:`${l}.maxFiles`,message:"Must be a non-negative integer."});let f=c.paths;if(!Array.isArray(f)||f.length===0){t.push({level:"error",path:`${l}.paths`,message:"Boundary paths must be a non-empty array."});continue}for(let[p,g]of f.entries()){let y=`${l}.paths[${p}]`;if(typeof g!="string"||g.trim()===""){t.push({level:"error",path:y,message:"Boundary path must be a non-empty string."});continue}T1(g)||t.push({level:"error",path:y,message:"Boundary path must be project-relative and may use only one trailing /* or /** glob."}),i.has(g)?t.push({level:"error",path:y,message:`Duplicate boundary path: ${g}`}):i.add(g)}}let o=e.architecture.allowedDependencies;if(o!==void 0&&!V(o))t.push({level:"error",path:"architecture.allowedDependencies",message:"Must be an object keyed by boundary name."});else if(V(o))for(let[a,c]of Object.entries(o)){let l=`architecture.allowedDependencies.${a}`;if(r.has(a)||t.push({level:"error",path:l,message:`Unknown source boundary: ${a}`}),!Array.isArray(c)){t.push({level:"error",path:l,message:"Dependency row must be an array."});continue}let u=new Set;for(let[d,m]of c.entries()){let f=`${l}[${d}]`;typeof m!="string"||m.trim()===""?t.push({level:"error",path:f,message:"Target boundary name is required."}):r.has(m)?u.has(m)?t.push({level:"error",path:f,message:`Duplicate target boundary: ${m}`}):u.add(m):t.push({level:"error",path:f,message:`Unknown target boundary: ${m}`})}}e.architecture.requireAcyclic!==void 0&&typeof e.architecture.requireAcyclic!="boolean"&&t.push({level:"error",path:"architecture.requireAcyclic",message:"Must be a boolean."});for(let a of["requireResolvedBoundaries","requireMinimalPolicy"])e.architecture[a]!==void 0&&typeof e.architecture[a]!="boolean"&&t.push({level:"error",path:`architecture.${a}`,message:"Must be a boolean."});for(let a of["maxBoundaryFanOut","maxBoundaryFiles"]){let c=e.architecture[a];c!==void 0&&(typeof c!="number"||!Number.isInteger(c)||c<0)&&t.push({level:"error",path:`architecture.${a}`,message:"Must be a non-negative integer."})}let s=e.architecture.testPaths;if(s!==void 0&&(!Array.isArray(s)||s.some(a=>typeof a!="string"))&&t.push({level:"error",path:"architecture.testPaths",message:"Must be an array of strings."}),e.architecture.requireCompletePolicy!==void 0&&typeof e.architecture.requireCompletePolicy!="boolean")t.push({level:"error",path:"architecture.requireCompletePolicy",message:"Must be a boolean."});else if(e.architecture.requireCompletePolicy===!0){let a=V(o)?o:{};for(let c of[...r].sort())Object.hasOwn(a,c)||t.push({level:"error",path:`architecture.allowedDependencies.${c}`,message:"A dependency row is required by architecture.requireCompletePolicy."})}}function T1(e){let t=e.replace(/\\/g,"/");if(t.startsWith("/")||t==="."||t===".."||t.split("/").includes(".."))return!1;let n=t.replace(/\/\*\*?$/,"");return n.length>0&&!/[*?[\]]/.test(n)}function F1(e,t){let n=e.docs?.snapshotPaths;if(n!==void 0){if(!Array.isArray(n)){t.push({level:"error",path:"docs.snapshotPaths",message:"Must be an array."});return}for(let[r,i]of n.entries())(typeof i!="string"||i.trim()==="")&&t.push({level:"error",path:`docs.snapshotPaths[${r}]`,message:"Snapshot path glob must be a non-empty string."})}}function _1(e,t,n){if(e.coverageContracts!==void 0){if(!Array.isArray(e.coverageContracts)){t.push({level:"error",path:"coverageContracts",message:"Must be an array."});return}for(let[r,i]of e.coverageContracts.entries()){let o=`coverageContracts[${r}]`;if(!V(i)){t.push({level:"error",path:o,message:"Coverage contract must be an object."});continue}(typeof i.name!="string"||i.name.trim()==="")&&t.push({level:"error",path:`${o}.name`,message:"Coverage contract name is required."}),typeof i.file!="string"||i.file.trim()===""?t.push({level:"error",path:`${o}.file`,message:"Coverage contract file is required."}):n.projectRoot&&!Wr(mr(n.projectRoot,i.file))&&t.push({level:"warning",path:`${o}.file`,message:`Coverage contract file does not exist: ${i.file}`}),JR(t,i.keys,`${o}.keys`,D1,"Unknown coverage-contract key extractor type."),JR(t,i.mustEqual,`${o}.mustEqual`,P1,"Unknown coverage-contract ground-truth source type."),i.allowExtra!==void 0&&typeof i.allowExtra!="boolean"&&t.push({level:"error",path:`${o}.allowExtra`,message:"Must be a boolean."})}}}function JR(e,t,n,r,i){if(!V(t)){e.push({level:"error",path:n,message:'Must be an object with a "type" field.'});return}if(typeof t.type!="string"||!r.has(t.type)){e.push({level:"error",path:`${n}.type`,message:`${i} Got: ${String(t.type)}`});return}let o={"object-literal-keys":["identifier"],"string-array":["identifier"],"markdown-list":["marker"],"top-level-dirs":["path"],"file-glob":["pattern"],"registered-commands":[],"builtin-skills":[]};for(let s of o[t.type]??[])(typeof t[s]!="string"||t[s].length===0)&&e.push({level:"error",path:`${n}.${s}`,message:`"${t.type}" requires a non-empty string "${s}".`})}function dde(e){return{...s1,...e.watch}}function mde(e,t){let n=mr(e,Kr),r={languages:t,watch:{enabled:!0,debounceMs:YR,cooldownMs:XR,gitPollMs:2e3,idleTimeoutMs:QR,autoRefresh:!0}},i=tl(n,o=>o.revision.exists?{kind:"unchanged"}:{kind:"write",text:nf(r)});return{configPath:n,changed:i.changed}}function fde(e,t,n){let r=mr(e,Kr),i=[...n],o=t,s=tl(r,a=>{let c=eC(a,t);if(tC(t.languages,c.config.languages,i))throw new ys(r,"languages");let l={...c.config,languages:i};return o=l,a.revision.exists&&!c.needsMigration&&nl(l,c.config)?{kind:"unchanged"}:{kind:"write",text:nf(l)}});return{configPath:r,config:o,changed:s.changed}}function pde(e,t,n){let r=mr(e,Kr),i=t,o=tl(r,s=>{let a=eC(s,t);if(tC(t.watch?.enabled,a.config.watch?.enabled,n))throw new ys(r,"watch.enabled");let c={...a.config,watch:{...a.config.watch,enabled:n,...n&&a.config.watch?.autoRefresh===void 0?{autoRefresh:!0}:{}}};return i=c,s.revision.exists&&!a.needsMigration&&nl(c,a.config)?{kind:"unchanged"}:{kind:"write",text:nf(c)}});return{configPath:r,config:i,changed:o.changed}}function eC(e,t){if(!e.revision.exists)return{config:Jc(t),needsMigration:!0};let n=nC(tf(e.text),e.path,"update");return{config:n.config,needsMigration:n.needsMigration}}function nf(e){return OR(e)}function nl(e,t){return JSON.stringify(e)===JSON.stringify(t)}function tC(e,t,n){return!nl(e,t)&&!nl(t,n)}function nC(e,t,n){if(e.kind==="legacy"||e.kind==="supported")return e;if(e.kind==="malformed"){let i=n==="read"?`invalid ${Kr} at ${t}: ${e.reason}`:`Cannot update ${t}: the latest project config is ${e.reason}.`;throw new Error(`${i} The file was left untouched.`)}let r=n==="read"?`invalid ${Kr} at ${t}`:`Cannot update ${t}: the latest project config is invalid`;throw new Error(`${r} (unsupported ${e.direction} schemaVersion ${e.schemaVersion}; this scip-query reads legacy v${ur} and current v${dr}). Upgrade scip-query before retrying; the file was left untouched.`)}function A1(e,t){if(!V(e))return;let n=e;if(xe(t,n,"",a1),xe(t,n.watch,"watch",c1),xe(t,n.hooks,"hooks",l1),xe(t,n.entryRoots,"entryRoots",u1),xe(t,n.semantic,"semantic",d1),xe(t,n.semantic?.typescript,"semantic.typescript",m1),xe(t,n.semantic?.rust,"semantic.rust",f1),xe(t,n.locality,"locality",g1),xe(t,n.architecture,"architecture",h1),xe(t,n.docs,"docs",b1),Array.isArray(n.architecture?.boundaries))for(let[r,i]of n.architecture.boundaries.entries())xe(t,i,`architecture.boundaries[${r}]`,y1);if(V(n.indexer)){xe(t,n.indexer,"indexer",KR);for(let[r,i]of Object.entries(n.indexer))KR.has(r)&&xe(t,i,`indexer.${r}`,p1)}if(Array.isArray(n.declaredCouplings))for(let[r,i]of n.declaredCouplings.entries())xe(t,i,`declaredCouplings[${r}]`,S1);if(Array.isArray(n.suppressions)){for(let[r,i]of n.suppressions.entries())if(xe(t,i,`suppressions[${r}]`,x1),V(i.decision)){if(xe(t,i.decision,`suppressions[${r}].decision`,R1),Array.isArray(i.decision.evidence))for(let[o,s]of i.decision.evidence.entries())xe(t,s,`suppressions[${r}].decision.evidence[${o}]`,C1);xe(t,i.decision.invalidateOn,`suppressions[${r}].decision.invalidateOn`,v1)}}if(Array.isArray(n.coverageContracts))for(let[r,i]of n.coverageContracts.entries()){let o=`coverageContracts[${r}]`;xe(t,i,o,I1),V(i)&&(xe(t,i.keys,`${o}.keys`,w1),xe(t,i.mustEqual,`${o}.mustEqual`,E1))}}function xe(e,t,n,r){if(V(t))for(let i of Object.keys(t))r.has(i)||e.push({level:"warning",path:n?`${n}.${i}`:i,message:"Unknown config key."})}import{existsSync as bC}from"fs";import{execFileSync as L1}from"child_process";import{existsSync as M1,readdirSync as iC}from"fs";import{extname as oC,join as sC}from"path";var aC=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),N1=[{language:"typescript",files:["tsconfig.json","tsconfig.base.json"],extensions:[".ts",".tsx",".mts",".cts"]},{language:"rust",files:["Cargo.toml"],extensions:[".rs"]},{language:"go",files:["go.mod"],extensions:[".go"]},{language:"java",files:["pom.xml","build.gradle","build.gradle.kts"],extensions:[".java"]},{language:"kotlin",files:["build.gradle.kts"],extensions:[".kt",".kts"]},{language:"scala",files:["build.sbt"],extensions:[".scala"]},{language:"clojure",files:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],extensions:[".clj",".cljs",".cljc"]},{language:"python",files:["pyproject.toml","setup.py","setup.cfg","Pipfile"],extensions:[".py",".pyi"]},{language:"ruby",files:["Gemfile"],extensions:[".rb"]},{language:"cpp",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"]},{language:"c",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".c",".h"]},{language:"csharp",globs:["*.csproj","*.sln"],extensions:[".cs"]},{language:"vb",globs:["*.vbproj"],extensions:[".vb"]},{language:"dart",files:["pubspec.yaml"],extensions:[".dart"]},{language:"php",files:["composer.json"],extensions:[".php"]},{language:"javascript",files:["package.json"],extensions:[".js",".jsx",".mjs",".cjs"]}];function bs(e){let t=[],n=O1(e),r=H1(e);for(let i of N1){if(B1(e,i.files)){t.push(i.language);continue}if(j1(n,i.globs)){t.push(i.language);continue}q1(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&rC(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&rC(t,"c"),t}function O1(e){try{return iC(e)}catch{return[]}}function B1(e,t){return t?.length?t.some(n=>M1(sC(e,n))):!1}function j1(e,t){return t?.length?e.some(n=>t.some(r=>$1(n,r))):!1}function $1(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[n,r]=t.split("*");return e.startsWith(n??"")&&e.endsWith(r??"")}function H1(e){let t=G1(e);if(t)return t;let n=new Set,r=[e];for(;r.length>0;){let i=r.pop();if(!i)continue;let o;try{o=iC(i,{withFileTypes:!0})}catch{continue}for(let s of o){if(s.name.startsWith(".")&&!s.name.endsWith("proj")&&!s.name.endsWith("sln")&&s.isDirectory())continue;let a=sC(i,s.name);if(s.isDirectory()){aC.has(s.name)||r.push(a);continue}let c=oC(s.name).toLowerCase();c&&n.add(c)}}return n}function G1(e){try{let t=L1("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"}),n=new Set;for(let r of t.split(`
|
|
410
|
+
`)){if(!r||r.split("/").some(o=>aC.has(o)))continue;let i=oC(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function q1(e,t){return t?.length?t.some(n=>e.has(n)):!1}function rC(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{createHash as lf}from"crypto";import{closeSync as U1,existsSync as ue,mkdirSync as V1,openSync as z1,readSync as W1,readdirSync as uf,renameSync as af,rmSync as Ss,statSync as Wi}from"fs";import{basename as dC,dirname as sn,join as X,relative as cC}from"path";var cf=Object.freeze({maxGenerations:8,maxLogicalBytes:2*1024*1024*1024});function mC(e){let t=Le(e.outputDb),n=Q1(e);e.onStage?.("after-recovery-retained");let r=e.preserveOutputScip?e.outputScip:e.tempOutputScip,i=mf({generationRoot:t,databasePath:e.tempOutputDb,indexPath:ue(r)?r:void 0,metadataPath:ue(e.tempMetaPath)?e.tempMetaPath:void 0}),o=(e.now??(()=>new Date))().toISOString(),s={version:Vr,currentGeneration:i.identity,artifactSet:"immutable-v1",...n?{previousGeneration:n}:{},...e.publication?{publication:e.publication}:{},publishedAt:o},a=vt(X(t,"state.json"),s,{spacing:2,trailingNewline:!0});e.onStage?.("after-pointer-handoff"),e.preserveOutputScip||sf(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),sf(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),sf(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let c=i.identity,l={...s,stableMirrors:df(e.outputDb,e.outputScip)};vt(X(t,"state.json"),l,{spacing:2,trailingNewline:!0});let u=fC(e.outputDb,{now:e.now}),d=Be(i.directorySync,a.directorySync);return{currentGeneration:c,...n?{previousGeneration:n}:{},retention:u,achievedDurability:d==="synced"?"directory-durable":"file-flushed",directorySync:d}}function K1(e,t,n,r=()=>new Date){if(!ue(e))return null;let i=sr(e),o=X(Le(e),"state.json");if(i?.artifactSet==="immutable-v1"&&Ac(e,i.currentGeneration))return i;let s=Le(e),a=!i&&ue(o)?eH(n,e,t):void 0;if(a&&!cs(s,a))return null;let c=mf({generationRoot:s,databasePath:e,indexPath:ue(t)?t:void 0,metadataPath:ue(n)?n:void 0,forcedIdentity:i?.currentGeneration??a}),l={version:Vr,currentGeneration:c.identity,artifactSet:"immutable-v1",stableMirrors:df(e,t),...i?.previousGeneration?{previousGeneration:i.previousGeneration}:{},...i?.publication?{publication:i.publication}:{},publishedAt:i?.publishedAt??r().toISOString()};return vt(X(s,"state.json"),l,{spacing:2,trailingNewline:!0}),l}function Tde(e,t,n=()=>new Date){if(!ue(e)||!ue(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=sr(e),i=Le(e),o=mf({generationRoot:i,databasePath:e,indexPath:ue(X(sn(e),"index.scip"))?X(sn(e),"index.scip"):void 0,metadataPath:t}),s=r&&r.currentGeneration!==o.identity?hC(e,r.currentGeneration):void 0,a={version:Vr,currentGeneration:o.identity,artifactSet:"immutable-v1",stableMirrors:df(e,X(sn(e),"index.scip")),...s?{previousGeneration:s}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return vt(X(Le(e),"state.json"),a,{spacing:2,trailingNewline:!0}),fC(e,{now:n}),a}function fC(e,t={}){let n=J1(t.limits),i=(t.now??(()=>new Date))().toISOString(),o=or(_c(e),{waitMs:0});if(!o)return{state:"deferred",generationCount:0,logicalBytes:0,protectedGenerations:0,activeReaderLeases:0,staleReaderLeasesRemoved:0,malformedReaderLeases:0,removedGenerations:0,removedLogicalBytes:0,limits:n,at:i,reason:"another process owns local generation retention"};try{let s=sr(e),a=pC(e),c=Mm(e,a.map(y=>y.identity),{isProcessAlive:t.isProcessAlive??Rt,readProcessIdentity:t.readProcessIdentity??tt}),l=new Set(c.protectedGenerations);s?.currentGeneration&&l.add(s.currentGeneration),s?.previousGeneration?.generationIdentity&&l.add(s.previousGeneration.generationIdentity);let u=a.length,d=a.reduce((y,h)=>y+h.logicalBytes,0),m=0,f=0;for(let y of a){if(u<=n.maxGenerations&&d<=n.maxLogicalBytes)break;l.has(y.identity)||(t.onBeforeRemove?.(y.identity),Ss(y.path,{recursive:!0,force:!0}),u-=1,d-=y.logicalBytes,m+=1,f+=y.logicalBytes)}let p=u>n.maxGenerations||d>n.maxLogicalBytes,g={state:p?"protected":m>0?"collected":"within-bounds",generationCount:u,logicalBytes:d,protectedGenerations:l.size,activeReaderLeases:c.activeLeases,staleReaderLeasesRemoved:c.staleLeasesRemoved,malformedReaderLeases:c.malformedLeases,removedGenerations:m,removedLogicalBytes:f,limits:n,at:i,...p?{reason:c.malformedLeases>0?"malformed reader ownership evidence fails closed":"retention bounds cannot be met without deleting a protected generation"}:{}};return lC(e,g),g}catch(s){let a={state:"error",generationCount:0,logicalBytes:0,protectedGenerations:0,activeReaderLeases:0,staleReaderLeasesRemoved:0,malformedReaderLeases:0,removedGenerations:0,removedLogicalBytes:0,limits:n,at:i,reason:s instanceof Error?s.message:String(s)};try{lC(e,a)}catch{}return a}finally{o.release()}}function Fde(e){let t=Le(e);if(!ue(t))return{state:"absent",generationCount:0,logicalBytes:0,protectedGenerations:0,activeReaderLeases:0,malformedReaderLeases:0,limits:{...cf},reason:"local immutable generation store does not exist"};let n=Y1(e),r=n?.limits??{...cf},i=or(_c(e),{waitMs:0});if(!i)return{state:"deferred",generationCount:n?.generationCount??0,logicalBytes:n?.logicalBytes??0,protectedGenerations:n?.protectedGenerations??0,activeReaderLeases:n?.activeReaderLeases??0,malformedReaderLeases:n?.malformedReaderLeases??0,limits:r,...n?{lastCollection:n}:{},reason:"another process owns local generation retention"};try{let o=pC(e),s=sr(e),a=Mm(e,o.map(l=>l.identity),{isProcessAlive:Rt,readProcessIdentity:tt},{removeStale:!1}),c=new Set(a.protectedGenerations);return s?.currentGeneration&&c.add(s.currentGeneration),s?.previousGeneration?.generationIdentity&&c.add(s.previousGeneration.generationIdentity),{state:"managed",generationCount:o.length,logicalBytes:o.reduce((l,u)=>l+u.logicalBytes,0),...o[0]?{oldestGenerationAt:new Date(o[0].modifiedAtMs).toISOString()}:{},protectedGenerations:c.size,activeReaderLeases:a.activeLeases,malformedReaderLeases:a.malformedLeases,limits:r,...n?{lastCollection:n}:{},...a.malformedLeases>0?{reason:"malformed reader ownership evidence prevents unsafe collection"}:{}}}catch(o){return{state:"error",generationCount:0,logicalBytes:0,protectedGenerations:0,activeReaderLeases:0,malformedReaderLeases:0,limits:r,...n?{lastCollection:n}:{},reason:o instanceof Error?o.message:String(o)}}finally{i.release()}}function J1(e={}){let t={...cf,...e};if(!Number.isSafeInteger(t.maxGenerations)||t.maxGenerations<2)throw new Error("Local SQLite generation retention must keep at least current and previous generations.");if(!Number.isSafeInteger(t.maxLogicalBytes)||t.maxLogicalBytes<=0)throw new Error("Local SQLite generation byte retention must be a positive safe integer.");return t}function pC(e){let t=Le(e);return ue(t)?uf(t,{withFileTypes:!0}).filter(n=>n.isDirectory()&&/^[a-f0-9]{64}$/.test(n.name)).map(n=>{let r=X(t,n.name),i=cs(t,n.name),o=i?i.database.size+(i.index?.size??0)+(i.metadata?.size??0):gC(r);return{identity:n.name,path:r,logicalBytes:o,modifiedAtMs:Wi(r).mtimeMs}}).sort((n,r)=>n.modifiedAtMs-r.modifiedAtMs||n.identity.localeCompare(r.identity)):[]}function gC(e){let t=0;for(let n of uf(e,{withFileTypes:!0})){let r=X(e,n.name);n.isDirectory()?t+=gC(r):n.isFile()&&(t+=Wi(r).size)}return t}function lC(e,t){nr(X(Le(e),"gc.json"),t,{spacing:2,trailingNewline:!0})}function Y1(e){try{let t=JSON.parse(O(X(Le(e),"gc.json"),"local SQLite generation GC status"));return!t||t.state!=="within-bounds"&&t.state!=="collected"&&t.state!=="protected"&&t.state!=="deferred"&&t.state!=="error"||!Number.isSafeInteger(t.generationCount)||t.generationCount<0||!Number.isFinite(t.logicalBytes)||t.logicalBytes<0||!Number.isFinite(Date.parse(t.at))?void 0:t}catch{return}}function xs(e,t=X(sn(e),"meta.json")){let n=X(Le(e),"state.json");if(!ue(n))return{state:"legacy",statePath:n};let r=sr(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=Ac(e,r.currentGeneration),o=i!==null,s=i?X1(e,t,i,r):!1,a=r.previousGeneration?ue(X(sn(e),r.previousGeneration.databasePath)):!0;return!s||!o||!a?{state:"drifted",statePath:n,currentMatches:s,recoveryExists:a,generation:r,reason:o?s?"retained recovery database is missing":"stable database or metadata no longer matches the published generation":"published immutable generation is missing"}:{state:"current",statePath:n,currentMatches:s,recoveryExists:a,generation:r}}catch(i){return{state:"drifted",statePath:n,currentMatches:!1,recoveryExists:!1,generation:r,reason:i instanceof Error?i.message:String(i)}}}function X1(e,t,n,r){if(r.stableMirrors&&(r.stableMirrors.databaseFileIdentity!==Fn(e)||r.stableMirrors.indexFileIdentity!==void 0&&r.stableMirrors.indexFileIdentity!==Fn(X(sn(e),"index.scip")))||!uC(e,n.database))return!1;let i=X(sn(e),"index.scip");if(n.index&&!uC(i,n.index))return!1;if(!n.metadata)return!ue(t);if(!ue(t))return!1;let o=X(Le(e),n.identity,n.metadata.file);return ue(o)&&ar(O(t,"reindex metadata"))===ar(O(o,"immutable reindex metadata"))}function uC(e,t){return ue(e)&&Wi(e).isFile()&&Wi(e).size===t.size}function Q1(e){let t=K1(e.outputDb,e.outputScip,e.metaPath);return t?hC(e.outputDb,t.currentGeneration):void 0}function df(e,t){return{databaseFileIdentity:Fn(e),...ue(t)?{indexFileIdentity:Fn(t)}:{}}}function hC(e,t){let n=X(Le(e),t),r=X(n,dC(e)),i=X(n,"meta.json");return{generationIdentity:t,databasePath:cC(sn(e),r),...ue(i)?{metadataPath:cC(sn(e),i)}:{}}}function Z1(e){if(ue(e))for(let t of uf(e,{withFileTypes:!0}))t.isDirectory()&&t.name.endsWith(".tmp")&&Ss(X(e,t.name),{recursive:!0,force:!0})}function eH(e,t,n=X(sn(t),"index.scip")){let r=lf("sha256").update("sqlite-generation-artifacts-v1\0");return r.update(rl(t)),ue(n)&&r.update(`\0${rl(n)}`),ue(e)&&r.update(`\0${ar(O(e,"reindex metadata"))}`),r.digest("hex")}function mf(e){let t=rf(e.databasePath),n=e.indexPath?rf(e.indexPath):void 0,r=e.metadataPath?rf(e.metadataPath):void 0,i=e.forcedIdentity??tH(t,n,e.metadataPath),o=X(e.generationRoot,i),s=X(o,Fc);if(ue(s)){let l=cs(e.generationRoot,i);if(l&&yC(o,l.database,t)&&rH(o,l.index,n)&&iH(o,l.metadata,e.metadataPath))return{identity:i,directorySync:ce(e.generationRoot)};throw new Error(`SQLite generation ${i} already exists with different or corrupt artifacts.`)}let a=[dt(e.generationRoot)];Z1(e.generationRoot);let c=`${o}.${process.pid}.${Date.now()}.tmp`;Ss(c,{recursive:!0,force:!0}),V1(c,{recursive:!0});try{a.push(of(e.databasePath,X(c,t.file))),n&&e.indexPath&&a.push(of(e.indexPath,X(c,n.file))),r&&e.metadataPath&&a.push(of(e.metadataPath,X(c,r.file)));let l=vt(X(c,Fc),{version:Lm,identity:i,database:t,...n?{index:n}:{},...r?{metadata:r}:{}},{spacing:2,trailingNewline:!0});l.directorySync!=="not-requested"&&a.push(l.directorySync),a.push(ce(c)),af(c,o),a.push(ce(e.generationRoot))}finally{Ss(c,{recursive:!0,force:!0})}return{identity:i,directorySync:Be(...a)}}function tH(e,t,n){let r=lf("sha256").update("sqlite-generation-artifacts-v1\0");return r.update(e.sha256),t&&r.update(`\0${t.sha256}`),n&&r.update(`\0${ar(O(n,"reindex metadata"))}`),r.digest("hex")}function rf(e){return{file:dC(e),size:Wi(e).size,sha256:rl(e)}}function rl(e){let t=lf("sha256"),n=z1(e,"r"),r=Buffer.allocUnsafe(1024*1024);try{for(;;){let i=nH(n,r);if(i===0)break;t.update(r.subarray(0,i))}}finally{U1(n)}return t.digest("hex")}function nH(e,t){let n=0;for(;n<t.length;){let r=W1(e,t,n,t.length-n,null);if(n+=r,r===0)break}return n}function of(e,t){return Ho(e,t,{mode:292})}function yC(e,t,n){let r=X(e,t.file);return t.file===n.file&&t.size===n.size&&t.sha256===n.sha256&&ue(r)&&Wi(r).size===t.size&&rl(r)===t.sha256}function rH(e,t,n){return!t||!n?t===n:yC(e,t,n)}function iH(e,t,n){if(!t||!n)return t===void 0&&n===void 0;let r=X(e,t.file);return ue(r)&&ar(O(r,"stored reindex metadata"))===ar(O(n,"candidate reindex metadata"))}function sf(e,t){Ss(`${t}.tmp-replace`,{force:!0}),af(e,`${t}.tmp-replace`),af(`${t}.tmp-replace`,t)}function SC(e,t,n){let r=new Date().toISOString();if(!bC(n.dbPath))return{state:"missing",checkedAt:r,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!bC(n.metaPath))return{state:"unknown",checkedAt:r,metaPath:n.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let i=Jt(O(n.metaPath,"reindex metadata"));if(i.kind==="unsupported")return{state:"unknown",checkedAt:r,metaPath:n.metaPath,reason:`Reindex metadata version ${i.version} is unsupported by this scip-query build.`,remedy:"Upgrade scip-query or run: scip-query reindex"};if(i.kind==="malformed")return{state:"unknown",checkedAt:r,metaPath:n.metaPath,reason:`Could not decode reindex metadata: ${i.reason}`,remedy:"Run: scip-query reindex"};let o=i.metadata,s=t.languages??bs(e),a=oH(e,s,t),c=[...o.indexedLanguages??[]].sort(),l=i.capabilities.publishableGeneration&&JSON.stringify(o.fingerprint)===JSON.stringify(a)&&JSON.stringify(c)===JSON.stringify(a.languages),u=xs(n.dbPath,n.metaPath),d=u.state==="invalid"||u.state==="drifted",m=l&&!d;return{state:m?"fresh":"stale",checkedAt:r,metaPath:n.metaPath,updatedAt:o.updatedAt,lastRefresh:o.lastRefresh,reason:d?`SQLite generation requires repair: ${u.reason}`:l?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:m?void 0:"Run: scip-query reindex"}}catch(i){return{state:"unknown",checkedAt:r,metaPath:n.metaPath,reason:`Could not read reindex metadata: ${i instanceof Error?i.message:String(i)}`,remedy:"Run: scip-query reindex"}}}function oH(e,t,n){return Co(e,t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath})}import{createHash as XC,randomUUID as GH}from"crypto";import{existsSync as pr,lstatSync as qH,mkdirSync as Yi,mkdtempSync as QC,readdirSync as UH,realpathSync as VH,renameSync as Xr,rmSync as fr,statSync as ml}from"fs";import{dirname as Df,join as M,resolve as _n}from"path";import{setTimeout as zH}from"timers/promises";import{pathToFileURL as zC}from"url";import{deserializeSCIP as ZC}from"@c4312/scip";import WH from"better-sqlite3";import{lstatSync as xH,readdirSync as RH}from"fs";import{join as CH,relative as vH,resolve as Rf,sep as IH}from"path";import{createHash as sH}from"crypto";import{existsSync as pf,mkdirSync as aH,readdirSync as Gde,renameSync as cH,rmSync as qde,writeFileSync as lH}from"fs";import{join as Ki}from"path";import{create as RC,fromBinary as CC,toBinary as uH}from"@bufbuild/protobuf";import{deserializeSCIP as il,DocumentSchema as gf,IndexSchema as vC,serializeSCIP as IC}from"@c4312/scip";var ol=1,Rs="typescript-scip-fragments";function Jde(e){if(e.length===0)throw new Error("affected TypeScript mini index requires documents");let t=new Set,n=[];for(let o of e){let s=Jr(o.relativePath);if(t.has(s))throw new Error(`duplicate TypeScript fragment replacement: ${s}`);if(t.add(s),o.bytes===null)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${s}`);let a=CC(gf,o.bytes);if(a.relativePath!==s)throw new Error(`TypeScript fragment path mismatch: expected ${s}, got ${a.relativePath}`);n.push(a)}let r=IC(RC(vC,{documents:n,externalSymbols:[]})),i=il(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function sl(e){let t=Ki(e,Rs);return{rootDir:t,blobDir:Ki(t,"blobs"),generationDir:Ki(t,"generations")}}function dH(e){let t=il(e.indexBytes);AC(t.metadata,LC(e)),_C(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let s=Jr(o.relativePath);if(n.has(s))throw new Error(`duplicate TypeScript SCIP document path: ${s}`);n.add(s);let a=uH(gf,o),c=e.documentIdentities.get(s)??(e.allowUntrackedDocuments?Yr(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:s,contentHash:Yr(a)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${s}`);r.push(PC(e.cacheDir,{relativePath:s,bytes:a,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=kC(e,r);return TC(e.cacheDir,i),i}function Yde(e){let t=sl(e.cacheDir);if(!pf(hf(t,e.generationIdentity)))return dH(e);let n=wC({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity});if(!e.allowUntrackedDocuments&&n.manifest.documents.length!==e.documentIdentities.size)throw new Error("TypeScript fragment generation document identities changed");for(let r of n.manifest.documents){let i=e.documentIdentities.get(r.relativePath);if(!(i===void 0&&e.allowUntrackedDocuments)&&i!==r.documentIdentity)throw new Error(`TypeScript fragment generation document identity changed: ${r.relativePath}`)}return n.manifest}function Xde(e){let t=wC({cacheDir:e.cacheDir,generationIdentity:e.previousGenerationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity}).manifest,n=new Map(t.documents.map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let s=Jr(o.relativePath);if(r.has(s))throw new Error(`duplicate TypeScript fragment replacement: ${s}`);if(r.add(s),!n.has(s))throw new Error(`TypeScript fragment replacement has no prior document: ${s}`);let a=e.documentIdentities.get(s);if(!a)throw new Error(`missing TypeScript document identity: ${s}`);o.bytes===null?n.delete(s):n.set(s,PC(e.cacheDir,o,a))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=kC(e,[...n.values()]);return TC(e.cacheDir,i),i}function wC(e){let t=sl(e.cacheDir),n=hf(t,e.generationIdentity),r;try{r=FC(J(n,{maxBytes:Ie,inputKind:"TypeScript fragment manifest"}))}catch(o){throw new Error(`TypeScript fragment generation is unavailable: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(r.generationIdentity!==e.generationIdentity)throw new Error("TypeScript fragment generation identity does not match its manifest path");if(e.producerIdentity&&r.producerIdentity!==e.producerIdentity)throw new Error("TypeScript fragment producer identity changed");if(e.projectIdentity&&r.projectIdentity!==e.projectIdentity)throw new Error("TypeScript fragment project identity changed");let i=new Map;for(let o of r.documents){let s=Ki(t.blobDir,`${o.blobHash}.scipdoc`),a=Se(s,{maxBytes:He,inputKind:"TypeScript fragment blob"});if(a.byteLength!==o.byteLength||Yr(a)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,a)}return{manifest:r,fragments:i}}function EC(e){let t=DC(e);return ff(t.baseIndex,t.completeDocuments,"assembled")}function Qde(e){let t=DC(e);return mH(t.deletedAffectedPaths),{completeIndexBytes:ff(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:ff(t.baseIndex,t.affectedDocuments,"affected")}}function DC(e){let t=il(e.baseIndexBytes);AC(t.metadata,LC(e)),_C(t.externalSymbols);let n=new Map;for(let a of e.fragments){let c=Jr(a.relativePath);if(n.has(c))throw new Error(`duplicate TypeScript fragment replacement: ${c}`);n.set(c,a)}if(n.size===0)throw new Error("TypeScript index assembly requires at least one replacement");let r=new Set,i=[],o=[],s=[];for(let a of t.documents){let c=Jr(a.relativePath);if(r.has(c))throw new Error(`duplicate TypeScript SCIP document path: ${c}`);r.add(c);let l=n.get(c);if(!l){i.push(a);continue}if(n.delete(c),l.bytes===null){s.push(c);continue}let u=CC(gf,l.bytes);if(u.relativePath!==c)throw new Error(`TypeScript fragment path mismatch: expected ${c}, got ${u.relativePath}`);i.push(u),o.push(u)}if(n.size>0)throw new Error(`TypeScript fragment replacement has no prior document: ${[...n.keys()].sort()[0]}`);return{baseIndex:t,completeDocuments:i,affectedDocuments:o,deletedAffectedPaths:s}}function ff(e,t,n){let r=IC(RC(vC,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=il(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function mH(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function PC(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=Jr(t.relativePath),i=Buffer.from(t.bytes),o=Yr(i),s=sl(e);aH(s.blobDir,{recursive:!0});let a=Ki(s.blobDir,`${o}.scipdoc`);if(pf(a)){let c=Se(a,{maxBytes:He,inputKind:"TypeScript fragment blob"});if(c.byteLength!==i.byteLength||Yr(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${a}.${process.pid}.${Date.now()}.tmp`;lH(c,i),cH(c,a)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function kC(e,t){if(!e.producerIdentity||!e.projectIdentity||!e.generationIdentity)throw new Error("TypeScript fragment generation identities must be non-empty");let n=[...t].sort((r,i)=>r.relativePath.localeCompare(i.relativePath));if(new Set(n.map(r=>r.relativePath)).size!==n.length)throw new Error("TypeScript fragment generation contains duplicate document paths");return{version:ol,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function TC(e,t){let n=sl(e),r=hf(n,t.generationIdentity);if(pf(r)){let i=FC(J(r,{maxBytes:Ie,inputKind:"TypeScript fragment manifest"}));if(xC(i)!==xC(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}nr(r,t,{spacing:2,trailingNewline:!0})}function xC(e){return Yr(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function FC(e){let t=JSON.parse(e);if(t.version!==ol||typeof t.producerIdentity!="string"||typeof t.projectIdentity!="string"||typeof t.generationIdentity!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.documents))throw new Error("invalid TypeScript fragment generation manifest");let n=new Set;for(let r of t.documents){if(!r||typeof r.relativePath!="string"||typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash)||typeof r.byteLength!="number"||!Number.isInteger(r.byteLength)||r.byteLength<0||typeof r.documentIdentity!="string"||!r.documentIdentity)throw new Error("invalid TypeScript fragment record");if(Jr(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function hf(e,t){return Ki(e.generationDir,fH(t))}function fH(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${Yr(e)}.json`}function _C(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function AC(e,t){if(!e||typeof e!="object")throw new Error("TypeScript SCIP shard has no producer metadata");let n=e,r=n.toolInfo??n.tool_info;if(!r||typeof r!="object")throw new Error("TypeScript SCIP shard has no producer tool identity");let i=r;if(i.name!=="scip-typescript"||i.version!==t)throw new Error("TypeScript SCIP shard producer identity changed")}function LC(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function Jr(e){if(!e||e.startsWith("/")||e.startsWith("\\")||e.includes("\\"))throw new Error(`invalid TypeScript SCIP document path: ${e}`);let t=e.split("/");if(t.includes("")||t.includes(".")||t.includes(".."))throw new Error(`invalid TypeScript SCIP document path: ${e}`);return e}function Yr(e){return sH("sha256").update(e).digest("hex")}import{createHash as pH}from"crypto";import{existsSync as Cs,mkdirSync as gH,readdirSync as yf,renameSync as hH,rmSync as MC,writeFileSync as yH}from"fs";import{join as zt}from"path";var al=1,sme=64*1024*1024,Is="typescript-scip-overlays";function ame(e){let t=OC(e.cacheDir,e.previousGenerationIdentity);if(!t&&!e.baseShardCurrent)throw new Error("deferred TypeScript SCIP base has no matching overlay generation");if(t&&(t.producerIdentity!==e.producerIdentity||t.projectIdentity!==e.projectIdentity))throw new Error("TypeScript overlay producer or project identity changed");let n=new Map((t?.overlays??[]).map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let s=xf(o.relativePath);if(r.has(s))throw new Error(`duplicate TypeScript overlay: ${s}`);r.add(s),n.set(s,bH(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:al,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:t?.baseGenerationIdentity??e.previousGenerationIdentity,generationIdentity:e.nextGenerationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),overlays:[...n.values()].sort((o,s)=>o.relativePath.localeCompare(s.relativePath))};return SH(e.cacheDir,i),i}function cme(e){let t=OC(e.cacheDir,e.generationIdentity);if(!t)throw new Error("TypeScript overlay generation is unavailable");let n=t.overlays.map(r=>{if(r.blobHash===null)return{relativePath:r.relativePath,bytes:null,occurrences:0,symbols:0,referenceFragments:[]};let i=Se(zt(ws(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`),{maxBytes:He,inputKind:"TypeScript overlay blob"});if(i.byteLength!==r.byteLength||vs(i)!==r.blobHash)throw new Error(`TypeScript overlay blob is corrupt: ${r.relativePath}`);return{relativePath:r.relativePath,bytes:i,occurrences:0,symbols:0,referenceFragments:[]}});return EC({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function lme(e,t){let n=ws(e),r=zt(n,"generations");if(!Cs(r))return;let i=new Set(t.map(Sf)),o=new Set;for(let a of yf(r).filter(c=>i.has(c))){let c=bf(J(zt(r,a),{maxBytes:Ie,inputKind:"TypeScript overlay manifest"}));for(let l of c.overlays)l.blobHash&&o.add(`${l.blobHash}.scipdoc`)}for(let a of yf(r))i.has(a)||MC(zt(r,a),{force:!0});let s=zt(n,"blobs");if(Cs(s))for(let a of yf(s))o.has(a)||MC(zt(s,a),{force:!0})}function OC(e,t){let n=zt(ws(e),"generations",Sf(t));if(!Cs(n))return null;let r=bf(J(n,{maxBytes:Ie,inputKind:"TypeScript overlay manifest"}));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function bH(e,t){let n=xf(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=vs(r),o=zt(ws(e),"blobs");gH(o,{recursive:!0});let s=zt(o,`${i}.scipdoc`);if(Cs(s)){let a=Se(s,{maxBytes:He,inputKind:"TypeScript overlay blob"});if(a.byteLength!==r.byteLength||vs(a)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let a=`${s}.${process.pid}.${Date.now()}.tmp`;yH(a,r),hH(a,s)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function SH(e,t){let n=zt(ws(e),"generations",Sf(t.generationIdentity));if(Cs(n)){let r=bf(J(n,{maxBytes:Ie,inputKind:"TypeScript overlay manifest"}));if(NC(r)!==NC(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}nr(n,t,{spacing:2,trailingNewline:!0})}function bf(e){let t=JSON.parse(e);if(t.version!==al||typeof t.producerIdentity!="string"||!t.producerIdentity||typeof t.projectIdentity!="string"||!t.projectIdentity||typeof t.baseGenerationIdentity!="string"||!t.baseGenerationIdentity||typeof t.generationIdentity!="string"||!t.generationIdentity||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.overlays))throw new Error("invalid TypeScript overlay manifest");let n=new Set;for(let r of t.overlays){if(!r||typeof r.relativePath!="string"||r.blobHash!==null&&(typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash))||!Number.isInteger(r.byteLength)||r.byteLength<0||r.blobHash===null&&r.byteLength!==0)throw new Error("invalid TypeScript overlay record");if(xf(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function ws(e){return zt(e,Is)}function Sf(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${vs(e)}.json`}function NC(e){return vs(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function xf(e){if(!e||e.startsWith("/")||e.includes("\\")||e.split("/").some(t=>!t||t==="."))throw new Error(`invalid TypeScript overlay path: ${e}`);if(e.split("/").includes(".."))throw new Error(`invalid TypeScript overlay path: ${e}`);return e}function vs(e){return pH("sha256").update(e).digest("hex")}var Es=1,Cf="language-indexes",BC=["index.db","index.scip","meta.json"],jC=[Cf,Rs,Is];function cl(e){let t=[];for(let n of BC)wH(e,n),t.push(n);for(let n of jC)$C(e,n,t);return{version:Es,files:t.sort()}}function ll(e){if(!e||e.includes("\0")||e.startsWith("/")||e.includes("\\"))throw new Error(`invalid index artifact path: ${e||"<empty>"}`);let t=e.split("/");if(t.some(r=>!r||r==="."||r===".."))throw new Error(`invalid index artifact path: ${e}`);let n=t[0];if(!BC.includes(e)&&!jC.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function an(e,t){let n=ll(t),r=Rf(e),i=Rf(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${IH}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function $C(e,t,n){let r=CH(e,t),i;try{i=RH(r,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(let o of i){let s=`${t}/${o.name}`;if(o.isSymbolicLink())throw new Error(`index artifact cannot be a symlink: ${s}`);o.isDirectory()?$C(e,s,n):o.isFile()&&n.push(ll(s))}}function wH(e,t){let n=an(e,t),r;try{r=xH(n)}catch{throw new Error(`required index artifact is missing: ${t}`)}if(!r.isFile()||r.isSymbolicLink())throw new Error(`required index artifact is not a regular file: ${t}`);if(vH(Rf(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{writeFileSync as If}from"fs";import{create as Ds}from"@bufbuild/protobuf";import{deserializeSCIP as wf,serializeSCIP as Ef,DocumentSchema as _H,IndexSchema as GC,MetadataSchema as AH,SymbolInformationSchema as LH}from"@c4312/scip";import{writeFileSync as EH}from"fs";import{create as HC}from"@bufbuild/protobuf";import{deserializeSCIP as DH,DocumentSchema as PH,IndexSchema as kH,serializeSCIP as TH,SymbolRole as FH}from"@c4312/scip";function Rme(e){let t;try{t=DH(Se(e,{inputKind:"SCIP sanitization input",maxBytes:Me}))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=vf(t);return n.removedDefinitionOccurrences>0&&EH(e,Buffer.from(TH(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function vf(e){let t=new Set;for(let o of e.documents){ht(o.relativePath);for(let s of o.symbols)s.symbol&&t.add(s.symbol)}for(let o of e.externalSymbols)o.symbol&&t.add(o.symbol);let n=0,r=0,i=[];for(let o of e.documents){let s=o.occurrences.filter(a=>(a.symbolRoles&FH.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(s.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(HC(PH,{language:o.language,relativePath:o.relativePath,occurrences:s,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:HC(kH,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function qC(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=NH(e),n=OH(e.flatMap(i=>i.documents??[])),r=VC(e.flatMap(i=>i.externalSymbols??[]));return Ds(GC,{metadata:t,documents:n,externalSymbols:r})}function Pme(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>wf(Se(i,{inputKind:"SCIP merge input",maxBytes:Me}))),r=qC(n);return If(t,Buffer.from(Ef(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function kme(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>wf(Se(i,{inputKind:"SCIP merge input",maxBytes:Me}))),r=vf(qC(n));return If(t,Buffer.from(Ef(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function MH(e,t,n){let r=e.metadata;if(!r)throw new Error("Cannot rebase a SCIP index without metadata");if(r.projectRoot!==t)throw new Error(`Cannot rebase SCIP project root: expected ${t}, got ${r.projectRoot}`);return Ds(GC,{metadata:Ds(AH,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function UC(e,t,n){let r=wf(Se(e,{inputKind:"SCIP normalization input",maxBytes:Me})),i=MH(r,t,n);If(e,Buffer.from(Ef(i)))}function NH(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let r of e.slice(1)){let i=r.metadata?.projectRoot;if(n&&i&&i!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${i}`)}return t}function OH(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);if(!r){t.set(n.relativePath,n);continue}t.set(n.relativePath,Ds(_H,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:BH([...r.occurrences,...n.occurrences]),symbols:VC([...r.symbols,...n.symbols]),text:$H(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function BH(e){let t=new Set,n=[];for(let r of e){let i=JSON.stringify(r);t.has(i)||(t.add(i),n.push(r))}return n}function VC(e){let t=new Map;for(let n of e){let r=t.get(n.symbol);if(!r){t.set(n.symbol,n);continue}t.set(n.symbol,Ds(LH,{symbol:r.symbol,documentation:HH([...r.documentation,...n.documentation]),relationships:jH([...r.relationships,...n.relationships]),kind:r.kind||n.kind,displayName:r.displayName||n.displayName,enclosingSymbol:r.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:r.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function jH(e){let t=new Set,n=[];for(let r of e){let i=[r.symbol,r.isReference?"1":"0",r.isImplementation?"1":"0",r.isTypeDefinition?"1":"0",r.isDefinition?"1":"0"].join("|");t.has(i)||(t.add(i),n.push(r))}return n}function $H(e,t){return e?t?e.length>=t.length?e:t:e:t}function HH(e){return[...new Set(e)]}var Ff=1,WC="SCIP_QUERY_SHARED_CACHE",Pf=JSON.stringify({cliVersion:wt,artifactCatalogVersion:Es,sqliteGenerationStoreVersion:Vr,typescriptFragmentStoreVersion:ol,typescriptOverlayStoreVersion:al}),ev="manifest.json",tv="shared-cache.json",_f=[Cf,Rs,Is];function ul(e,t){if(!e.clean||!e.treeOid)return;let n=uv(JSON.stringify({version:Ff,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:Pf}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:Pf,generationId:n,repositoryCacheDir:ps(e.repositoryId)}}function nv(e,t,n){if(process.env[WC]==="0")return`${WC}=0`;if(!Ym(n))return"explicit cache or database override";if(zc(Df(t))!==zc(Vc(e))||t!==M(Df(t),"index.db"))return"index database is outside the managed worktree cache"}function rv(e,t,n){if(!Ym(t))return;let r=n??ui(e);return r?M(ps(r.repositoryId),"evidence.db"):void 0}function Qr(e,t=!0){let n=Mf(e),r;try{r=KH(J(M(n,ev),{inputKind:"shared-generation manifest",maxBytes:Ie}))}catch{return null}if(r.generationId!==e.generationId||r.repositoryId!==e.repositoryId||r.treeOid!==e.treeOid||r.producerIdentity!==e.producerIdentity||JSON.stringify(r.fingerprint)!==JSON.stringify(e.fingerprint))return null;if(!t)return r;try{for(let i of r.artifacts){let o=an(n,i.path),s=ml(o);if(!s.isFile()||s.size!==i.size||Zt(o,{inputKind:"shared-generation artifact",maxBytes:Me})!==i.sha256)return null}}catch{return null}return r}function iv(e){let t=Qr(e.snapshot);if(t)return KC(e.snapshot,t);if(!Ji(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=JC(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=cl(e.sourceCacheDir),i=M(e.snapshot.repositoryCacheDir,"generations"),o=[dt(i)],s=QC(M(i,`.tmp-${process.pid}-`));try{let a=[];for(let p of r.files){let g=an(e.sourceCacheDir,p),y=an(s,p);o.push(ks(g,y,292)),e.onPublicationStage?.("after-artifact-flushed",p);let h=ml(y).size;a.push({path:p,size:h,sha256:Zt(y,{inputKind:"staged shared-generation artifact",maxBytes:Me})})}let c=ZC(Se(M(s,"index.scip"),{inputKind:"staged shared SCIP index",maxBytes:Me})).metadata?.projectRoot;if(!c)throw new Error("shared SCIP generation has no project root metadata");let l=Nf(e.sourceProjectRoot);if(c!==l)throw new Error("shared SCIP generation root does not match its source worktree");if(JC(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let u={version:Ff,artifactCatalogVersion:Es,generationId:e.snapshot.generationId,repositoryId:e.snapshot.repositoryId,treeOid:e.snapshot.treeOid,fingerprint:e.snapshot.fingerprint,producerIdentity:e.snapshot.producerIdentity,sourceProjectRoot:e.sourceProjectRoot,scipProjectRoot:c,createdAt:(e.now??(()=>new Date))().toISOString(),artifacts:a.sort((p,g)=>p.path.localeCompare(g.path))},d=vt(M(s,ev),u,{spacing:2,trailingNewline:!0});d.directorySync!=="not-requested"&&o.push(d.directorySync),e.onPublicationStage?.("after-manifest-flushed"),o.push(ce(s)),e.onPublicationStage?.("after-staging-directory-synced");let m=Mf(e.snapshot);try{if(pr(m)&&!Qr(e.snapshot)){let p=`${m}.corrupt-${process.pid}-${Date.now()}`;Xr(m,p),fr(p,{recursive:!0,force:!0})}Xr(s,m)}catch(p){let g=Qr(e.snapshot);if(g)return KC(e.snapshot,g);throw p}e.onPublicationStage?.("after-generation-renamed"),o.push(ce(i)),e.onPublicationStage?.("after-generations-directory-synced");let f=Be(...o);return{kind:"published",manifest:u,achievedDurability:f==="synced"?"directory-durable":"file-flushed",directorySync:f}}finally{fr(s,{recursive:!0,force:!0})}}function KC(e,t){let n=ce(M(e.repositoryCacheDir,"generations"));return{kind:"existing",manifest:t,achievedDurability:n==="synced"?"directory-durable":"file-flushed",directorySync:n}}function kf(e){let t=Mf(e.snapshot);Yi(e.targetCacheDir,{recursive:!0});let n=or(M(e.targetCacheDir,"cache-lifecycle.lock"),{waitMs:3e4});if(!n)throw new Error("timed out waiting for another cache hydration");let r,i,o=!1;try{r=QC(M(e.targetCacheDir,".shared-hydrate-")),eG(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let l=an(t,c.path),u=an(r,c.path);if(ks(l,u),ml(u).size!==c.size||Zt(u,{inputKind:"hydrated shared-generation artifact",maxBytes:Me})!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let s=Nf(e.targetProjectRoot);if(s!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&UC(an(r,c.path),e.manifest.scipProjectRoot,s);if(!Ji(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=XH(e.targetCacheDir,r),o=!0,QH(r,e.targetCacheDir,i),mC({tempOutputScip:M(r,"index.scip"),tempOutputDb:M(r,"index.db"),tempMetaPath:M(r,"meta.json"),outputScip:M(e.targetCacheDir,"index.scip"),outputDb:M(e.targetCacheDir,"index.db"),metaPath:M(e.targetCacheDir,"meta.json"),now:e.now});let a=xs(M(e.targetCacheDir,"index.db"),M(e.targetCacheDir,"meta.json"));if(a.state==="invalid"||a.state==="drifted")throw new Error(`hydrated SQLite generation failed validation: ${a.reason}`);Tf(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(s){throw o&&i&&ZH(e.targetCacheDir,i),s}finally{r&&fr(r,{recursive:!0,force:!0}),n.release()}}function ov(e,t,n,r){let i=nv(e,n.dbPath,t);if(i)return{kind:"bypassed",reason:i};try{let o=r??ui(e);if(!o)return{kind:"missed",reason:"Git worktree identity is unavailable"};if(!o.clean)return dl(o,n.cacheDir,"missed",void 0,"worktree has uncommitted changes"),{kind:"missed",reason:"worktree has uncommitted changes"};let s=t.languages??bs(e),a=Co(e,s,av(t)),c=ul(o,a);if(!c)return{kind:"missed",reason:"clean committed snapshot is unavailable"};let l=Qr(c);if(l)return kf({snapshot:c,manifest:l,targetCacheDir:n.cacheDir,targetProjectRoot:e}),{kind:"attached",generationId:c.generationId};let u=JH(c,e);return u?(l=u.manifest,kf({snapshot:c,manifest:l,targetCacheDir:n.cacheDir,targetProjectRoot:e,action:"peer-imported"}),{kind:"peer-imported",generationId:c.generationId,sourceProjectRoot:u.sourceProjectRoot}):(dl(o,n.cacheDir,"missed",void 0,"no exact shared or peer generation exists"),{kind:"missed",reason:"no exact shared or peer generation exists"})}catch(o){return{kind:"failed",reason:o instanceof Error?o.message:String(o)}}}function Af(e,t,n,r){let i=nv(e,n.dbPath,t);if(i)return{kind:"bypassed",reason:i};try{let o=r??ui(e);if(!o)return{kind:"missed",reason:"Git worktree identity is unavailable"};if(!o.clean)return dl(o,n.cacheDir,"missed",void 0,"worktree is not a clean committed snapshot"),{kind:"missed",reason:"worktree is not a clean committed snapshot"};let s=t.languages??bs(e),a=Co(e,s,av(t)),c=ul(o,a);if(!c)return dl(o,n.cacheDir,"missed",void 0,"worktree is not a clean committed snapshot"),{kind:"missed",reason:"worktree is not a clean committed snapshot"};let l=Qr(c);if(l)return Ji(n.cacheDir,e,a)?(Tf(c,n.cacheDir,"local-fresh"),{kind:"local-fresh"}):(kf({snapshot:c,manifest:l,targetCacheDir:n.cacheDir,targetProjectRoot:e}),{kind:"attached",generationId:c.generationId});let u=fl(n.cacheDir);return!u||JSON.stringify(u.fingerprint)!==JSON.stringify(a)||JSON.stringify([...u.indexedLanguages??[]].sort())!==JSON.stringify([...s].sort())?{kind:"missed",reason:"local metadata does not match the clean worktree snapshot"}:Ji(n.cacheDir,e,a)?(iv({snapshot:c,sourceCacheDir:n.cacheDir,sourceProjectRoot:e,sourceStillValid:()=>{let d=ui(e);return(d?ul(d,a):void 0)?.generationId===c.generationId}}),Tf(c,n.cacheDir,"built"),{kind:"built",generationId:c.generationId}):{kind:"missed",reason:"local index artifacts are incomplete or incompatible"}}catch(o){return{kind:"failed",reason:o instanceof Error?o.message:String(o)}}}async function tfe(e,t={}){let n=t.timeoutMs??3e4,r=t.pollMs??100,i=t.now??Ae,o=i()+n,s=M(e.repositoryCacheDir,"locks"),a=M(s,`${e.generationId}.lock`),c=l=>{if(!l||typeof l!="object"||Array.isArray(l))return null;let u=l.pid;return typeof u=="number"&&Number.isSafeInteger(u)&&u>0?{pid:u}:null};for(;i()<=o;){if(Qr(e))return{kind:"generation-ready"};let l=Gi(a,{kind:"shared-generation-build",detail:{generationId:e.generationId},parseLegacy:c});if(l.kind==="acquired")return{kind:"owner",release:()=>l.lock.release()};let u=o-i();if(u<=0)break;await zH(Math.min(r,u))}return Qr(e)?{kind:"generation-ready"}:{kind:"timeout"}}function Tf(e,t,n,r=void 0){let i={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,baseGenerationId:e.generationId,activeGenerationId:e.generationId,lastAction:n,lastSeenAt:(r??(()=>new Date))().toISOString()},o={...i,ownershipChecksum:Lf(i)};return cv(e.repositoryCacheDir,o,!0),o}function dl(e,t,n,r=void 0,i=void 0){let o={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,lastAction:n,...i?{lastReason:i}:{},lastSeenAt:(r??(()=>new Date))().toISOString()},s={...o,ownershipChecksum:Lf(o)};return cv(ps(e.repositoryId),s,!1),s}function Lf(e){return uv(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:_n(e.projectRoot),localCacheDir:_n(e.localCacheDir)}))}function sv(e,t,n=void 0,r,i={}){try{let o=YC(t);if(!o)return null;let s=ps(o.repositoryId);i.onBeforeRepositoryLock?.();let a=Tm(s,{waitMs:5e3});if(!a)return null;try{let c=YC(t);if(!c||c.repositoryId!==o.repositoryId||c.worktreeId!==o.worktreeId)return null;let l=M(s,"worktrees",`${c.worktreeId}.json`),u=JSON.parse(J(l,{inputKind:"worktree cache lease",maxBytes:Ie})),d=r??ui(e);if(!d?.clean||!d.treeOid||u.version!==1||u.repositoryId!==c.repositoryId||u.worktreeId!==c.worktreeId||u.repositoryId!==d.repositoryId||u.worktreeId!==d.worktreeId||_n(u.projectRoot)!==_n(d.projectRoot)||u.treeOid!==d.treeOid||_n(u.localCacheDir)!==_n(t)||u.ownershipChecksum!==Lf(u))return null;let m=fl(t);if(!tG(m?.fingerprint))return null;let f=ul(d,m.fingerprint);if(!f||f.repositoryCacheDir!==s||u.baseGenerationId!==f.generationId||u.activeGenerationId!==f.generationId||!Ji(t,e,f.fingerprint,!0,!1))return null;let p=(n??(()=>new Date))();if(Number.isFinite(Date.parse(u.lastSeenAt))&&p.getTime()-Date.parse(u.lastSeenAt)<6e4)return u;let g={...u,lastSeenAt:p.toISOString()};return vt(l,g,{spacing:2,trailingNewline:!0}),g}finally{a.release()}}catch{return null}}function KH(e){let t=JSON.parse(e);if(t.version!==Ff||t.artifactCatalogVersion!==Es||typeof t.generationId!="string"||!/^[a-f0-9]{64}$/.test(t.generationId)||typeof t.repositoryId!="string"||!/^[a-f0-9]{24}$/.test(t.repositoryId)||typeof t.treeOid!="string"||!t.treeOid||typeof t.producerIdentity!="string"||t.producerIdentity!==Pf||typeof t.sourceProjectRoot!="string"||typeof t.scipProjectRoot!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!t.fingerprint||!Array.isArray(t.artifacts))throw new Error("invalid shared generation manifest");let n=new Set;for(let r of t.artifacts){if(!r||typeof r.path!="string"||typeof r.size!="number"||r.size<0||typeof r.sha256!="string"||!/^[a-f0-9]{64}$/.test(r.sha256))throw new Error("invalid shared generation artifact");if(ll(r.path),n.has(r.path))throw new Error(`duplicate shared generation artifact: ${r.path}`);n.add(r.path)}for(let r of["index.db","index.scip","meta.json"])if(!n.has(r))throw new Error(`shared generation is missing ${r}`);return t}function ks(e,t,n=384){return Ho(e,t,{mode:n})}function JH(e,t){for(let n of Rh(t)){if(_n(n.path)===_n(t))continue;let r=Vc(n.path),i=fl(r);if(!(!i||JSON.stringify(i.fingerprint)!==JSON.stringify(e.fingerprint)||JSON.stringify([...i.indexedLanguages??[]].sort())!==JSON.stringify([...e.fingerprint.languages].sort()))&&Ji(r,n.path,e.fingerprint))try{return{manifest:iv({snapshot:e,sourceCacheDir:r,sourceProjectRoot:n.path}).manifest,sourceProjectRoot:n.path}}catch{continue}}return null}function YH(e,t,n){Yi(e,{recursive:!0}),vt(M(e,tv),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function JC(e){try{let t=cl(e),n=XC("sha256");for(let r of t.files){let i=an(e,r),o=ml(i).size;n.update(r).update("\0").update(String(o)).update("\0"),pi(i,{inputKind:"source-generation artifact",maxBytes:Me},s=>n.update(s)),n.update("\0")}return n.digest("hex")}catch{return null}}function fl(e){try{let t=Jt(J(M(e,"meta.json"),{inputKind:"reindex metadata",maxBytes:Ie}));return(t.kind==="legacy"||t.kind==="supported")&&t.capabilities.publishableGeneration?t.metadata:void 0}catch{return}}function av(e){return{pnpmWorkspaces:e.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:e.indexer?.typescript?.projectMode,typescriptProjects:e.indexer?.typescript?.projects,clojureConfigPath:e.indexer?.clojure?.configPath}}function Mf(e){return M(e.repositoryCacheDir,"generations",e.generationId)}function YC(e){let t=JSON.parse(J(M(e,tv),{inputKind:"worktree cache pointer",maxBytes:Ie}));return t.version!==1||typeof t.repositoryId!="string"||!/^[a-f0-9]{24}$/.test(t.repositoryId)||typeof t.worktreeId!="string"||!/^[a-f0-9]{24}$/.test(t.worktreeId)?null:{version:t.version,repositoryId:t.repositoryId,worktreeId:t.worktreeId}}function cv(e,t,n){let r=Tm(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId;if(!o||!pr(M(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=M(e,"worktrees");Yi(i,{recursive:!0}),vt(M(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),YH(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function XH(e,t){let n=M(t,".rollback"),r=new Map,i=new Map;Yi(n,{recursive:!0});for(let a of["index.scip","index.db","meta.json"]){let c=M(e,a),l=pr(c);r.set(a,l),l&&ks(c,M(n,"stable",a))}for(let a of _f){let c=M(e,a),l=pr(c);if(l){let u=qH(c);if(!u.isDirectory()||u.isSymbolicLink())throw new Error(`managed artifact path is not a directory: ${a}`)}i.set(a,l)}let o=M(e,as),s=pr(o);return s&&lv(o,M(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:s}}function QH(e,t,n){for(let r of _f){let i=M(t,r);if(n.managedDirectories.get(r)){let s=M(n.root,"managed",r);Yi(Df(s),{recursive:!0}),Xr(i,s)}let o=M(e,r);pr(o)&&Xr(o,i)}}function ZH(e,t){for(let i of _f){let o=M(e,i),s=M(t.root,"managed",i);t.managedDirectories.get(i)?pr(s)&&(fr(o,{recursive:!0,force:!0}),Xr(s,o)):fr(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let s=M(e,i);if(!o){fr(s,{force:!0});continue}let a=`${s}.shared-restore-${GH()}`;ks(M(t.root,"stable",i),a),fr(s,{force:!0}),Xr(a,s)}let n=M(e,as);fr(n,{recursive:!0,force:!0});let r=M(t.root,"sqlite-generations");t.generationStoreExisted&&pr(r)&&Xr(r,n)}function lv(e,t){Yi(t,{recursive:!0});for(let n of UH(e,{withFileTypes:!0})){let r=M(e,n.name),i=M(t,n.name);if(n.isSymbolicLink())throw new Error(`managed cache backup cannot contain a symlink: ${r}`);n.isDirectory()?lv(r,i):n.isFile()&&ks(r,i)}}function eG(e,t){if(e.generationId!==t.generationId||e.repositoryId!==t.repositoryId||e.treeOid!==t.treeOid||e.producerIdentity!==t.producerIdentity||JSON.stringify(e.fingerprint)!==JSON.stringify(t.fingerprint))throw new Error("shared generation manifest does not match the requested snapshot")}function Ji(e,t,n,r=!0,i=!0){try{let o=fl(e);if(!o||JSON.stringify(o.fingerprint)!==JSON.stringify(n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return Ps("source validation rejected metadata"),!1;let s=cl(e),a=xs(M(e,"index.db"),M(e,"meta.json"));if(r?a.state!=="current":a.state==="invalid"||a.state==="drifted")return Ps(`source validation rejected SQLite generation state ${a.state}`),!1;let c=new WH(M(e,"index.db"),{readonly:!0,fileMustExist:!0});try{if(i){if(c.pragma("quick_check(1)",{simple:!0})!=="ok")return!1}else c.pragma("schema_version",{simple:!0})}finally{c.close()}let l=Nf(t),d=(i?s.files.filter(m=>m.endsWith(".scip")):["index.scip"]).every(m=>{let f=ZC(Se(an(e,m),{inputKind:"shared SCIP validation artifact",maxBytes:Me})).metadata?.projectRoot;return f!==l&&Ps(`source validation rejected SCIP root for ${m}: ${String(f)}`),f===l});return d||Ps("source validation rejected SCIP project roots"),d}catch(o){return Ps(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function Ps(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function Nf(e){try{return zC(VH(e)).href}catch{return zC(_n(e)).href}}function tG(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===2&&Array.isArray(t.languages)&&typeof t.pnpmWorkspaces=="boolean"&&(t.typescriptProjectMode==="single"||t.typescriptProjectMode==="workspace")&&Array.isArray(t.typescriptProjects)&&Array.isArray(t.files)&&t.files.every(n=>n!==null&&typeof n=="object"&&typeof n.path=="string"&&typeof n.size=="number"&&typeof n.hash=="string")}function uv(e){return XC("sha256").update(e).digest("hex")}function dv(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var Of,pl;function mfe(e){Of=e}function ffe(){return pl}function mv(e=dv(),t=void 0){if(t===void 0&&Of?.projectRoot===e)return Of;let n=ZR(e),r=PR(e,n),i=process.env.SCIP_QUERY_INDEX_DB;if(i)return{projectRoot:e,config:n,paths:r,dbPath:i,dbPathSource:"env",gitContext:t};if(Bf(r.dbPath))return{projectRoot:e,config:n,paths:r,dbPath:r.dbPath,dbPathSource:"configured",gitContext:t};let o=rG(e,"index.db");return{projectRoot:e,config:n,paths:r,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:aG(o,r.dbPath),gitContext:t}}function pfe(e){return mv(e).dbPath}function gfe(e,t,n,r={}){return Bf(n.dbPath)&&sv(e,n.cacheDir,void 0,r.gitContext)?{kind:"local-fresh"}:r.gitContext?.clean===!1&&r.watcherGeneration!==void 0&&Qx(n.dbPath)===r.watcherGeneration?Af(e,t,n,r.gitContext):SC(e,t,n).state==="fresh"?Af(e,t,n,r.gitContext):ov(e,t,n,r.gitContext)}function hfe(e){return!e.startsWith("__")&&!iG.has(e)}var iG=new Set(["bench","config-validate","hook-context","hook-stop","init","setup","setup-agent","setup-ci","setup-hooks","uninstall","work-audit"]);function oG(){try{return sG(dv(),{warnOnRootFallback:!0})}catch(e){console.error(`error: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}function sG(e,t={}){let{config:n,paths:r,dbPath:i,dbPathSource:o,rootFallbackWarning:s,gitContext:a}=mv(e);if(!Bf(i))throw new Error("No index.db found. Run: scip-query reindex");t.warnOnRootFallback&&o==="root-fallback"&&s&&console.error(s);let c={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??r.indexPath,projectRoot:e,sharedEvidenceDbPath:rv(e,n,a),entryRoots:n.entryRoots,semantic:n.semantic,suppressions:n.suppressions,declaredCouplings:n.declaredCouplings,locality:n.locality,architecture:n.architecture,coverageContracts:n.coverageContracts,docs:n.docs},l=MR(e);return new Wc(c,l)}function aG(e,t){let n="unknown time";try{n=nG(e).mtime.toISOString()}catch{}return`warning: using legacy project-root index.db (${e}, modified ${n}) because the configured index was not found at ${t}. This fallback may be stale; run 'scip-query reindex' to refresh the configured index.`}function An(e){let t=oG(),n=pl;pl=t;try{return e(t)}finally{pl=n,t.close()}}function yfe(e,t){return t.concat([e])}function fv(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(0)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function bfe(e){switch(e.state){case"idle":return"Watching (idle)";case"waiting":{let t=Math.round((e.reindexAt-Date.now())/1e3);return`${e.changedFiles} file(s) changed, reindexing in ${t}s...`}case"indexing":return`Reindexing... (${Math.round((Date.now()-e.startedAt)/1e3)}s)`;case"cooldown":return`Cooldown (${Math.round((e.until-Date.now())/1e3)}s)${e.dirty?" \u2014 changes pending":""}`;case"draining":return`Stopping safely \u2014 ${e.reason}`;default:return cG(e)}}function cG(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}var lG=new Map([[8,"\u2408"],[9,"\u2409"],[10,"\u2424"],[13,"\u240D"]]);function pv(e,t={}){let n=t.allowNewlines??!0,r=t.allowTabs??!0,i="";for(let o=0;o<e.length;){let s=e.charCodeAt(o);if(s===27){o=uG(e,o);continue}if(s===155){o=gv(e,o+1);continue}if(s===144||s===152||s===157||s===158||s===159){o=hv(e,o+1);continue}if(fG(s)){s===10&&n?i+=`
|
|
411
|
+
`:s===9&&r?i+=" ":i+=lG.get(s)??"\uFFFD",o+=1;continue}if(pG(s)){i+="\uFFFD",o+=1;continue}i+=e[o],o+=1}return i}function Ot(e){return pv(e,{allowNewlines:!1,allowTabs:!1})}function Xi(e,t=n=>process.stdout.write(n)){t(`${e}
|
|
412
|
+
`)}function xfe(e=console){let t={log:e.log.bind(e),error:e.error.bind(e),warn:e.warn.bind(e)};return e.log=(...n)=>t.log(...n.map(jf)),e.error=(...n)=>t.error(...n.map(jf)),e.warn=(...n)=>t.warn(...n.map(jf)),()=>{e.log=t.log,e.error=t.error,e.warn=t.warn}}function jf(e){return typeof e=="string"?pv(e):e}function uG(e,t){let n=e.charCodeAt(t+1);if(Number.isNaN(n))return e.length;if(n===91)return gv(e,t+2);if(n===80||n===88||n===93||n===94||n===95)return hv(e,t+2);let r=t+1;for(;r<e.length&&dG(e.charCodeAt(r));)r+=1;return r<e.length&&mG(e.charCodeAt(r))?r+1:t+1}function gv(e,t){let n=t;for(;n<e.length;){let r=e.charCodeAt(n);if(n+=1,r>=64&&r<=126)return n}return e.length}function hv(e,t){let n=t;for(;n<e.length;){let r=e.charCodeAt(n);if(r===7||r===156)return n+1;if(r===27&&e.charCodeAt(n+1)===92)return n+2;n+=1}return e.length}function dG(e){return e>=32&&e<=47}function mG(e){return e>=48&&e<=126}function fG(e){return e<=31||e>=127&&e<=159}function pG(e){return e===1564||e===8206||e===8207||e>=8234&&e<=8238||e>=8294&&e<=8297}function yv(e){return e+1}function gG(e,t){return`${yv(e)}-${yv(t)}`}function vfe(e,t,n){return`${Ot(e)}:${gG(t,n)}`}function Ife(e,t=180){let n=Ot(e).replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var cn={empty(e){console.log(Ot(e))},list(e,t){for(let n of e)console.log(Ot(t(n)))},groupedByFile(e,t,n=r=>r.relativePath){let r="";for(let i of e){let o=n(i);o!==r&&(r&&console.log(""),console.log(Ot(o)),r=o),console.log(Ot(t(i)))}},sectionedReport(e){let t=!0;for(let n of e)if(!(n.skipIfEmpty&&n.rows.length===0)){t||console.log(""),t=!1,n.title!==void 0&&console.log(`\u2550\u2550\u2550 ${Ot(n.title)} \u2550\u2550\u2550`),n.explanation!==void 0&&console.log(Ot(n.explanation));for(let r of n.rows)console.log(Ot(r))}},table(e,t,n){console.log(` ${e.map(Ot).join(" ")}`);let r=n??e.map(i=>i.length);console.log(` ${r.map(i=>"\u2500".repeat(i)).join(" ")}`);for(let i of t)console.log(Ot(i))}};import{availableParallelism as DZ}from"os";import{fileURLToPath as Ng}from"url";import{existsSync as gl,readdirSync as xv}from"fs";import{join as Ts}from"path";var hG={files:new Set,pathPrefixes:[]},yG={reasonsByFile:new Map},$f=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,bG=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,Rv=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],SG=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),xG=4,RG=z("package-surface",{clearGroups:["whole-project"]}),CG=z("package-operational-surface",{clearGroups:["whole-project"]});function vG(e){return RG.get(e,()=>wG(e.config.projectRoot))}function Mn(e,t){let n=vG(e);return n.files.has(t)?!0:n.pathPrefixes.some(r=>t.startsWith(r))}function IG(e){return CG.get(e,()=>EG(e.config.projectRoot))}function Cv(e,t){return IG(e).reasonsByFile.get(t)??[]}function wG(e){let t=new Set,n=[];for(let{manifest:r,packageRoot:i}of vv(e))for(let o of DG(r))Dv(e,i,o,t,n);return t.size===0&&n.length===0?hG:{files:t,pathPrefixes:n}}function EG(e){let t=new Map;for(let{manifest:n,packageRoot:r}of vv(e)){let i=PG(n);for(let s of i)bv(e,r,s,"package binary",t);let o=n.scripts;if(!(!o||typeof o!="object")){for(let[s,a]of Object.entries(o))if(typeof a=="string")for(let c of kG(a))bv(e,r,c,`package script "${s}"`,t)}}return t.size===0?yG:{reasonsByFile:t}}function vv(e){let t=[],n=wv(e,"");return n&&t.push({manifest:n,packageRoot:""}),Iv(e,"",t,0),t}function Iv(e,t,n,r){if(r>=xG)return;let i=Ts(e,t);if(gl(i))for(let o of xv(i,{withFileTypes:!0})){if(!o.isDirectory()||SG.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=wv(e,s);a&&n.push({manifest:a,packageRoot:s}),Iv(e,s,n,r+1)}}function wv(e,t){let n;try{n=de(e,Ts(t,"package.json"),{maxBytes:8*1024*1024,inputKind:"package manifest"})}catch(r){if(!we(r))throw r;return null}try{let r=JSON.parse(n);return r&&typeof r=="object"?r:null}catch{return null}}function DG(e){let t=[];for(let r of["main","module","types","browser"])typeof e[r]=="string"&&t.push(e[r]);let n=e.bin;if(typeof n=="string")t.push(n);else if(n&&typeof n=="object")for(let r of Object.values(n))typeof r=="string"&&t.push(r);return Ev(e.exports,t),t}function PG(e){let t=e.bin;return typeof t=="string"?[t]:!t||typeof t!="object"?[]:Object.values(t).filter(n=>typeof n=="string")}function kG(e){let t=[],n=/(?:^|&&|\|\||;)\s*(?:(?:cross-env|env)(?:\s+[A-Za-z_][A-Za-z0-9_]*=\S+)*\s+)?(?:node|bun|tsx|ts-node|vite-node|python3?|deno\s+run)\s+(?:(?:--?[A-Za-z0-9-]+(?:=\S+)?)\s+)*["']?([^"'`\s]+\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs|py))["']?/g;for(let r of e.matchAll(n)){let i=r[1];i&&!i.startsWith("node_modules/")&&!i.startsWith("./node_modules/")&&t.push(i)}return t}function bv(e,t,n,r,i){let o=new Set;Dv(e,t,n,o,[]);for(let s of o){let a=i.get(s)??[];a.includes(r)||a.push(r),i.set(s,a)}}function Ev(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))Ev(n,t)}function Dv(e,t,n,r,i){let o=n.replace(/\\/g,"/").replace(/^\.\//,"");if(o===""||o.startsWith(".."))return;let s=o.indexOf("*");if(s>=0){let c=o.slice(0,s);for(let l of Sv(c))l!==""&&i.push(Ln(t,l));return}let a=o.replace(bG,"");for(let c of Sv(a)){c===a&&c===o&&r.add(Ln(t,o));for(let l of Rv)TG(e,r,t,c+l)}r.add(Ln(t,o))}function Sv(e){let t=[e];return $f.test(e)&&(t.push(e.replace($f,"src/")),t.push(e.replace($f,""))),t}function TG(e,t,n,r){let i=Ln(n,r);if(t.add(i),!r.startsWith("src/")||gl(Ts(e,i)))return;let o=Rv.find(u=>r.endsWith(u));if(!o)return;let s=r.slice(0,-o.length);FG(e,t,n,s,o);let a=s.lastIndexOf("/");if(a<=4)return;let c=s.slice(0,a),l=s.slice(a+1);for(let u of Pv(e,n,c,`${l}${o}`))t.add(u)}function FG(e,t,n,r,i){let o=Ln(n,`${r}/index${i}`);gl(Ts(e,o))&&t.add(o)}function Pv(e,t,n,r){let i=Ts(e,t,n);if(!gl(i))return[];let o=[];for(let s of xv(i,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...Pv(e,t,a,r)):s.isFile()&&s.name===r&&o.push(Ln(t,a))}return o}function Ln(e,t){return e?`${e}/${t}`:t}import{existsSync as Hf,readdirSync as _G}from"fs";import{dirname as AG,join as Gf}from"path";var LG={rootFiles:new Set,sourcePrefixes:[]},MG=new Set([".git",".scipquery","node_modules","target"]),NG=6,OG=z("rust-library-surface",{clearGroups:["whole-project"]});function kv(e,t,n){if(!n.endsWith(".rs")||!$G(BG(e),n))return!1;let r=ie(e,n).find(i=>i.symbol===t);return r?HG(Ne(e,n)[r.startLine]??""):!1}function BG(e){return OG.get(e,()=>jG(e.config.projectRoot))}function jG(e){let t=new Set,n=new Set;for(let r of GG(e)){let i=de(e,Gf(r,"Cargo.toml"),{maxBytes:8388608,inputKind:"Cargo manifest"}),o=qG(i),s=Ln(r,"src/lib.rs"),a=o?Ln(r,o):!UG(i)&&st(e,s)?s:null;if(!a)continue;t.add(a);let c=AG(a).replaceAll("\\","/");n.add(c==="."?"":`${c}/`)}return t.size===0?LG:{rootFiles:t,sourcePrefixes:[...n].sort()}}function $G(e,t){return t.endsWith(".rs")?e.rootFiles.has(t)?!0:VG(t)?!1:e.sourcePrefixes.some(n=>t.startsWith(n)):!1}function HG(e){return/^\s*pub\s+(?!\()/.test(e)}function GG(e){if(!Hf(e))return[];let t=[];return Tv(e,"",t,0),t}function Tv(e,t,n,r){let i=Gf(e,t);if(Hf(i)&&(Hf(Gf(i,"Cargo.toml"))&&n.push(t),!(r>=NG)))for(let o of _G(i,{withFileTypes:!0})){if(!o.isDirectory()||MG.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name;Tv(e,s,n,r+1)}}function qG(e){let t=!1;for(let n of e.split(`
|
|
413
|
+
`)){let r=n.replace(/\s+#.*$/,"").trim(),i=/^\[([^\]]+)\]$/.exec(r);if(i){t=i[1]==="lib";continue}if(!t)continue;let o=/^path\s*=\s*["']([^"']+)["']/.exec(r)?.[1];if(o)return o.replaceAll("\\","/").replace(/^\.\//,"")}return null}function UG(e){let t=!1;for(let n of e.split(`
|
|
414
|
+
`)){let r=n.replace(/\s+#.*$/,"").trim(),i=/^\[([^\]]+)\]$/.exec(r);if(i){t=i[1]==="package";continue}if(t&&/^autolib\s*=\s*false\b/.test(r))return!0}return!1}function VG(e){return/(?:^|\/)src\/main\.rs$/.test(e)||/(?:^|\/)src\/bin\//.test(e)||/(?:^|\/)(?:examples|tests|benches)\//.test(e)}function U(e){let t=te(e);return aq(t)?"test":cq(t)?"worker":lq(t)?"entry":uq(t)?"barrel":"source"}function Qi(e){return U(e)==="barrel"}function _v(e){return zG.get(e,()=>{let n=L(e,{includeIgnored:!1}).filter(s=>{let a=U(s);return a==="entry"||a==="worker"});if(n.length===0)return new Set;let r=le(e),i=new Set,o=new Set;for(;n.length>0;){let s=n.shift();if(!i.has(s)){i.add(s),U(s)==="barrel"&&o.add(s);for(let a of r.get(s)??[])i.has(a)||n.push(a)}}return o})}var zG=z("live-barrels",{clearGroups:["whole-project"]});function qf(e,t){return _v(e).has(te(t))}function Av(e){let t=_v(e);return L(e,{includeIgnored:!1}).filter(n=>Qi(n)&&!t.has(n)&&!WG(e,n))}function WG(e,t){let n=te(t),r=Lt(e).forFile(n,{facts:!0}).facts?.callables;return r&&r.length>0?!0:(e.get(`SELECT COUNT(*) AS n
|
|
415
|
+
FROM defn_enclosing_ranges der
|
|
416
|
+
JOIN documents d ON d.id = der.document_id
|
|
417
|
+
WHERE d.relative_path = ?
|
|
418
|
+
AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function Ue(e,t){let n=te(t),r=U(t);return r==="entry"||r==="worker"||Uf(n)||qf(e,n)}function Re(e,t,n){let r=te(n);if(Mn(e,r)||JG(e,t,r)||kv(e,t,r)||iq(t,r))return!0;let i=e.config.entryRoots;return i?!!(i.files?.some(o=>te(o)===r)||i.pathPrefixes?.some(o=>r.startsWith(te(o)))||i.qualifiedVars?.some(o=>dq(t,o))||i.symbolPatterns?.some(o=>{try{return hs(o,"entryRoots.symbolPatterns entry").test(t)}catch{return!1}})):!1}var KG=z("package-surface-reachability",{clearGroups:["whole-project"]});function JG(e,t,n){let r=YG(e).get(n);return r===void 0?!1:r===null||r.has(T(t))}function YG(e){return KG.get(e,()=>{let t=new Map,n=[];for(let r of L(e,{includeIgnored:!1}))Mn(e,r)&&(t.set(r,null),n.push(r));for(;n.length>0;){let r=n.shift(),i=t.get(r);if(i!==void 0)for(let o of wn(e,r)){if(!o.sourcePath||e.isIgnored(o.sourcePath))continue;let s=XG(i,o);s!==void 0&&QG(t,o.sourcePath,s)&&n.push(o.sourcePath)}}return t})}function XG(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;let n=t.names.filter(r=>e.has(r));return n.length>0?new Set(n):void 0}function QG(e,t,n){if(!e.has(t))return e.set(t,n),!0;let r=e.get(t);if(r===void 0)return!1;if(r===null||n===null)return r===null?!1:(e.set(t,null),!0);let i=!1;for(let o of n)r.has(o)||(r.add(o),i=!0);return i}var Lv=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),ZG=new Set(["default","generateMetadata","generateStaticParams"]),eq=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),tq=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),nq=new Set(["load","actions","entries",...Lv]),rq=new Set(["default"]);function iq(e,t){let n=T(e);return n===""?!1:Mv(t)?Lv.has(n):Nv(t)?ZG.has(n):Ov(t)?eq.has(n):Bv(t)?tq.has(n):jv(t)?nq.has(n):sq(t)?rq.has(n):!1}function Uf(e){return Mv(e)||Nv(e)||Ov(e)||oq(e)||Bv(e)||jv(e)}function Mv(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Nv(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function Ov(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function oq(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 Bv(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function jv(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function sq(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function aq(e){return!!(/\.(?:test|spec)\.[a-z0-9]+$/i.test(e)||/(?:^|\/)(?:_)?test_[^/]+$/i.test(e)||/(?:^|\/)spec_[^/]+$/i.test(e)||/(?:^|\/)[^/]+_test\.[a-z0-9]+$/i.test(e)||/(?:^|\/)[^/]+_tests\.rs$/i.test(e)||/(?:^|\/)tests\.rs$/i.test(e)||/(?:^|\/)[^/]+_spec\.[a-z0-9]+$/i.test(e)||/(?:^|\/)__tests__\//i.test(e)||/(?:^|\/)test\//i.test(e)||/(?:^|\/)tests\//i.test(e)||/(?:^|\/)__fixtures__\//i.test(e)||/(?:^|\/)__mocks__\//i.test(e)||/(?:^|\/)test-support\//i.test(e)||/(?:^|\/)test-utils\//i.test(e)||/(?:^|\/)testing\//i.test(e))}function cq(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function lq(e){let t=e.split("/"),n=t[t.length-1]??e;return n==="cli.ts"||n==="cli.js"||n==="postinstall.ts"||n==="postinstall.js"||n==="main.ts"||n==="main.js"||n==="main.rs"||n==="main.go"||n==="main.py"||n==="build.rs"||n==="lib.rs"||/\bsrc\/bin\/[^/]+\.rs$/.test(e)||/(?:^|\/)examples\/[^/]+\.rs$/.test(e)||/(?:^|\/)tests\/[^/]+\.rs$/.test(e)||/(?:^|\/)benches\/[^/]+\.rs$/.test(e)?!0:n==="index.ts"||n==="index.js"?/(?:^|\/)(?:apps|services)\/[^/]+\/src\/index\.(?:ts|js)$/.test(e)?!0:t.length<=2:!1}function uq(e){return e==="index.ts"||e==="index.js"||e.endsWith("/index.ts")||e.endsWith("/index.js")||e.endsWith("/mod.rs")||e.endsWith("/__init__.py")}function dq(e,t){let n=t.lastIndexOf("/");if(n<0)return!1;let r=t.slice(0,n),i=t.slice(n+1);return e.includes(Fv(r)+"/")&&e.includes(Fv(i)+".")}function Fv(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}import{SymbolInformation_Kind as Q}from"@c4312/scip";var hl=new Map(Object.entries(Q).filter(([e,t])=>Number.isInteger(Number(e))&&typeof t=="string").map(([e,t])=>[Number(e),t])),$v=new Map([...hl.entries()].map(([e,t])=>[t.toLowerCase(),e]));function Fs(e){return hl.get(e)??"Unknown"}function ln(){return[Q.Function,Q.Method,Q.Macro,Q.Constructor,Q.Getter,Q.Setter,Q.StaticMethod,Q.SingletonMethod,Q.AbstractMethod,Q.ProtocolMethod,Q.TraitMethod]}function Hv(){return[Q.Class,Q.Interface,Q.Struct,Q.Trait,Q.Type,Q.TypeAlias,Q.Enum,Q.Union,Q.Protocol]}function Xfe(){return[Q.Constant,Q.Variable,Q.Value,Q.Field,Q.Property,Q.StaticDataMember,Q.StaticField,Q.StaticProperty,Q.StaticVariable,Q.EnumMember]}function Bt(e,t,n={}){let r=yl(e,[t],{additive:n.additive,semantic:n.semantic,semanticEvidence:n.semanticEvidence}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(o=>ye(o.symbol)||o.source==="ast-callsite"):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function Nn(e,t,n){return _s(e,[t],n).get(t.symbolId)??[]}function _s(e,t,n){let r=gq(e)?yq(e,t,{semantic:n.semantic!==!1,semanticEvidence:n.semanticEvidence}):hq(e,n.semanticEvidence);return typeof n.limit!="number"?new Map(t.map(i=>[i.symbolId,r.get(i.symbolId)??[]])):new Map(t.map(i=>[i.symbolId,(r.get(i.symbolId)??[]).slice(0,n.limit)]))}var mq=z("caller-rows",{clearGroups:["whole-project"]}),fq=z("targeted-caller-strategy",{clearGroups:["whole-project"]}),pq=2e4;function gq(e){return fq.get(e,()=>(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>pq)}function hq(e,t){return mq.get(e,()=>{let n=Oe(e),r=yl(e,n,{semanticEvidence:t}),i=new Map;for(let a of n)i.set(a.symbol,a.symbolId);let o=new Map,s=new Map;for(let a of n){let c=r.get(a.symbolId);if(!(!c||c.length===0))for(let l of c){let u=i.get(l.symbol);if(u===void 0||u===a.symbolId)continue;let d=o.get(u);d||(d=[],o.set(u,d),s.set(u,new Set));let m=`${a.symbol}|${a.relativePath}`;s.get(u).has(m)||(s.get(u).add(m),d.push({symbol:a.symbol,file:a.relativePath,source:"caller-map-inversion"}))}}return o})}function yq(e,t,n){let r=n.semantic&&n.semanticEvidence?t.flatMap(c=>{let l=bq(e,c);return l?[l]:[]}):[],i=new Map(r.map(c=>[c.symbolId,c])),o=n.semanticEvidence?.referenceMap(e,r)??new Map,s=Fd(e,t),a=new Map;for(let c of t){let l=[],u=new Set,d=f=>{if(f.symbol===c.symbol)return;let p=`${f.symbol}|${f.file}`;u.has(p)||(u.add(p),l.push(f))};for(let f of s.get(c.symbolId)??[])f.file!==c.relativePath&&d({symbol:f.enclosingSymbol??f.file,file:f.file,source:"resolved-reference"});let m=i.get(c.symbolId);if(m)for(let f of o.get(m.symbolId)??[]){if(f.file===c.relativePath||e.isIgnored(f.file))continue;let p=tn(ie(e,f.file),f.line);d({symbol:p?.symbol??f.file,file:f.file,source:"semantic-reference"})}a.set(c.symbolId,l)}return a}function bq(e,t){let n=ln().join(", "),r=Hv().join(", ");return e.get(`SELECT
|
|
419
|
+
d.id AS documentId,
|
|
420
|
+
gs.id AS symbolId,
|
|
421
|
+
gs.symbol,
|
|
422
|
+
d.relative_path AS relativePath,
|
|
423
|
+
COALESCE(der.start_line, c.start_line) AS startLine,
|
|
424
|
+
COALESCE(der.end_line, c.end_line) AS endLine,
|
|
425
|
+
COALESCE(gs.display_name, '') AS leaf,
|
|
426
|
+
NULL AS parentTypeName,
|
|
427
|
+
CASE WHEN gs.kind IN (${n}) OR gs.symbol LIKE '%().' THEN 1 ELSE 0 END AS isFunctionLike,
|
|
428
|
+
CASE WHEN gs.kind IN (${r}) THEN 1 ELSE 0 END AS isTypeLike,
|
|
429
|
+
gs.kind AS kind,
|
|
430
|
+
gs.documentation AS documentation,
|
|
431
|
+
gs.enclosing_symbol AS enclosingSymbol
|
|
432
|
+
FROM global_symbols gs
|
|
433
|
+
LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
434
|
+
LEFT JOIN chunks c ON c.document_id = der.document_id
|
|
435
|
+
JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
|
|
436
|
+
WHERE gs.id = ?
|
|
437
|
+
LIMIT 1`,t.symbolId)??null}function yl(e,t,n={}){if(t.length===0)return new Map;let r=n.additive??!1,i=[],o=[];for(let u of t)N(u.relativePath)&&Kn(e,u.relativePath)!==null?i.push(u):o.push(u);let s=new Map,a=new Map,c=u=>{for(let[d,m]of u){let f=s.get(d);f||(f=[],s.set(d,f));let p=a.get(d);p||(p=new Set,a.set(d,p));for(let g of m){let y=`${g.symbol}|${g.chunkId}`;p.has(y)||(p.add(y),f.push(g))}}};i.length>0&&c(Sq(e,i)),n.semantic!==!1&&n.semanticEvidence&&c(wq(n.semanticEvidence.calleeMap(e,t)));let l=r?t:o;return l.length>0&&c(vq(e,l)),s}function Sq(e,t){let n=new Map,r=xq(t,n),i=kn(e);for(let[o,s]of r){let a=Kn(e,o);if(!a)continue;let c=Pd(s);for(let l of a){let u=c.get(l.line);if(!u)continue;let d=Rq(e,o,i,l);d&&d.symbol!==u.symbol&&n.get(u.symbolId).push({symbol:d.symbol,file:d.file,chunkId:l.line,source:"ast-callsite"})}}return n}function xq(e,t){let n=new Map;for(let r of e){let i=n.get(r.relativePath);i?i.push(r):n.set(r.relativePath,[r]),t.set(r.symbolId,[])}for(let r of n.values())r.sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine));return n}function Rq(e,t,n,r){let i=rc(t,n.get(r.calleeLeaf)??[]);if(i.length===0)return null;let o=Cq(e,t,i,r.calleeQualifier);return o||ic(e,t,i,r.memberAccess)}function Cq(e,t,n,r){if(!r||N(t)!=="clojure")return null;let o=oe(e,t).filter(s=>s.kind==="namespace"&&s.localName===r&&s.sourcePath).map(s=>s.sourcePath);for(let s of o){let a=n.find(c=>gt(s,c.file));if(a)return a}return n.find(s=>/`([^`]+)`\//.exec(s.symbol)?.[1]===r)??null}function vq(e,t){if(t.length===0)return new Map;let r=Vf(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
|
|
438
|
+
FROM mentions m
|
|
439
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
440
|
+
WHERE m.role != 1
|
|
441
|
+
AND c.document_id IN (${f.map(()=>"?").join(",")})`,...f)),i=new Map;for(let f of r)i.has(f.document_id)||i.set(f.document_id,[]),i.get(f.document_id).push(f);let s=Vf(r.map(f=>f.symbol_id)).flatMap(f=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
|
|
442
|
+
COALESCE(der.document_id, def_chunk.document_id) AS document_id
|
|
443
|
+
FROM global_symbols gs
|
|
444
|
+
LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
445
|
+
LEFT JOIN (
|
|
446
|
+
SELECT m.symbol_id, MIN(c.document_id) AS document_id
|
|
447
|
+
FROM mentions m
|
|
448
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
449
|
+
WHERE m.role = 1
|
|
450
|
+
AND m.symbol_id IN (${f.map(()=>"?").join(",")})
|
|
451
|
+
GROUP BY m.symbol_id
|
|
452
|
+
) def_chunk ON def_chunk.symbol_id = gs.id
|
|
453
|
+
WHERE gs.id IN (${f.map(()=>"?").join(",")})`,...f,...f)),a=Vf([...t.map(f=>f.documentId),...s.flatMap(f=>f.document_id===null?[]:[f.document_id])]),c=new Map(a.flatMap(f=>e.all(`SELECT id, relative_path FROM documents
|
|
454
|
+
WHERE id IN (${f.map(()=>"?").join(",")})`,...f).map(p=>[p.id,p.relative_path]))),l=new Map;for(let f of s)l.has(f.symbol_id)||l.set(f.symbol_id,{symbol:f.symbol,file:f.document_id!==null?c.get(f.document_id)??"":""});let u=new Map,d=c,m=Iq(t);for(let[f,p]of m){let y=[...i.get(f)??[]].sort((R,x)=>R.start_line-x.start_line||R.end_line-x.end_line),h=[...p].sort((R,x)=>R.startLine-x.startLine||R.endLine-x.endLine),S=new Set,b=0;for(let R of h){for(;b<y.length&&y[b].start_line<=R.endLine;)S.add(y[b]),b+=1;for(let I of S)I.end_line<R.startLine&&S.delete(I);let x=new Set,v=[],C=null,w=()=>{if(C)return C;let I=d.get(R.documentId)??"",P=new Set;if(I){let _=Rb(e,I),se=Math.max(0,R.startLine),ee=Math.min(_.length-1,R.endLine);for(let A=se;A<=ee;A+=1)for(let ge of _[A])P.add(ge)}return C=P,P};for(let I of S){if(I.symbol_id===R.symbolId)continue;let P=l.get(I.symbol_id);if(!P)continue;if(!(I.start_line>=R.startLine&&I.end_line<=R.endLine)){if(!(I.start_line<=R.endLine&&I.end_line>=R.startLine))continue;let A=T(P.symbol);if(!A||!w().has(A))continue}let se=`${P.symbol}|${I.chunk_id}`;x.has(se)||(x.add(se),v.push({...P,chunkId:I.chunk_id,source:"scip-chunk"}))}u.set(R.symbolId,v)}}return u}var Gv=500;function Vf(e){let t=[...new Set(e)],n=[];for(let r=0;r<t.length;r+=Gv)n.push(t.slice(r,r+Gv));return n}function Iq(e){let t=new Map;for(let n of e){let r=t.get(n.documentId);r?r.push(n):t.set(n.documentId,[n])}return t}function wq(e){let t=new Map;for(let[n,r]of e){let i=[];for(let o of r)i.push({symbol:o.symbol,file:o.file,chunkId:-1,source:"semantic-callee"});t.set(n,i)}return t}function qv(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=L(e,{includeIgnored:!1}),o=kn(e),s=t??Oe(e),a=new Set(s.map(l=>l.symbolId)),c=_q(s);return Eq(e,r,i,o,a,c),Dq(e,r,s,a),Fq(e,r,i,o,a,c),n.semantic!==!1&&n.semanticEvidence&&Lq(r,n.semanticEvidence.callerMap(e,Aq(s))),r}function Eq(e,t,n,r,i,o){for(let s of n){if(!N(s))continue;let a=Kn(e,s);if(a)for(let c of a){if(o&&!o.has(c.calleeLeaf))continue;let l=rc(s,r.get(c.calleeLeaf)??[]);if(!l||l.length===0)continue;let u=ic(e,s,l,c.memberAccess);u&&i.has(u.symbolId)&&u.file!==s&&zf(t,u.symbolId,s)}}}function Dq(e,t,n,r){let i=kq(n);for(let o of Pq(e,r))e.isIgnored(o.relative_path)||Tq(o,i.get(o.symbol_id))||zf(t,o.symbol_id,o.relative_path)}function Pq(e,t){return Pi(e,t?[...t]:void 0)}function kq(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 Tq(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function Fq(e,t,n,r,i,o){for(let s of n){if(N(s)!=="rust")continue;let a=Ar(e,s,{includeRustAttributeNames:!0});if(a.length!==0)for(let{name:c}of a){if(o&&!o.has(c))continue;let l=r.get(c);if(l)for(let u of l)i.has(u.symbolId)&&u.file!==s&&zf(t,u.symbolId,s)}}}function zf(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function _q(e){let t=new Set;for(let n of e){let r="leaf"in n&&typeof n.leaf=="string"?n.leaf:"symbol"in n&&typeof n.symbol=="string"?T(n.symbol):"";r&&t.add(r)}return t.size>0?t:null}function Aq(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function Lq(e,t){for(let[n,r]of t){let i=e.get(n);i||(i=new Set,e.set(n,i));for(let o of r)i.add(o)}}function Wf(e,t,n={}){return qv(e,t,n)}function As(e,t,n={}){return Fb(e,t,n)}function Uv(e,t,n={}){let r=Wf(e,t,{semantic:n.semantic,semanticEvidence:n.semanticEvidence});return n.sourceFallback===!1?r:On(r,As(e,t))}function On(e,t){let n=new Map;for(let[r,i]of e)n.set(r,new Set(i));for(let[r,i]of t){let o=n.get(r)??new Set;for(let s of i)o.add(s);n.set(r,o)}return n}function Vv(e,t,n){let r=t.identifierResolution==="strict"?ki:kb,i=t.candidateNames?Bo(t.candidateNames):null,o=0,s=0,a=0,c=0,l="";for(let u of t.paths)if(o+=1,l=u,!(!N(u)&&!(t.includeVueSfc&&hn(u)))&&!e.isIgnored(u)&&!t.skipPath?.(u))try{if(i&&!oc(k(e,u),i))continue;s+=1;let m=(p,g,y,h)=>{if(t.candidateNames&&!t.candidateNames.has(p))return;a+=1;let S=t.resolveTargets?t.resolveTargets({sourceFile:u,name:p,kind:g,defaultTargets:h}):h();for(let b of S)c+=1,n({sourceFile:u,name:p,target:b,occurrences:y,kind:g})},f=Pn(e,u);for(let[p,g]of f)m(p,"identifier",g.length,()=>r(e,u,p));for(let p of Ar(e,u,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let g=p.kind==="cross-language-dispatch"?()=>ki(e,u,p.name):()=>r(e,u,p.name);m(p.name,p.kind,p.occurrences,g)}}finally{t.afterPath?.(u),o%10===0&&D("source-reference-scan.progress",()=>{},()=>({scannedPaths:o,currentPath:l,candidateMatchedPaths:s,visitedNames:a,visitedHits:c}))}}function j(e){return e.endLine-e.startLine+1}function zv(e,t={}){let{scope:n,files:r,minLoc:i=1,maxLoc:o=Number.POSITIVE_INFINITY,excludeSymbol:s,excludeEntrySurfaces:a=!1,excludeTypesFiles:c=!1,excludeRootedSymbols:l=!1,requireFunctionLikeSymbol:u=!1,requireCallableSymbol:d=!1,excludeRustTraitImplMembers:m=!1,includeSuppressed:f=!1,sortByLocDesc:p=!1}=t,g=[],y=Mq(e,{scope:n,files:r,requireFunctionLikeSymbol:u,requireCallableSymbol:d}),h=new Map,S=new Map,b=x=>{let v=h.get(x);if(v!==void 0)return v;let C=Ue(e,x);return h.set(x,C),C},R=x=>{let v=S.get(x);if(v!==void 0)return v;let C=U(x);return S.set(x,C),C};for(let x of y){let v=x.relativePath;if(e.isIgnored(v)||a&&b(v)||!Nq(x,{requireFunctionLikeSymbol:u,requireCallableSymbol:d})||s!==void 0&&x.symbol===s)continue;let C=j(x);C<i||C>o||c&&Oq(v)||l&&Re(e,x.symbol,v)||m&&$e(x.symbol)||R(v)!=="test"&&(di(x.symbol)||!f&&Sa(e,v,x.startLine)||g.push(x))}return p?g.sort((x,v)=>j(v)-j(x)):g}function Mq(e,t){return t.files!==void 0?[...new Set(t.files.map(r=>r.replace(/\\/g,"/")))].sort().filter(r=>!t.scope||r.includes(t.scope)).flatMap(r=>ie(e,r)):t.requireCallableSymbol?Lo(e,{scope:t.scope,symbolMatches:ye,sqlPrefilter:"callable"}):t.requireFunctionLikeSymbol?Lo(e,{scope:t.scope,symbolMatches:ae,sqlPrefilter:"function-like"}):pb(e,t.scope)}function Nq(e,t){return t.requireCallableSymbol?ye(e.symbol):t.requireFunctionLikeSymbol?ae(e.symbol):e.isFunctionLike}function Oq(e){return(e.split("/").pop()??"").includes("types")}var F=class{constructor(t){this.db=t}db;scopedDefinitions(t){return Dd(this.db,t)}definitionsForFile(t){return ie(this.db,t)}productionCallableDefinitions(t={}){return zv(this.db,t)}calleeMap(t,n={}){return yl(this.db,t,{...n,semanticEvidence:q})}crossFileCallerMap(t,n={}){return Wf(this.db,t,{...n,semanticEvidence:q})}sourceFallbackCallerFiles(t,n={}){return As(this.db,t,n)}callerFileMap(t,n={}){return Uv(this.db,t,{...n,semanticEvidence:q})}frameworkReferencedSymbolIds(t){let n=new Map;for(let i of t){if(!i.leaf)continue;let o=n.get(i.leaf)??[];o.push(i.symbolId),n.set(i.leaf,o)}let r=new Set;for(let i of L(this.db,{includeIgnored:!1}))if(N(i)==="rust")for(let{name:o}of Ar(this.db,i,{includeRustAttributeNames:!0}))for(let s of n.get(o)??[])r.add(s);return r}symbolsWithNonSelfCallees(t,n={}){if(t.length===0)return new Set;let r=new Map(t.map(o=>[o.symbolId,o.symbol])),i=this.calleeMap(t,n);return new Set([...i.entries()].filter(([o,s])=>{let a=r.get(o);return s.some(c=>c.symbol!==a)}).map(([o])=>o))}fileDependencyGraph(t){return le(this.db,t)}fileKind(t){return U(t)}hasSuppressionComment(t){return Sa(this.db,t.relativePath,t.startLine)}sourceFiles(){return ct(this.db)}scanSourceReferences(t,n){Vv(this.db,t,n)}callableSignature(t){let n=Lt(this.db).forFile(t.relativePath,{facts:!0}).facts?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};import{statSync as Bq}from"fs";function Zr(e){let t=e.get("SELECT COUNT(*) as c FROM documents").c,n=e.get("SELECT COUNT(*) as c FROM global_symbols").c,r=e.get("SELECT COUNT(*) as c FROM mentions WHERE role = 1").c,i=e.get("SELECT COUNT(*) as c FROM mentions WHERE role != 1").c;return{documents:t,symbols:n,definitions:r,references:i,...jq(e.generation.databasePath)}}function jq(e){try{let t=Bq(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function $q(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function Hq(e,t){let n=$q(t);return L(e,{like:n,includeIgnored:!1}).filter(r=>Gq({pattern:t,relativePath:r})).map(r=>({relativePath:r}))}function Gq(e,t){let n=typeof e=="string"?{pattern:e,relativePath:t}:e;if(typeof n.pattern!="string"||typeof n.relativePath!="string")throw new TypeError("pathMatchesGlob requires pattern and relativePath.");let r=ht(n.pattern),i=ht(n.relativePath);if(!/[*?]/.test(r))return i.includes(r);let o=r.includes("/")?r:`**/${r}`;return bl(o.split("/"),i.split("/"))}function bl(e,t){if(e.length===0)return t.length===0;let[n,...r]=e;return n==="**"?bl(r,t)||t.length>0&&bl(e,t.slice(1)):t.length===0||!qq(n??"",t[0]??"")?!1:bl(r,t.slice(1))}function qq(e,t){let n="^";for(let r of e)r==="*"?n+="[^/]*":r==="?"?n+="[^/]":n+=Uq(r);return n+="$",new RegExp(n).test(t)}function Uq(e){return/[\\^$.*+?()[\]{}|]/.test(e)?`\\${e}`:e}import{basename as Vq}from"path";function zq(e,t){let n=t.className,r=Or(e,n);return r.match?r.total>1?{kind:"ambiguous",query:n,total:r.total,candidates:[Wv(r.match),...r.candidates]}:{kind:"matched",query:n,owner:Kq(r.match),methods:Wq(e,r.match)}:{kind:"missing",query:n,suggestions:Sb(e,n,5)}}function Wq(e,t){let n=T(t.symbol),i=new F(e).definitionsForFile(t.relativePath).filter(c=>ye(c.symbol)),o=i.filter(c=>c.parentTypeName===n||c.symbol.includes(n)),a=(o.length>0?o:Jq(Vq(t.relativePath))===n?i.filter(c=>c.symbol.includes("<invalid-global-code>")):[]).map(c=>({startLine:c.startLine,endLine:c.endLine,name:T(c.symbol)}));return N(t.relativePath)!=="clojure"?a:Xq(a,Yq(e,t))}function Wv(e){return{symbol:e.symbol,shortName:E(e.symbol),relativePath:e.relativePath,startLine:e.startLine}}function Kq(e){return{...Wv(e),endLine:e.endLine}}function Jq(e){return e.replace(/\.[^.]+$/,"")}function Yq(e,t){let n=T(t.symbol);return n?(Y(e,t.relativePath)?.clojureMembers??[]).filter(r=>r.ownerName===n).map(r=>({startLine:r.startLine,endLine:r.endLine,name:r.memberName})):[]}function Xq(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.name}:${r.startLine}:${r.endLine}`,r);return[...n.values()].sort((r,i)=>r.startLine-i.startLine||r.endLine-i.endLine)}function Kf(e,t,n={}){let r=G(e,t);if(!r)return{definitions:[],referencedBy:[]};let i=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",r.symbolId),o=Dn(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:Zq(o,i?.display_name??null,r.symbol),source:Qq(e,r.relativePath,r.startLine,r.endLine)}],a=nn(e,r,{semantic:n.semantic,semanticEvidence:q}).map(c=>({relativePath:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol,enclosingShort:c.enclosingSymbol?E(c.enclosingSymbol):"(top-level)"}));return{definitions:s,referencedBy:a}}function Qq(e,t,n,r){let i=k(e,t);if(!i)return null;let s=i.split(`
|
|
455
|
+
`).slice(n,r+1).join(`
|
|
456
|
+
`).trimEnd();return s.length>0?s:null}function Zq(e,t,n){let r=En(e);if(r&&!eU(r))return r;let i=(t??"").trim();return i?ae(n)&&!i.endsWith("()")?`${i}()`:i:E(n)}function eU(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function Zi(e,t,n){return n.length===0?[]:e.all(tU(e,t,n.length),...n).map(r=>r.relative_path)}function tU(e,t,n){if(!Number.isSafeInteger(n)||n<=0)throw new Error("file dependency SQL requires at least one selected path");let r=Array.from({length:n},()=>"(?)").join(", ");return t==="forward"?nU(e,r):rU(e,r)}function nU(e,t){return`WITH selected(relative_path) AS (VALUES ${t}),
|
|
457
|
+
source_symbols(symbol_id) AS MATERIALIZED (
|
|
458
|
+
SELECT DISTINCT source_m.symbol_id
|
|
459
|
+
FROM selected
|
|
460
|
+
JOIN documents source_d ON source_d.relative_path = selected.relative_path
|
|
461
|
+
JOIN chunks source_c ON source_c.document_id = source_d.id
|
|
462
|
+
JOIN mentions source_m ON source_m.chunk_id = source_c.id
|
|
463
|
+
JOIN global_symbols gs ON gs.id = source_m.symbol_id
|
|
464
|
+
WHERE ${e.localSymbolPredicate}
|
|
465
|
+
)
|
|
466
|
+
SELECT DISTINCT target_d.relative_path
|
|
467
|
+
FROM source_symbols
|
|
468
|
+
JOIN mentions definition_m ON definition_m.symbol_id = source_symbols.symbol_id
|
|
469
|
+
AND definition_m.role = 1
|
|
470
|
+
JOIN chunks definition_c ON definition_c.id = definition_m.chunk_id
|
|
471
|
+
JOIN documents target_d ON target_d.id = definition_c.document_id
|
|
472
|
+
WHERE NOT EXISTS (
|
|
473
|
+
SELECT 1
|
|
474
|
+
FROM selected target_selected
|
|
475
|
+
WHERE target_selected.relative_path = target_d.relative_path
|
|
476
|
+
)
|
|
477
|
+
ORDER BY target_d.relative_path`}function rU(e,t){return`WITH selected(relative_path) AS (VALUES ${t}),
|
|
478
|
+
target_symbols(symbol_id) AS MATERIALIZED (
|
|
479
|
+
SELECT DISTINCT definition_m.symbol_id
|
|
480
|
+
FROM selected
|
|
481
|
+
JOIN documents target_d ON target_d.relative_path = selected.relative_path
|
|
482
|
+
JOIN chunks definition_c ON definition_c.document_id = target_d.id
|
|
483
|
+
JOIN mentions definition_m ON definition_m.chunk_id = definition_c.id
|
|
484
|
+
AND definition_m.role = 1
|
|
485
|
+
)
|
|
486
|
+
SELECT DISTINCT source_d.relative_path
|
|
487
|
+
FROM target_symbols
|
|
488
|
+
JOIN mentions source_m ON source_m.symbol_id = target_symbols.symbol_id
|
|
489
|
+
JOIN chunks source_c ON source_c.id = source_m.chunk_id
|
|
490
|
+
JOIN documents source_d ON source_d.id = source_c.document_id
|
|
491
|
+
WHERE NOT EXISTS (
|
|
492
|
+
SELECT 1
|
|
493
|
+
FROM selected source_selected
|
|
494
|
+
WHERE source_selected.relative_path = source_d.relative_path
|
|
495
|
+
)
|
|
496
|
+
ORDER BY source_d.relative_path`}function Jf(e,t){let n=it(e,t);return n?Zi(e,"forward",[n]).filter(i=>!e.isIgnored(i)).map(i=>({relativePath:i})):[]}function Yf(e,t){let n=it(e,t);return n?Zi(e,"reverse",[n]).filter(i=>!e.isIgnored(i)).map(i=>({relativePath:i})):[]}function Xf(e,t){let n=Vi(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let r=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
|
|
497
|
+
WHERE relative_path IN (${r})
|
|
498
|
+
ORDER BY relative_path`,...n).map(l=>l.relative_path).filter(l=>!e.isIgnored(l)),s=Ya(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:l,...u})=>u),a=Zi(e,"forward",n).filter(l=>!e.isIgnored(l)),c=Zi(e,"reverse",n).filter(l=>!e.isIgnored(l));return{files:o,symbols:s,dependsOn:a,dependedOnBy:c}}function Qf(e,t){let n=Vi(e,t);return n.length===0?[]:sU([...iU(e,n),...oU(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(aU)}function iU(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
|
|
499
|
+
FROM mentions m
|
|
500
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
501
|
+
JOIN documents d1 ON c.document_id = d1.id
|
|
502
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
503
|
+
WHERE d1.relative_path NOT IN (${n})
|
|
504
|
+
AND (
|
|
505
|
+
EXISTS (
|
|
506
|
+
SELECT 1
|
|
507
|
+
FROM defn_enclosing_ranges der
|
|
508
|
+
JOIN documents d2 ON der.document_id = d2.id
|
|
509
|
+
WHERE der.symbol_id = gs.id
|
|
510
|
+
AND d2.relative_path IN (${n})
|
|
511
|
+
)
|
|
512
|
+
OR EXISTS (
|
|
513
|
+
SELECT 1
|
|
514
|
+
FROM mentions def_m
|
|
515
|
+
JOIN chunks def_c ON def_m.chunk_id = def_c.id
|
|
516
|
+
JOIN documents d2 ON def_c.document_id = d2.id
|
|
517
|
+
WHERE def_m.symbol_id = gs.id
|
|
518
|
+
AND def_m.role = 1
|
|
519
|
+
AND d2.relative_path IN (${n})
|
|
520
|
+
)
|
|
521
|
+
)
|
|
522
|
+
AND m.role != 1
|
|
523
|
+
AND ${e.localSymbolPredicate}
|
|
524
|
+
${e.pathExclusionsFor("d1")}
|
|
525
|
+
ORDER BY d1.relative_path`,...t,...t,...t)}function oU(e,t){let n=new F(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>ye(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function sU(e){let t=new Set;return e.filter(n=>{let r=`${n.relative_path}|${n.symbol}`;return t.has(r)?!1:(t.add(r),!0)})}function aU(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:E(e.symbol)}}var Ls=new WeakMap,Kv=me({kind:"definition-exclusions",invalidation:re("definition-exclusions"),serialize:e=>JSON.stringify(e),deserialize:cU});function Yv(e,t){let n=N(t);if(!(n==="rust"||n==="typescript"||n==="tsx"||n==="javascript"))return[];let i=k(e,t);if(!i)return[];let o=he(e,t,i),s=Kv.read(e,t,o);if(s)return s;let a=n==="rust"?hU(e,t):mU(e,t);return Kv.write(e,t,o,a),a}function cU(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=t.map(lU);return n.some(r=>r===null)?null:n}catch{return null}}function lU(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?PU(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 Xv=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),uU=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,dU=/\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 mU(e,t){let n=k(e,t);if(!n||!fU(n))return[];let r=ne(e,t);if(!r)return[];let i=Ls.get(r);if(i)return i;let o=!1,s=r.rootNode;for(let c of s.namedChildren){if(c.type!=="expression_statement")continue;let l=c.namedChild(0);if(!l||l.type!=="call_expression")continue;let u=l.namedChild(0);if(!u)continue;let d=u.type==="member_expression"?u.namedChild(u.namedChildCount-1)?.text:u.text;if(d&&Xv.has(d)){o=!0;break}}let a=[];o&&a.push({startLine:0,endLine:s.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)",disposition:"exclude"});for(let c of s.namedChildren){let l=null,u=null;if(c.type==="function_declaration")l=c.namedChild(0)?.text??null,u=c;else if(c.type==="export_statement"){let d=c.namedChild(0);d?.type==="function_declaration"&&(l=d.namedChild(0)?.text??null,u=d)}else if(c.type==="lexical_declaration"){let d=c.namedChild(0);if(d?.type==="variable_declarator"){let m=d.namedChild(0)?.text,f=d.namedChild(1);m&&(f?.type==="arrow_function"||f?.type==="function_expression")&&(l=m,u=d)}}l&&/^use[A-Z]/.test(l)&&u&&a.push({startLine:u.startPosition.row,endLine:u.endPosition.row,reason:"React custom hook (use*)",disposition:"exclude"})}return a.push(...Qv(r,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),Ls.set(r,a),a}function fU(e){if(e.includes("scip-query"))return!0;let t=!1;for(let n of Xv)if(e.includes(n)){t=!0;break}return t&&uU.test(e)?!0:e.includes("use")&&dU.test(e)}var pU=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function gU(e){return pU.test(e)}function Qv(e,t,n){let r=[],i=o=>{if(t.has(o.type)&&o.parent){let a=o.parent.children,c=-1;for(let l=0;l<a.length;l+=1)if(a[l].startIndex===o.startIndex&&a[l].type===o.type){c=l;break}if(c>0)for(let l=c-1;l>=0;l-=1){let u=a[l];if(n.has(u.type)){if(gU(u.text)){r.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"scip-query suppression comment",disposition:"exclude"});break}continue}if(!(u.type==="attribute_item"||u.type==="inner_attribute_item"))break}}for(let s of o.namedChildren)i(s)};return i(e.rootNode),r}function hU(e,t){let n=ne(e,t);if(!n)return[];let r=Ls.get(n);if(r)return r;let i=[],o=yU(n);return o?(Ls.set(n,o),o):(Zv(n.rootNode,i,!1,!1),i.push(...Qv(n,new Set(["function_item","function_signature_item","struct_item","enum_item","union_item","impl_item","mod_item","static_item","const_item"]),new Set(["line_comment","block_comment"]))),i.push(...EU(n.rootNode)),Ls.set(n,i),i)}function yU(e){return kU(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)",disposition:"exclude"}]:null}function Zv(e,t,n,r){let i=n,o=r;e.type==="trait_item"&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait declaration body (dynamic dispatch)",disposition:"implicit-usage"}),e.type==="impl_item"&&e.childForFieldName("trait")&&(o=!0,t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl block (dynamic dispatch)",disposition:"implicit-usage"})),e.type==="function_item"||e.type==="function_signature_item"?bU(e,t,n,r):r&&wU(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"?SU(e,t,n):e.type==="mod_item"&&Zf(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)Zv(s,t,i,o)}function bU(e,t,n,r){let i=Zf(e),o=null;r?o={reason:"trait impl method (dynamic dispatch)",disposition:"implicit-usage"}:n&&(o={reason:"inside #[cfg(test)] mod",disposition:"exclude"});for(let s of i){if(eI(s)){o={reason:"#[allow(dead_code)]",disposition:"exclude"};break}let a=vU(s);if(a){o=a;break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o.reason,disposition:o.disposition})}function SU(e,t,n){let r=Zf(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(IU)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(...)] - generated impl may access fields",disposition:"implicit-usage",containerName:i}),r.some(eI)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[allow(dead_code)]",disposition:"exclude",containerName:i}),n&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"inside #[cfg(test)] mod",disposition:"exclude",containerName:i})}function Zf(e){let t=e.parent;if(!t)return[];let n=t.children,r=-1;for(let o=0;o<n.length;o+=1)if(n[o].startIndex===e.startIndex&&n[o].type===e.type){r=o;break}if(r<=0)return[];let i=[];for(let o=r-1;o>=0;o-=1){let s=n[o];if(s.type==="attribute_item"||s.type==="inner_attribute_item")i.push(s.text);else{if(s.type==="line_comment"||s.type==="block_comment")continue;break}}return i}var xU=new Set(["test","bench","tokio::test","async_std::test"]),RU=new Set(["no_mangle","export_name","link_name","used","macro_export","proc_macro","proc_macro_derive","proc_macro_attribute"]),CU=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 vU(e){if(/#\[\s*cfg\s*\(\s*test\s*\)/.test(e))return{reason:"#[cfg(test)]",disposition:"exclude"};let t=DU(e);return t?xU.has(t)?{reason:`#[${t}]`,disposition:"exclude"}:RU.has(t)?{reason:`Rust ABI/export attribute #[${t}]`,disposition:"implicit-usage"}:CU.has(t)?null:{reason:`Rust attribute macro #[${t}]`,disposition:"implicit-usage"}:null}function IU(e){return/#\[\s*derive\s*\(/.test(e)}function eI(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function wU(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function EU(e){let t=TU(e);if(t.size===0)return[];let n=[];for(let r of e.descendantsOfType("mod_item")){let i=r.childForFieldName("name")?.text;i&&t.has(i)&&n.push({startLine:r.startPosition.row,endLine:r.endPosition.row,reason:'attribute `with = "..."` module - body may be invoked via reflection',disposition:"implicit-usage",containerName:i})}return n}function DU(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 PU(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 kU(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 Jv=/\bwith\s*=\s*"([^"]+)"/g;function TU(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){Jv.lastIndex=0;let r;for(;(r=Jv.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function tI(e){let t=ep(e);return(n,r,i,o)=>t(n,r,i,o)?.disposition==="exclude"}function ep(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=Yv(e,r),s=new Map;for(let a of o){if(!a.containerName)continue;let c=s.get(a.containerName)??[];c.push(a),s.set(a.containerName,c)}return i={ranges:o,containers:s},t.set(r,i),i};return(r,i,o,s)=>{let a=n(r),c=[];for(let u of a.ranges)i>=u.startLine&&i<=u.endLine&&c.push(u);let l=new Set;s&&l.add(s);for(let u of Za(o))l.add(u);for(let u of l){let d=a.containers.get(u);d&&c.push(...d)}return FU(c)}}function FU(e){if(e.length===0)return null;let n=e.find(r=>r.disposition==="exclude")??e[0];return{disposition:n.disposition,reason:n.reason}}function tp(e,t={}){bu(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function nI(e,t,n={}){bu(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function rI(e,t){if(t.isIgnoredPath(e.relativePath))return ot("ignored-file");if(Wn(e.symbol))return ot("module-like-symbol");if(!Sl(e.symbol))return ot("non-value-symbol");if(!e.isFunctionLike&&e.enclosingSymbol&&Sl(e.enclosingSymbol))return ot("nested-non-callable-value");if(!t.includeTests&&!_U(e.relativePath))return ot("test-file");if(!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName))return ot("excluded-file-region");let n=T(e.symbol);if(n==="<constructor>")return ot("implicit-constructor");if(e.symbol.startsWith("scip-python ")){if(n==="__all__")return ot("python-runtime-metadata");if(/^__[^_].*__$/.test(n))return ot("python-protocol-member")}return t.isDeclarationOnlyCallable()?ot("declaration-only-callable"):t.isFrameworkContractCallable()?ot("framework-contract-member"):$e(e.symbol)?ot("rust-trait-impl-member"):di(e.symbol)?ot("rust-test-module"):!t.includeMembers&&!AU(e)?ot("member"):e.endLine-e.startLine+1<t.minLoc?ot("below-min-loc"):{accepted:!0}}function _U(e){return U(e)!=="test"}function ot(e){return{accepted:!1,rejectionReason:e}}function Sl(e){return ae(e)||e.endsWith("().")||e.endsWith(".")}function AU(e){return ye(e.symbol)||Za(e.symbol).length===0}function xl(e,t){return j(e)-j(t)||e.relativePath.localeCompare(t.relativePath)}function fe(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function eo(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}`;t.has(i)||(t.add(i),n.push(r))}return n}function iI(){return new Map}function oI(e,t,n){let r=new Map;for(let i of Cb(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||Cl(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function sI(e,t,n,r={}){let i=new Set;if(r.conservative||n.size===0){for(let o of Ib(e,t))i.add(o.symbol_id);return i}for(let o of vb(e,t))e.isIgnored(o.relative_path)||n.has(o.relative_path)||i.add(o.symbol_id);return i}function np(e,t){let n=e.get(t);if(!n)return!1;for(let r of n.values())if(r.occurrences>0)return!0;return!1}function Rl(e,t,n){let r=e.get(t);if(!r)return!1;for(let[i,o]of r)if(i!==n&&o.occurrences>0)return!0;return!1}function aI(e){return e?.occurrences??0}function Cl(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=lI(e,t,n);o.occurrences+=r,o.sources.add(i)}function cI(e,t,n,r,i){if(r<=0)return;let o=lI(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function lI(e,t,n){let r=e.get(t);r||(r=new Map,e.set(t,r));let i=r.get(n);return i||(i={occurrences:0,sources:new Set},r.set(n,i)),i}var LU=new Set(["componentDidCatch","componentDidMount","componentDidUpdate","componentWillUnmount","getDerivedStateFromError","getDerivedStateFromProps","getSnapshotBeforeUpdate","render","shouldComponentUpdate","UNSAFE_componentWillMount","UNSAFE_componentWillReceiveProps","UNSAFE_componentWillUpdate"]);function to(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=ne(e,t.relativePath);if(!n)return!1;let r=n.rootNode.descendantsOfType("method_definition").find(s=>s.startPosition.row<=t.startLine&&s.endPosition.row>=t.endLine);if(!r)return!1;if(/\boverride\b/.test(r.text.slice(0,Math.max(0,r.text.indexOf("{")))))return!0;let i=r.parent;for(;i&&i.type!=="class_declaration"&&i.type!=="class";)i=i.parent;if(!i)return!1;let o=i.text.slice(0,Math.max(0,i.text.indexOf("{")));return/\bimplements\b/.test(o)||/\bextends\b/.test(o)?!0:LU.has(t.leaf)&&/\bextends\s+(?:React\.)?(?:Component|PureComponent)\b/.test(o)}var MU=1e3,NU=300;function ei(e,t={}){let{scope:n,minLoc:r=1,includeTests:i=!1,skipBarrels:o=!1,includeMembers:s=!1,deadCodeOnly:a=!1,scanLimit:c,semantic:l=!0}=t,u=0,d=D("dead.candidates",()=>{let x=fe(OU(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c);return u=x.length,x},()=>({definitions:u})),m=0,f=o?D("dead.inactive-barrels",()=>{let x=new Set(Av(e));return m=x.size,x},()=>({paths:m})):new Set,p=0,g=a?iI():D("dead.mention-reference-counts",()=>{let x=oI(e,f,d.map(v=>v.symbolId));return p=x.size,x},()=>({definitions:d.length,symbolsWithReferences:p})),y=0,h=a?D("dead.mentioned-symbol-ids",()=>{let x=sI(e,d.map(v=>v.symbolId),f,{conservative:f.size===0});return y=x.size,x},()=>({definitions:d.length,referencedSymbols:y})):new Set,S=a?d.filter(x=>!h.has(x.symbolId)):d.filter(x=>!Rl(g,x.symbolId,x.relativePath));a?D("dead.source-fallback.dead-code-only",()=>UU(e,S,g,{inactiveBarrelPaths:f}),()=>({definitions:S.length,testReferencesIncluded:!0})):D("dead.source-fallback.ast",()=>qU(e,S,g,{inactiveBarrelPaths:f}),()=>({definitions:S.length,testReferencesIncluded:!0}));let b=a?S.filter(x=>!np(g,x.symbolId)):S.filter(x=>!Rl(g,x.symbolId,x.relativePath));D("dead.caller-map-supplement",()=>JU(e,b,g,{inactiveBarrelPaths:f,includeSemantic:!a&&l}),()=>({definitions:b.length,semantic:!a&&l}));let R=a?S.filter(x=>!np(g,x.symbolId)):d;return GU(e,$U(R,g))}function OU(e,t){let n=tI(e),r=[];for(let i of Lo(e,{scope:t.scope,symbolMatches:Sl,sqlPrefilter:"function-like"}))rI(i,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n,isDeclarationOnlyCallable:()=>jU(e,i),isFrameworkContractCallable:()=>to(e,i)}).accepted&&r.push(i);return r}var BU=["method_signature","abstract_method_signature","call_signature","construct_signature"];function jU(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=ne(e,t.relativePath);if(n)return n.rootNode.descendantsOfType([...BU]).some(i=>i.startPosition.row<=t.startLine&&i.endPosition.row>=t.endLine);let r=Ne(e,t.relativePath).slice(t.startLine,t.endLine+1).join(`
|
|
526
|
+
`).trim();return r.endsWith(";")&&!r.includes("=>")&&!r.includes("{")}function $U(e,t){return e.map(n=>HU(n,t)).filter(n=>n.cross_file_refs===0).sort((n,r)=>r.loc-n.loc||n.relative_path.localeCompare(r.relative_path)||n.start_line-r.start_line)}function HU(e,t){let n=t.get(e.symbolId)??new Map,r=aI(n.get(e.relativePath)),i=0;for(let[o,s]of n)o!==e.relativePath&&(i+=s.occurrences);return{relative_path:e.relativePath,start_line:e.startLine,end_line:e.endLine,loc:e.endLine-e.startLine+1,symbol:e.symbol,parent_type_name:e.parentTypeName,same_file_refs:r,cross_file_refs:i}}function GU(e,t){let n=ep(e),r=[],i=0,o=0,s=0,a=0,c=0,l=0;for(let u of t){if(e.isIgnored(u.relative_path))continue;if(Ue(e,u.relative_path)){a++;continue}if(Re(e,u.symbol,u.relative_path)){c++;continue}let d=n(u.relative_path,u.start_line,u.symbol,u.parent_type_name),m=d?.disposition==="implicit-usage"?d.reason:void 0,f=m?"implicit-usage":u.same_file_refs===0?"dead-code":"file-internal";f==="dead-code"?i++:f==="file-internal"?o++:s++,l+=u.loc,r.push({relativePath:u.relative_path,startLine:u.start_line,endLine:u.end_line,loc:u.loc,symbol:u.symbol,shortName:E(u.symbol),sameFileRefs:u.same_file_refs,kind:f,...m?{implicitUsageReason:m}:{}})}return{symbols:r,counts:{total:r.length,deadCode:i,fileInternal:o,implicitUsage:s,loc:l},applicability:{entrySurfaceExcluded:a,externalRootExcluded:c,implicitUsageSignals:s},totalCount:r.length,deadCodeCount:i,fileInternalCount:o,implicitUsageCount:s,totalLoc:l}}function qU(e,t,n,r){if(t.length===0)return;let i=new F(e),o=new Set(t.map(c=>c.symbolId)),s=new Set(t.map(c=>c.leaf).filter(Boolean)),a=new Set(i.sourceFiles());for(let c of L(e))a.add(c);i.scanSourceReferences({paths:a,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:s,skipPath:c=>r.inactiveBarrelPaths.has(c)},c=>{o.has(c.target.symbolId)&&(WU(e,c)||Cl(n,c.target.symbolId,c.sourceFile,KU(c),"source-fallback"))})}function UU(e,t,n,r){if(t.length===0)return;let i=new F(e),o=VU(t),s=new Set(i.sourceFiles());for(let u of L(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=sc(e,u),c.set(u,d)),d};i.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>r.inactiveBarrelPaths.has(u),resolveTargets:({sourceFile:u,name:d,kind:m})=>{let f=o.get(d);return f?zU(u,d,f,()=>l(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),nI(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&uI(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||Cl(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function VU(e){let t=new Map;for(let n of e){if(!n.leaf)continue;let r=t.get(n.leaf)??[];r.push(n),t.set(n.leaf,r)}return t}function zU(e,t,n,r,i){let o=n.filter(l=>l.relativePath===e);if(o.length>0)return o;if(!i.permissive&&n.length===1)return[...n];let s=r(),a=s.get(t);if(a)for(let l of a){let u=n.filter(d=>gt(l,d.relativePath));if(u.length>0)return u}let c=new Set;for(let l of s.values())for(let u of l)c.add(u);for(let l of c){let u=n.filter(d=>gt(l,d.relativePath));if(u.length>0&&u.length===n.length)return u}return i.permissive?[...n]:[]}function WU(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&uI(e,t)}function KU(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function uI(e,t){return t.occurrences>1?!1:oe(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function JU(e,t,n,r){let i=r.includeSemantic!==!1,o=i&&t.length>=MU&&L(e).length>=NU,s=(u,d)=>{d===u.relativePath||e.isIgnored(d)||r.inactiveBarrelPaths.has(d)||cI(n,u.symbolId,d,1,"caller-map")};if(o?D("dead.caller-map.per-symbol-non-semantic",()=>{for(let u of t){let d=Nn(e,u,{semantic:!1,semanticEvidence:q});for(let m of d)s(u,m.file)}},()=>({definitions:t.length,semantic:!1})):D("dead.caller-map.per-symbol",()=>{for(let u of t){let d=Nn(e,u,{semantic:i,semanticEvidence:q});if(d.length!==0)for(let m of d)s(u,m.file)}},()=>({definitions:t.length,semantic:i})),!o)return;let a=0,c=D("dead.caller-map.semantic-candidates",()=>{let u=t.filter(d=>!Rl(n,d.symbolId,d.relativePath));return a=u.length,u},()=>({definitions:t.length,semanticCandidates:a}));if(c.length===0)return;let l=fR(e,c);for(let u of c){let d=l.get(u.symbolId);if(d)for(let m of d)s(u,m)}}function YU(e,t={}){let{limit:n=30,scope:r}=t,i=r?"AND def_d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[],a=e.all(`SELECT
|
|
527
|
+
gs.symbol,
|
|
528
|
+
COUNT(*) AS ref_count,
|
|
529
|
+
COUNT(DISTINCT ref_d.id) AS file_count,
|
|
530
|
+
def_d.relative_path AS defined_in
|
|
531
|
+
FROM mentions m
|
|
532
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
533
|
+
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
534
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
535
|
+
JOIN (
|
|
536
|
+
SELECT m2.symbol_id, c2.document_id
|
|
537
|
+
FROM mentions m2
|
|
538
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
539
|
+
WHERE m2.role = 1
|
|
540
|
+
GROUP BY m2.symbol_id
|
|
541
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
542
|
+
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
543
|
+
WHERE m.role != 1
|
|
544
|
+
AND def_d.id != ref_d.id
|
|
545
|
+
${e.pathExclusionsFor("def_d")}
|
|
546
|
+
${e.symbolNoiseFor("gs")}
|
|
547
|
+
${i}
|
|
548
|
+
GROUP BY gs.id
|
|
549
|
+
ORDER BY ref_count DESC
|
|
550
|
+
LIMIT ?`,...o,n).filter(c=>!e.isIgnored(c.defined_in)).map(c=>({symbol:c.symbol,shortName:E(c.symbol),refCount:c.ref_count,fileCount:c.file_count,definedIn:c.defined_in}));return a.length>0?a:XU(e,r,n)}function XU(e,t,n){return Oe(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>QU(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function QU(e,t){let r=Nn(e,t,{limit:500,semanticEvidence:q}).filter(i=>i.file!==t.relativePath);return{symbol:t.symbol,shortName:E(t.symbol),refCount:r.length,fileCount:new Set(r.map(i=>i.file)).size,definedIn:t.relativePath}}function ZU(e,t,n={}){return lV(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function eV(e,t){let n=G(e,t),r=rV(e,t);if(r.length>0&&!oV(n))return r;let i=iV(e,t,n);return rp(t)&&i.length>0?i:sV([...r,...i])}function tV(e,t,n={}){let r=it(e,t);if(!r)return[];let i=mI(e,r),o=n.semantic===!1?null:dI(e,r);return(o?nV(o,i):i).filter(a=>!a.used).map(a=>({symbol:a.symbol,shortName:a.shortName,importedIn:a.importer}))}function nV(e,t){let n=new Map;for(let i of t){let o=n.get(i.shortName);o?o.push(i):n.set(i.shortName,[i])}let r=e.map(i=>{let o=n.get(i.shortName),s=o?.shift();return o?.length===0&&n.delete(i.shortName),s?{...i,used:i.used||s.used}:i});return r.push(...[...n.values()].flat()),r}function rV(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
|
|
551
|
+
FROM mentions m
|
|
552
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
553
|
+
JOIN documents d ON c.document_id = d.id
|
|
554
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
555
|
+
WHERE gs.symbol LIKE ?
|
|
556
|
+
AND m.role = 2
|
|
557
|
+
ORDER BY d.relative_path`,`%${t}%`).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:E(r.symbol),fromFile:r.importer}))}function iV(e,t,n=G(e,t)){let r=n?.relativePath??null,i=n?T(n.symbol):t.replace(/\(\)$/,""),o=n?Wn(n.symbol):!1,s=new Set;for(let c of L(e,{includeIgnored:!1}))for(let l of oe(e,c))aV(l,c,{targetFile:r,targetLeaf:i,targetIsModule:o,targetPattern:t})&&s.add(c);let a=rp(t)?t.trim():null;return[...s].sort().map(c=>({symbol:a??n?.symbol??i,shortName:a??(n?E(n.symbol):i),fromFile:c}))}function oV(e){return!!(e&&(e.symbol.startsWith("scip-clojure ")||N(e.relativePath)==="clojure"))}function sV(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.fromFile}`;t.has(i)||(t.add(i),n.push(r))}return n.sort((r,i)=>r.fromFile.localeCompare(i.fromFile)||r.shortName.localeCompare(i.shortName))}function aV(e,t,n){return!e.sourcePath||n.targetFile&&te(e.sourcePath)!==te(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&fV(t)||e.kind==="namespace"&&cV(e,n.targetPattern)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function cV(e,t){let n=t.trim().replace(/\(\)$/,"");return rp(n)?e.importedName===n||e.localName===n:!1}function rp(e){let t=e.trim().replace(/\(\)$/,"");return t.includes(".")&&!t.includes("/")&&!t.includes(":")}function lV(e,t,n={}){let r=it(e,t);return r?uV(e,r,n)??(n.semantic===!1?null:dI(e,r))??mI(e,r):null}function uV(e,t,n){let i=e.all(`SELECT DISTINCT
|
|
558
|
+
gs.symbol,
|
|
559
|
+
def_d.relative_path AS from_file,
|
|
560
|
+
imp_d.relative_path AS importer,
|
|
561
|
+
EXISTS (
|
|
562
|
+
SELECT 1
|
|
563
|
+
FROM mentions ref_m
|
|
564
|
+
JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
|
|
565
|
+
WHERE ref_m.symbol_id = gs.id
|
|
566
|
+
AND ref_m.role != 1
|
|
567
|
+
AND ref_c.document_id = imp_d.id
|
|
568
|
+
) AS used
|
|
569
|
+
FROM mentions m
|
|
570
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
571
|
+
JOIN documents imp_d ON c.document_id = imp_d.id
|
|
572
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
573
|
+
LEFT JOIN (
|
|
574
|
+
SELECT m2.symbol_id, c2.document_id
|
|
575
|
+
FROM mentions m2
|
|
576
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
577
|
+
WHERE m2.role = 1
|
|
578
|
+
GROUP BY m2.symbol_id
|
|
579
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
580
|
+
LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
581
|
+
WHERE imp_d.relative_path = ?
|
|
582
|
+
AND m.role = 2
|
|
583
|
+
ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(i.length>0){let o=n.semantic===!1?[]:ds(e,t);return i.map(s=>({symbol:s.symbol,shortName:E(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 dI(e,t){let n=ds(e,t);return n.length>0?n.map(r=>{let i=fI(r.importedName,r.localName,r.kind);return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:r.kind==="side-effect"?!0:r.isUsed}}):null}function mI(e,t){let n=dV(t,k(e,t));return oe(e,t).map(r=>{let i=fI(r.importedName,r.localName,r.kind),o=r.kind==="side-effect"||mV(t,r)||n.has(r.localName??r.importedName)?!0:r.used;return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:o}})}function dV(e,t){let n=new Set;if(N(e)!=="python")return n;let r=/(?:^|\n)\s*__all__\s*(?:\+?=)\s*[[(]([\s\S]*?)[\])]/g;for(let i of t.matchAll(r)){let o=i[1]??"";for(let s of o.matchAll(/(['"])([A-Za-z_]\w*)\1/g))n.add(s[2])}return n}function mV(e,t){if(N(e)!=="rust"||t.used||t.kind==="side-effect")return!1;let n=t.localName??t.importedName;return n==="_"||/^[A-Z]/.test(n)}function fI(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 fV(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function pV(e,t){let n=G(e,t);if(!n)return[];let i=new F(e).definitionsForFile(n.relativePath).filter(o=>o.symbol!==n.symbol).filter(o=>vh(n.symbol,o.symbol)).sort((o,s)=>o.startLine-s.startLine||o.endLine-s.endLine).map(o=>({symbol:o.symbol,shortName:E(o.symbol),startLine:o.startLine,endLine:o.endLine,kind:be(o.symbol)??"unknown"}));return N(n.relativePath)!=="clojure"?i:hV(i,gV(e,n))}function gV(e,t){let n=T(t.symbol);if(!n)return[];let r=E(t.symbol);return(Y(e,t.relativePath)?.clojureMembers??[]).filter(i=>i.ownerName===n).map(i=>({symbol:`${t.symbol}${i.memberName}().`,shortName:`${r}:${i.memberName}()`,startLine:i.startLine,endLine:i.endLine,kind:i.memberKind}))}function hV(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.shortName}:${r.startLine}:${r.endLine}`,r);return[...n.values()].sort((r,i)=>r.startLine-i.startLine||r.endLine-i.endLine)}function yV(e,t){let n=G(e,t);if(!n)return[];let r=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
|
|
584
|
+
FROM mentions m
|
|
585
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
586
|
+
JOIN (
|
|
587
|
+
SELECT m2.symbol_id, c2.document_id
|
|
588
|
+
FROM mentions m2
|
|
589
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
590
|
+
WHERE m2.role = 1
|
|
591
|
+
GROUP BY m2.symbol_id
|
|
592
|
+
) sym_def ON sym_def.symbol_id = m.symbol_id
|
|
593
|
+
WHERE m.symbol_id = ?
|
|
594
|
+
AND m.role != 1
|
|
595
|
+
AND sym_def.document_id != c.document_id`,n.symbolId);return[{name:E(n.symbol),count:r?.file_count??0,symbol:n.symbol,definedIn:n.relativePath}]}function bV(e,t){let n=it(e,t);if(!n)return[];let i=e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
|
|
596
|
+
FROM mentions m
|
|
597
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
598
|
+
JOIN documents d ON c.document_id = d.id
|
|
599
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
600
|
+
JOIN (
|
|
601
|
+
SELECT m2.symbol_id, c2.document_id
|
|
602
|
+
FROM mentions m2
|
|
603
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
604
|
+
WHERE m2.role = 1
|
|
605
|
+
GROUP BY m2.symbol_id
|
|
606
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
607
|
+
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
608
|
+
WHERE d.relative_path = ?
|
|
609
|
+
AND m.role != 1
|
|
610
|
+
AND def_d.id != d.id
|
|
611
|
+
GROUP BY d.id
|
|
612
|
+
ORDER BY symbol_count DESC`,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}));if(i.length>0)return i;let s=le(e).get(n);return!s||s.size===0?[]:[{name:n,count:s.size}]}function SV(e,t={}){return xV(e,t).map(n=>({name:E(n.symbol),count:n.file_count,symbol:n.symbol,definedIn:n.defined_in}))}function xV(e,t){let{limit:n=30,scope:r}=t,i=r?"AND def_d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[];return e.all(`SELECT gs.symbol,
|
|
613
|
+
COUNT(DISTINCT c.document_id) AS file_count,
|
|
614
|
+
def_d.relative_path AS defined_in
|
|
615
|
+
FROM mentions m
|
|
616
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
617
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
618
|
+
JOIN (
|
|
619
|
+
SELECT m2.symbol_id, c2.document_id
|
|
620
|
+
FROM mentions m2
|
|
621
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
622
|
+
WHERE m2.role = 1
|
|
623
|
+
GROUP BY m2.symbol_id
|
|
624
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
625
|
+
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
626
|
+
WHERE m.role != 1
|
|
627
|
+
AND def_d.id != c.document_id
|
|
628
|
+
${e.pathExclusionsFor("def_d")}
|
|
629
|
+
${e.symbolNoiseFor("gs")}
|
|
630
|
+
${i}
|
|
631
|
+
GROUP BY gs.id
|
|
632
|
+
HAVING file_count > 1
|
|
633
|
+
ORDER BY file_count DESC
|
|
634
|
+
LIMIT ?`,...o,n)}function RV(e,t={}){let{limit:n=30,scope:r}=t,i=r?"AND d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[];return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
|
|
635
|
+
FROM mentions m
|
|
636
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
637
|
+
JOIN documents d ON c.document_id = d.id
|
|
638
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
639
|
+
JOIN (
|
|
640
|
+
SELECT m2.symbol_id, c2.document_id
|
|
641
|
+
FROM mentions m2
|
|
642
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
643
|
+
WHERE m2.role = 1
|
|
644
|
+
GROUP BY m2.symbol_id
|
|
645
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
646
|
+
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
647
|
+
WHERE m.role != 1
|
|
648
|
+
AND def_d.id != d.id
|
|
649
|
+
${e.pathExclusionsFor("d")}
|
|
650
|
+
${e.symbolNoiseFor("gs")}
|
|
651
|
+
${i}
|
|
652
|
+
GROUP BY d.id
|
|
653
|
+
ORDER BY symbol_count DESC
|
|
654
|
+
LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}))}var pI=`SELECT COUNT(*) AS shared
|
|
655
|
+
FROM (
|
|
656
|
+
SELECT definition_m.symbol_id
|
|
657
|
+
FROM documents definition_d
|
|
658
|
+
JOIN chunks definition_c ON definition_c.document_id = definition_d.id
|
|
659
|
+
JOIN mentions definition_m ON definition_m.chunk_id = definition_c.id
|
|
660
|
+
AND definition_m.role = 1
|
|
661
|
+
JOIN mentions reference_m ON reference_m.symbol_id = definition_m.symbol_id
|
|
662
|
+
AND reference_m.role != 1
|
|
663
|
+
JOIN chunks reference_c ON reference_c.id = reference_m.chunk_id
|
|
664
|
+
JOIN documents reference_d ON reference_d.id = reference_c.document_id
|
|
665
|
+
WHERE definition_d.relative_path = ?
|
|
666
|
+
AND reference_d.relative_path = ?
|
|
667
|
+
UNION
|
|
668
|
+
SELECT definition_m.symbol_id
|
|
669
|
+
FROM documents definition_d
|
|
670
|
+
JOIN chunks definition_c ON definition_c.document_id = definition_d.id
|
|
671
|
+
JOIN mentions definition_m ON definition_m.chunk_id = definition_c.id
|
|
672
|
+
AND definition_m.role = 1
|
|
673
|
+
JOIN mentions reference_m ON reference_m.symbol_id = definition_m.symbol_id
|
|
674
|
+
AND reference_m.role != 1
|
|
675
|
+
JOIN chunks reference_c ON reference_c.id = reference_m.chunk_id
|
|
676
|
+
JOIN documents reference_d ON reference_d.id = reference_c.document_id
|
|
677
|
+
WHERE definition_d.relative_path = ?
|
|
678
|
+
AND reference_d.relative_path = ?
|
|
679
|
+
)`;function CV(e,t,n){let r=it(e,t)??t,i=it(e,n)??n,o=e.get(pI,r,i,i,r);return{...gI(r,i,o?.shared??0)}}function vV(e,t={}){let{limit:n=20,scope:r}=t,i=r?"AND def_d.relative_path LIKE ? AND ref_d.relative_path LIKE ?":"",o=r?[`%${r}%`,`%${r}%`]:[];return e.all(`SELECT
|
|
680
|
+
def_d.relative_path AS file1,
|
|
681
|
+
ref_d.relative_path AS file2,
|
|
682
|
+
COUNT(DISTINCT gs.id) AS shared
|
|
683
|
+
FROM mentions m
|
|
684
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
685
|
+
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
686
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
687
|
+
JOIN (
|
|
688
|
+
SELECT m2.symbol_id, c2.document_id
|
|
689
|
+
FROM mentions m2
|
|
690
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
691
|
+
WHERE m2.role = 1
|
|
692
|
+
GROUP BY m2.symbol_id
|
|
693
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
694
|
+
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
695
|
+
WHERE m.role != 1
|
|
696
|
+
AND def_d.id != ref_d.id
|
|
697
|
+
${e.pathExclusionsFor("def_d","ref_d")}
|
|
698
|
+
${i}
|
|
699
|
+
GROUP BY def_d.id, ref_d.id
|
|
700
|
+
ORDER BY shared DESC
|
|
701
|
+
LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.file1)&&!e.isIgnored(a.file2)).map(a=>gI(a.file1,a.file2,a.shared))}function gI(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 Ms(e,t={}){return bI(e,t).cycles}function bI(e,t={}){let{scope:n,maxDepth:r=10}=t,i=le(e,n,{scipEdges:"imports-only"}),o=[],s=new Set,a=new Set,c=[],l=!1;function u(m,f){if(f>r){l=!0;return}if(a.has(m)){let g=c.indexOf(m);if(g!==-1){let y=c.slice(g).concat(m),h=y.indexOf(y.reduce((R,x)=>R<x?R:x)),S=[...y.slice(h,-1),...y.slice(0,h),y[h]],b=S.join(" -> ");d.has(b)||(d.add(b),o.push({path:S,kind:IV(S)}))}return}if(s.has(m))return;s.add(m),a.add(m),c.push(m);let p=i.get(m);if(p)for(let g of p)u(g,f+1);c.pop(),a.delete(m)}let d=new Set;for(let m of i.keys())s.has(m)||u(m,0);return o.sort((m,f)=>m.kind!==f.kind?m.kind==="real"?-1:1:m.path.length-f.path.length),{cycles:o,truncated:l,maxDepth:r}}function IV(e){for(let r of e){let i=U(r);if(i==="test"||i==="barrel"||i==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":Qi(t)||Qi(n)||hI(t,n)||hI(n,t)||yI(t,n)||yI(n,t)||U(t)==="entry"||U(n)==="entry"?"module-hierarchy":"real"}function hI(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 yI(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=e.replace(/\.rs$/,""),r=t.replace(/\.rs$/,"");if(n===r+"_tests"||n===r+"/tests")return!0;let i=e.split("/"),o=t.split("/");if(i.length===o.length&&i.includes("tests")&&o.includes("src")){let s=i[i.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}import{readdirSync as wV}from"fs";import{join as SI}from"path";function gr(e,t){let n=vl(e),r=vl(t);if(n.endsWith("/**")){let i=n.slice(0,-3);return r===i||r.startsWith(`${i}/`)}if(n.endsWith("/*")){let i=n.slice(0,-2);if(!r.startsWith(`${i}/`))return!1;let o=r.slice(i.length+1);return o.length>0&&!o.includes("/")}return n==="**"?!0:n==="*"?r.length>0&&!r.includes("/"):n===r}function EV(e){return vl(e).replace(/\/\*\*?$/,"")}function Il(e,t){let n=vl(t),r=EV(n),i=n.endsWith("/**"),o=[],s=(a,c)=>{let l;try{l=wV(a,{withFileTypes:!0})}catch{return}for(let u of l){if(u.name.startsWith("."))continue;let d=c?`${c}/${u.name}`:u.name;gr(n,d)&&o.push(d),i&&u.isDirectory()&&s(SI(a,u.name),d)}};return s(SI(e,r),r),o.sort()}function vl(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}function Ns(e){let t=new Map,n=[],r=new Map,i=new Map,o=new Set,s=[],a=0,c=l=>(e.get(l)??[]).values();for(let l of e.keys()){if(r.has(l))continue;let u=[];for(r.set(l,a),i.set(l,a),a+=1,s.push(l),o.add(l),u.push({node:l,iter:c(l),pendingChild:null});u.length>0;){let d=u[u.length-1];if(d.pendingChild!==null){let p=d.pendingChild;d.pendingChild=null,i.set(d.node,Math.min(i.get(d.node),i.get(p)))}let m=d.iter.next();if(m.done){if(i.get(d.node)===r.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;r.has(f)?o.has(f)&&i.set(d.node,Math.min(i.get(d.node),r.get(f))):(r.set(f,a),i.set(f,a),a+=1,s.push(f),o.add(f),d.pendingChild=f,u.push({node:f,iter:c(f),pendingChild:null}))}}return{components:n,componentOf:t}}var DV=/\.(test|spec)\.(ts|tsx|js|jsx|mts|cts)$/,xI=new Map;function RI(e,t,n,r){if(!t?.testPaths?.length)return[];let i=PV(t),o=[];for(let s of kV(e,t.testPaths)){let a=TV(e,s,r),c=a?n(a):null;if(c)for(let l of oe(e,s)){let u=l.sourcePath;if(!u)continue;let d=n(u);d&&d!==c&&(i.get(c)?.has(d)||o.push({testFile:s,ownerBoundary:c,importedFile:u,importedBoundary:d,reason:"outside-owner-policy"}))}}return FV(o)}function PV(e){let t=e.allowedDependencies??{},n=e.boundaries.map(s=>s.name),r=new Map,i=(s,a)=>{for(let c of t[s]??[])a.has(c)||(a.add(c),i(c,a))};for(let s of n){let a=new Set;i(s,a),r.set(s,a)}let o=new Map;for(let s of n){let a=new Set(r.get(s));for(let c of n)c!==s&&r.get(c)?.has(s)&&a.add(c);o.set(s,a)}return o}function kV(e,t){let n=`${e.config.projectRoot}\0${t.join("\0")}`,r=xI.get(n);if(r)return r;let i=new Set;for(let s of t)for(let a of Il(e.config.projectRoot,s))DV.test(a)&&i.add(a);let o=[...i].sort();return xI.set(n,o),o}function TV(e,t,n){let r=t.replace(/^tests\//,"src/").replace(/\.(test|spec)\.(\w+)$/,".$2");if(r!==t&&n(r))return r;let i=t.split("/").pop().replace(/\.(test|spec)\.(\w+)$/,".$2"),o=oe(e,t).map(s=>s.sourcePath).filter(s=>!!s&&n(s)&&s.split("/").pop()===i);return o.length===1?o[0]:null}function FV(e){let t=new Map;for(let n of e){let r=`${n.testFile}\0${n.importedBoundary}`;t.has(r)||t.set(r,n)}return[...t.values()].sort((n,r)=>n.testFile.localeCompare(r.testFile)||n.importedBoundary.localeCompare(r.importedBoundary))}var Wt="architecture:";function CI(e,t,n,r={}){let i=LV(e,t);if(!n||n.boundaries.length===0)return{configured:!1,boundaries:[],edges:[],forbiddenEdges:[],reciprocalPairs:[],cycles:[],coarseBoundaries:[],staleAllowances:[],boundaryLimits:[],fragileEdges:[],testBoundaryViolations:[],coverage:{totalFiles:i.length,mappedFiles:0,unmappedFiles:[],ambiguousFiles:[]},policyCoverage:{declaredRows:0,totalBoundaries:0,missingRows:[],requiresCompletePolicy:!1,requiresMinimalPolicy:!1}};let o=new Map,s=new Map(n.boundaries.map(b=>[b.name,new Set])),a=[],c=[];for(let b of i){let R=n.boundaries.filter(x=>x.paths.some(v=>gr(v,b))).map(x=>x.name).sort();if(R.length===0)a.push(b);else if(R.length>1)c.push({file:b,boundaries:R});else{let x=R[0];o.set(b,x),s.get(x).add(b)}}let l=new Map;for(let[b,R]of e){let x=o.get(b);if(x)for(let v of R){let C=o.get(v);if(!C||x===C)continue;let w=no(x,C),I=l.get(w);I||(I={from:x,to:C,fileEdges:[],importers:new Set,importedFiles:new Set},l.set(w,I)),I.fileEdges.push({fromFile:b,toFile:v}),I.importers.add(b),I.importedFiles.add(v)}}let u=[...l.values()].map(b=>MV(b,n)).sort(qV),d=u,m=new Map(d.map(b=>[no(b.from,b.to),b])),f=new Map(n.boundaries.map(b=>[b.name,new Set]));for(let b of d)f.get(b.from).add(b.to);let p=[];for(let b of d){if(b.from>=b.to)continue;let R=m.get(no(b.to,b.from));R&&p.push({boundaries:[b.from,b.to],forward:b,reverse:R})}let{components:g}=Ns(f),y=g.filter(b=>b.length>1).map(b=>OV(b,d,n.requireAcyclic===!0)).sort((b,R)=>R.boundaries.length-b.boundaries.length||b.boundaries.join("/").localeCompare(R.boundaries.join("/"))),h=n.allowedDependencies??{},S=n.boundaries.map(b=>b.name).filter(b=>!Object.hasOwn(h,b)).sort();return{configured:!0,boundaries:n.boundaries.map(b=>({name:b.name,paths:[...b.paths],fileCount:s.get(b.name).size,dependencyPolicyDeclared:Object.hasOwn(h,b.name)})).sort((b,R)=>b.name.localeCompare(R.name)),edges:u,forbiddenEdges:d.filter(b=>b.policyStatus==="forbidden"),reciprocalPairs:p,cycles:y,staleAllowances:jV(n,d),boundaryLimits:$V(n,d,s),fragileEdges:d.filter(b=>b.fragile),testBoundaryViolations:r.testBoundaryViolations??[],coarseBoundaries:BV(e,s,r.isModuleHierarchyFile,n.requireResolvedBoundaries===!0,b=>n.boundaries.find(R=>R.name===b)?.subUnits??"directory"),coverage:{totalFiles:i.length,mappedFiles:o.size,unmappedFiles:a,ambiguousFiles:c},policyCoverage:{declaredRows:n.boundaries.length-S.length,totalBoundaries:n.boundaries.length,missingRows:S,requiresCompletePolicy:n.requireCompletePolicy===!0,requiresMinimalPolicy:n.requireMinimalPolicy===!0}}}function ti(e,t={}){let n=le(e,t.scope,{scipEdges:"imports-only",sourceEdges:"imports-and-reexports"}),r=L(e,{includeIgnored:!1}).filter(o=>!t.scope||o.includes(t.scope)),i=new Set(r);return CI(n,r,e.config.architecture,{isModuleHierarchyFile:o=>AV(e,o),testBoundaryViolations:RI(e,e.config.architecture,o=>_V(e.config.architecture,o),o=>i.has(o))})}function _V(e,t){let n=(e?.boundaries??[]).filter(r=>r.paths.some(i=>gr(i,t)));return n.length===1?n[0].name:null}function AV(e,t){let n=U(t);return n==="test"||n==="entry"?!0:n!=="barrel"?!1:ie(e,t).length===0}function wl(e){let t=e.forbiddenEdges.map(r=>`${Wt}forbidden-edge:${encodeURIComponent(r.from)}:${encodeURIComponent(r.to)}`);if(e.policyCoverage.requiresCompletePolicy)for(let r of e.policyCoverage.missingRows)t.push(`${Wt}missing-policy-row:${encodeURIComponent(r)}`);if(e.policyCoverage.requiresMinimalPolicy)for(let r of e.staleAllowances)t.push(`${Wt}stale-allowance:${encodeURIComponent(r.from)}:${encodeURIComponent(r.to)}`);for(let r of e.testBoundaryViolations)t.push(`${Wt}test-boundary:${encodeURIComponent(r.testFile)}:${encodeURIComponent(r.importedBoundary)}`);for(let r of e.boundaryLimits)t.push(`${Wt}boundary-limit:${r.kind}:${encodeURIComponent(r.boundary)}`);let n=new Map;for(let r of e.coarseBoundaries)r.violatesPolicy&&n.set(r.boundary,(n.get(r.boundary)??0)+1);for(let[r,i]of n){let o=`${Wt}coarse-boundary:${encodeURIComponent(r)}`;t.push(o);for(let s=2;s<=i;s+=1)t.push(`${o}:component:${s}`)}for(let r of e.cycles)r.violatesPolicy&&t.push(`${Wt}cycle:${r.boundaries.map(i=>encodeURIComponent(i)).sort().join("|")}`);return[...new Set(t)].sort()}function vI(e){return!!e&&(Object.keys(e.allowedDependencies??{}).length>0||e.requireCompletePolicy===!0||e.requireAcyclic===!0||e.requireResolvedBoundaries===!0||e.requireMinimalPolicy===!0||e.maxBoundaryFanOut!==void 0||e.maxBoundaryFiles!==void 0||e.boundaries.some(t=>t.maxFiles!==void 0)||(e.testPaths?.length??0)>0)}function LV(e,t){let n=new Set(t);for(let[r,i]of e){n.add(r);for(let o of i)n.add(o)}return[...n].sort()}function MV(e,t){let n=[...e.fileEdges].sort((r,i)=>r.fromFile.localeCompare(i.fromFile)||r.toFile.localeCompare(i.toFile));return{from:e.from,to:e.to,policyStatus:NV(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 NV(e,t,n){return!e.allowedDependencies||!Object.hasOwn(e.allowedDependencies,t)?"undeclared":e.allowedDependencies[t].includes(n)?"allowed":"forbidden"}function OV(e,t,n){let r=[...e].sort(),i=new Set(r),o=t.filter(a=>i.has(a.from)&&i.has(a.to)),s=Math.min(...o.map(a=>a.fileEdgeCount));return{boundaries:r,internalEdges:o,narrowestEdges:o.filter(a=>a.fileEdgeCount===s),violatesPolicy:n}}function BV(e,t,n=HV,r=!1,i=()=>"directory"){let o=[];for(let[s,a]of t){let c=i(s)==="file"?p=>p:GV,l=[...a].filter(p=>!n(p));if(l.length<2)continue;let u=new Set(l),d=new Map,m=new Map;for(let p of l)m.set(c(p),new Set);for(let p of l)for(let g of e.get(p)??[]){if(!u.has(g))continue;let y=c(p),h=c(g);if(y===h)continue;let S=no(y,h),b=d.get(S);b||(b={from:y,to:h,fileEdges:[]},d.set(S,b)),b.fileEdges.push({fromFile:p,toFile:g}),m.get(y).add(h)}let{components:f}=Ns(m);for(let p of f){if(p.length<2)continue;let g=new Set(p),y=[...d.values()].filter(S=>g.has(S.from)&&g.has(S.to)).map(S=>({from:S.from,to:S.to,fileEdgeCount:S.fileEdges.length,examples:S.fileEdges.slice(0,5)})).sort((S,b)=>S.from.localeCompare(b.from)||S.to.localeCompare(b.to)),h=Math.min(...y.map(S=>S.fileEdgeCount));o.push({boundary:s,violatesPolicy:r,subUnits:[...p].sort(),internalEdges:y,narrowestEdges:y.filter(S=>S.fileEdgeCount===h)})}}return o.sort((s,a)=>a.subUnits.length-s.subUnits.length||s.boundary.localeCompare(a.boundary))}function jV(e,t){let n=new Set(t.map(s=>no(s.from,s.to))),r=e.allowedDependencies??{},i=new Set(e.boundaries.map(s=>s.name)),o=[];for(let[s,a]of Object.entries(r))if(i.has(s))for(let c of a)!i.has(c)||n.has(no(s,c))||o.push({from:s,to:c});return o.sort((s,a)=>s.from.localeCompare(a.from)||s.to.localeCompare(a.to))}function $V(e,t,n){let r=[],i=new Map;for(let o of t)i.set(o.from,(i.get(o.from)??0)+1);for(let o of e.boundaries){if(e.maxBoundaryFanOut!==void 0){let a=i.get(o.name)??0;a>e.maxBoundaryFanOut&&r.push({boundary:o.name,kind:"fan-out",observed:a,limit:e.maxBoundaryFanOut})}let s=o.maxFiles??e.maxBoundaryFiles;if(s!==void 0){let a=n.get(o.name)?.size??0;a>s&&r.push({boundary:o.name,kind:"files",observed:a,limit:s})}}return r.sort((o,s)=>o.boundary.localeCompare(s.boundary)||o.kind.localeCompare(s.kind))}function HV(e){let t=U(e);return t==="test"||t==="entry"}function GV(e){let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)}function no(e,t){return`${e}\0${t}`}function qV(e,t){return e.from.localeCompare(t.from)||e.to.localeCompare(t.to)}function UV(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:o=2,scanLimit:s}=t,a=new F(e),c=fe(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s),l=t.semantic!==!1,u=_s(e,c,{limit:500,semantic:l,semanticEvidence:q});return c.map(m=>VV(e,m,l,u.get(m.symbolId)??[])).filter(m=>m.fanIn>=i&&m.fanOut>=o).sort((m,f)=>f.score-m.score||f.fanIn-m.fanIn).slice(0,n)}function VV(e,t,n,r){let i=[...new Set(r.map(u=>u.file))].sort(),o=new Map;for(let u of Bt(e,t,{limit:500,semantic:n,semanticEvidence:q})){if(u.file===t.relativePath)continue;let d=`${u.symbol}|${u.file}`;o.has(d)||o.set(d,{symbol:u.symbol,shortName:E(u.symbol),file:u.file})}let s=[...o.values()].sort((u,d)=>u.file.localeCompare(d.file)||u.symbol.localeCompare(d.symbol)),a=i.length,c=s.length,l=a*c;return{symbol:t.symbol,shortName:E(t.symbol),fanIn:a,fanOut:c,callerFiles:i,externalCallees:s,score:l,definedIn:t.relativePath,actionTier:"signal",riskKind:"coordination-hotspot",evidenceReasons:[`${a} incoming file(s) reference this symbol`,`${c} distinct cross-file callee symbol(s) are reached from it`,`centrality score is ${l} (fan-in * fan-out)`],recommendation:"Review ownership, API stability, and caller groups before changing this central symbol; do not refactor solely from graph centrality."}}function Os(e,t={}){let{scope:n,minLoc:r=3,scanLimit:i}=t,o=new F(e),s=t.semantic!==!1,a=0,c=D("isolated.candidates",()=>{let v=fe(o.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:typeof i=="number"&&i>0}),i).filter(C=>!to(e,C));return a=v.length,v},()=>({definitions:a})),l=0,u=D("isolated.strict-callees",()=>{let x=o.symbolsWithNonSelfCallees(c,{additive:!1,semantic:!1});return l=x.size,x},()=>({definitions:c.length,symbols:l})),d=c.filter(x=>!u.has(x.symbolId)),m=0,f=D("isolated.scip-callers",()=>{let x=o.crossFileCallerMap(d,{semantic:!1});return m=x.size,x},()=>({definitions:d.length,symbols:m})),p=new Set(f.keys());for(let x of o.frameworkReferencedSymbolIds(d))p.add(x);let g=d.filter(x=>!p.has(x.symbolId));if(s&&g.length>0){for(let x of lr(e,g).keys())p.add(x);for(let x of o.symbolsWithNonSelfCallees(g,{additive:!1,semantic:!0}))u.add(x);g=g.filter(x=>!p.has(x.symbolId)).filter(x=>!u.has(x.symbolId))}let y=0,h=D("isolated.source-fallback-callers",()=>{let x=o.sourceFallbackCallerFiles(g,{skipPath:v=>U(v)==="test"});return y=x.size,x},()=>({definitions:g.length,symbols:y}));for(let x of h.keys())p.add(x);let S=g.filter(x=>!p.has(x.symbolId)),b=0,R=D("isolated.additive-callees",()=>{let x=o.symbolsWithNonSelfCallees(S,{additive:!0,semantic:s});return b=x.size,x},()=>({definitions:S.length,symbols:b}));for(let x of R)u.add(x);return S.filter(x=>!u.has(x.symbolId)).sort((x,v)=>j(v)-j(x)||x.relativePath.localeCompare(v.relativePath)||x.startLine-v.startLine).map(x=>({symbol:x.symbol,shortName:E(x.symbol),relativePath:x.relativePath,startLine:x.startLine,endLine:x.endLine,loc:j(x)}))}import{SymbolInformation_Kind as Ve}from"@c4312/scip";var II=500;function zV(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=$v.get(n);if(r!==void 0)return r;for(let[i,o]of hl)if(o.toLowerCase().includes(n))return i;return null}function WV(e,t,n={}){let{scope:r,limit:i=100}=n,o=zV(t);return o===null?[]:JV(e,r).map(a=>({row:a,resolvedKind:EI(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:E(a.symbol),kind:c,kindName:Fs(c),relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function KV(e,t={}){let n=YV(e,t.scope);for(let r of XV(e,t.scope)){let i=EI(r);i===null||i===0||n.set(i,(n.get(i)??0)+1)}return[...n.entries()].sort((r,i)=>i[1]-r[1]||r[0]-i[0]).map(([r,i])=>({kind:r,kindName:Fs(r),count:i}))}function JV(e,t){return Oe(e,{scope:t}).map(QV)}function YV(e,t){let n=new Map;for(let r of wI(L(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", "),o=e.all(`SELECT gs.kind AS kind, COUNT(*) AS count
|
|
702
|
+
FROM defn_enclosing_ranges der
|
|
703
|
+
JOIN global_symbols gs ON der.symbol_id = gs.id
|
|
704
|
+
JOIN documents d ON der.document_id = d.id
|
|
705
|
+
WHERE gs.kind IS NOT NULL
|
|
706
|
+
AND gs.kind != 0
|
|
707
|
+
AND gs.symbol NOT LIKE '%#'
|
|
708
|
+
AND d.relative_path IN (${i})
|
|
709
|
+
GROUP BY gs.kind`,...r);for(let s of o)n.set(s.kind,(n.get(s.kind)??0)+s.count)}return n}function XV(e,t){let n=[];for(let r of wI(L(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", ");n.push(...e.all(`SELECT gs.symbol,
|
|
710
|
+
gs.kind,
|
|
711
|
+
gs.documentation,
|
|
712
|
+
gs.enclosing_symbol,
|
|
713
|
+
d.relative_path,
|
|
714
|
+
der.start_line,
|
|
715
|
+
der.end_line
|
|
716
|
+
FROM defn_enclosing_ranges der
|
|
717
|
+
JOIN global_symbols gs ON der.symbol_id = gs.id
|
|
718
|
+
JOIN documents d ON der.document_id = d.id
|
|
719
|
+
WHERE (gs.kind IS NULL OR gs.kind = 0 OR gs.symbol LIKE '%#')
|
|
720
|
+
${e.symbolNoiseFor("gs")}
|
|
721
|
+
AND d.relative_path IN (${i})
|
|
722
|
+
ORDER BY d.relative_path, der.start_line, der.end_line, gs.symbol`,...r))}return n}function wI(e){let t=[];for(let n=0;n<e.length;n+=II)t.push(e.slice(n,n+II));return t}function QV(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 EI(e){return e.kind!==null&&e.kind!==0?ZV(e.kind,e.symbol,e.documentation):ez(e.symbol,e.documentation,e.enclosing_symbol)}function ZV(e,t,n){let r=(n??"").toLowerCase();if(be(t)==="type"){if(r.includes("type "))return Ve.TypeAlias;if(r.includes("interface "))return Ve.Interface;if(r.includes("struct "))return Ve.Struct;if(r.includes("trait "))return Ve.Trait;if(r.includes("class "))return Ve.Class}return e}function ez(e,t,n){let r=Te(e);if("kind"in r)return null;let i=r.descriptors,o=i[i.length-2]??null,s=be(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?Ve.TypeAlias:a.includes("interface ")?Ve.Interface:a.includes("struct ")?Ve.Struct:a.includes("trait ")?Ve.Trait:a.includes("class ")?Ve.Class:Ve.Class:s==="method"?o?.suffix==="type"?Ve.Method:Ve.Function:s==="namespace"?Ve.Module:s!=="term"?null:a.includes("async def ")||a.includes("def ")?Ve.Function:(n?be(n):o?.suffix??null)==="type"?Ve.Field:Ve.Variable}function tz(e,t={}){let{limit:n=10,scope:r,minDepth:i=3}=t,o=le(e,r),{components:s,componentOf:a}=Ns(o),c=new Map;for(let g=0;g<s.length;g++)c.set(g,new Set);for(let[g,y]of o){let h=a.get(g);for(let S of y){let b=a.get(S);b!==h&&c.get(h).add(b)}}let l=new Array(s.length),u=new Array(s.length);for(let g=0;g<s.length;g++){let y=[],h=0;for(let S of c.get(g)){let b=u[S];b>h&&(h=b,y=l[S])}l[g]=[g,...y],u[g]=1+h}function d(g){return l[g]}let m=s.map(g=>[...g].sort()),f=new Set,p=[];for(let g=0;g<s.length;g++){let h=d(g).map(R=>m[R]),S=h.map(R=>R[0]);if(h.length<i)continue;let b=S.join(" ");f.has(b)||(f.add(b),p.push(nz(S,h)))}return p.sort((g,y)=>y.depth-g.depth),rz(p).slice(0,n)}function nz(e,t){let n=t.reduce((i,o)=>i+o.length,0),r=t.filter(i=>i.length>1).length;return{chain:e,components:t,depth:t.length,fileCount:n,actionTier:"signal",chainKind:"transitive-dependency-depth",evidenceReasons:[`${t.length} condensed dependency component(s) form the representative transitive path`,`${n} file(s) are represented; ${r} component(s) contain a dependency cycle`,"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 rz(e){let t=[];for(let n of e)t.some(r=>iz(n.chain,r.chain))||t.push(n);return t}function iz(e,t){if(e.length>=t.length)return!1;let n=t.length-e.length;for(let r=0;r<e.length;r++)if(e[r]!==t[n+r])return!1;return!0}function oz(e,t){let n=G(e,t);if(!n)return[];let r=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
|
|
723
|
+
WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:E(r.symbol),depth:0}],o=r.enclosing_symbol,s=1,a=new Set([r.symbol]);for(;o&&!a.has(o)&&s<20;){a.add(o);let d=e.get("SELECT symbol, enclosing_symbol FROM global_symbols WHERE symbol = ?",o);if(!d)break;i.push({symbol:d.symbol,shortName:E(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(i.length>1)return i;let c=Te(r.symbol);if("kind"in c)return i;let l=c.descriptors;if(l.length<=1)return i;let u=[i[0]];for(let d=l.length-2,m=1;d>=0;d--,m++){let p=l.slice(0,d+1).map(g=>g.suffix==="method"?`${g.name}()`:g.name.replace(/\.(ts|tsx|js|jsx|mjs|cjs|py|pyi|rs|java|scala|kt|kts|rb|go|cs|vb|dart|php|c|cc|cpp|cxx|h|hpp)$/,"")).join(":");u.push({symbol:p,shortName:p,depth:m})}return u}function ip(e,t,n={}){let r=G(e,t);if(!r)return null;let i=n.semantic!==!1,o=Nn(e,r,{semantic:i,semanticEvidence:q}).filter(a=>ae(a.symbol)).slice(0,50),s=eo(Bt(e,r,{limit:50,additive:!0,callableOnly:!0,semantic:i,semanticEvidence:q}));return{symbol:r.symbol,shortName:E(r.symbol),callers:o.map(a=>({symbol:a.symbol,shortName:E(a.symbol),file:a.file})),callees:s.map(a=>({symbol:a.symbol,shortName:E(a.symbol),file:a.file}))}}function jt(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function ze(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function hr(e,t){if(e.size===0&&t.size===0)return 0;let n=0;for(let i of e)t.has(i)&&(n+=1);let r=e.size+t.size-n;return r===0?0:n/r}function DI(e,t){if(e.size===0)return 0;let n=0;for(let r of e)t.has(r)&&(n+=1);return n/e.size}function op(e,t){if(t<=0)return new Map;let n=new Map;for(let[r,i]of e)i>0&&n.set(r,Math.log(t/i));return n}function ro(e){let t=[...e.values()].sort((r,i)=>r-i);if(t.length===0)return 0;let n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function io(e,t){let n=0;for(let r of e){let i=t.get(r)??0;n+=i*i}return Math.sqrt(n)}function PI(e,t,n,r={}){let i=0,o=0,s=0,a=r.medianIdf??ro(n),c=[],l=[];for(let m of e){let f=n.get(m)??0;o+=f*f,t.has(m)&&(i+=f*f,f>=a?c.push(m):l.push(m))}if(c.length===0&&l.length===0)return{similarity:0,significantShared:[],trivialShared:[]};for(let m of t){let f=n.get(m)??0;s+=f*f}let u=Math.sqrt(o)*Math.sqrt(s),d=u>0?i/u:0;return c.sort((m,f)=>(n.get(f)??0)-(n.get(m)??0)),{similarity:d,significantShared:c,trivialShared:l}}function kI(e,t,n,r){let i=0,o=r.medianIdf??ro(n),s=[],a=[];for(let u of e){if(!t.has(u))continue;let d=n.get(u)??0;i+=d*d,d>=o?s.push(u):a.push(u)}if(s.length===0&&a.length===0)return{similarity:0,significantShared:[],trivialShared:[]};let c=r.magnitudeA*r.magnitudeB,l=c>0?i/c:0;return s.sort((u,d)=>(n.get(d)??0)-(n.get(u)??0)),{similarity:l,significantShared:s,trivialShared:a}}function El(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=pz(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!ae(o.symbol))return[];if(o.callees.size===0)return TI(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"});let s=az(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):TI(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"})}function lp(e,t,n,r={}){let i=G(e,t),o=G(e,n);if(!i||!o)return null;let s=El(e,i.symbol,{minSimilarity:0,limit:Number.POSITIVE_INFINITY,semantic:r.semantic,scanLimit:r.scanLimit}).find(l=>l.symbolB===o.symbol||l.symbolA===o.symbol);if(!s)return null;let a=i.endLine-i.startLine+1,c=o.endLine-o.startLine+1;return{symbolA:{symbol:i.symbol,shortName:E(i.symbol),file:i.relativePath,loc:a},symbolB:{symbol:o.symbol,shortName:E(o.symbol),file:o.relativePath,loc:c},similarity:s.similarity,similarityBasis:s.similarityBasis??"callees",sharedEvidence:s.sharedCallees,uniqueToA:s.uniqueToA,uniqueToB:s.uniqueToB,evidenceClass:s.evidenceClass,actionTier:s.actionTier,recommendation:s.recommendation,consolidationStrategy:sz(s)}}function sz(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 az(e,t,n,r){let i=oo(e).calleeIndex({minCallees:3,scanLimit:r.scanLimit,semantic:r.semantic}),o=Cz(t,i.corpus),s=Sz(o,i),a=cz(o,i),c=ro(a),l=io(o.callees,a),u=[];for(let d of s){if(d.callees.size<3)continue;let m=io(d.callees,a),f=LI(o,d,a,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:c,magnitudeA:l,magnitudeB:m});f&&u.push(f)}return u.sort((d,m)=>m.similarity-d.similarity),u}function cz(e,t){let n=new Map(t.docFreq);for(let r of e.callees)n.set(r,(n.get(r)??0)+1);return op(n,t.corpus.length+1)}function LI(e,t,n,r){let i=uz(e,t,n,r);if(!dz(i,r))return null;let{similarity:o,significantShared:s,trivialShared:a}=i,c=s.length>0?s:a,l=jI(c,"callees");return{symbolA:e.symbol,shortNameA:E(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:E(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:c.map(E),uniqueToA:[...ze(e.callees,t.callees)].map(E),uniqueToB:[...ze(t.callees,e.callees)].map(E),...l}}function lz(e,t,n,r){let i=r.magnitudeA??io(e.callees,n),o=r.magnitudeB??io(t.callees,n),s=0,a=0,c=0,l=r.medianIdf??ro(n);for(let m of e.callees){if(!t.callees.has(m))continue;let f=n.get(m)??0;s+=f*f,c+=1,f>=l&&(a+=1)}if(c===0)return!1;let u=i*o;return(u>0?s/u:0)<r.minSimilarity?!1:a>=r.requireSignificantShared||c>=r.requireSharedCount}function uz(e,t,n,r){return r.magnitudeA===void 0||r.magnitudeB===void 0?PI(e.callees,t.callees,n,{medianIdf:r.medianIdf}):kI(e.callees,t.callees,n,{medianIdf:r.medianIdf,magnitudeA:r.magnitudeA,magnitudeB:r.magnitudeB})}function dz(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 Bs(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,minCallees:o=4,crossFileOnly:s=!1,scanLimit:a}=t,c=t.semantic!==!1,l=W(),u=0,d=0,m=0,f=0,p=0,g=0,y=0;return D("similar.all",()=>{let S=oo(e).calleeIndex({minCallees:o,scope:i,scanLimit:a,semantic:c}),b=S.corpus;u=b.length;let R=t.focusFiles,x=[],v=0;return D("similar.all.pair-scan",()=>{for(let C=0;C<b.length;C+=1){let w=b[C],I=R?.has(w.file)??!1,P=S.weightedMagnitudes[C],_=new Set;for(let se of w.callees){let ee=S.candidateIndexesByCallee.get(se);if(ee)for(let A of ee)A<=C||R&&!I&&!R.has(b[A].file)||_.add(A)}l&&(m+=_.size,_.size>0&&(d+=1));for(let se of _){let ee=b[se];if(s&&w.file===ee.file){l&&(p+=1);continue}if(MI(w,ee)){l&&(g+=1);continue}l&&(f+=1);let A=LI(w,ee,S.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:S.medianIdf,magnitudeA:P,magnitudeB:S.weightedMagnitudes[se]});A&&(mz(x,A,r,v),l&&(y+=1),v+=1)}}},()=>({corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:f,crossFileSkips:p,signatureSkips:g,insertedResults:y,topResults:x.length})),D("similar.all.sort-project",()=>(x.sort((C,w)=>w.result.similarity-C.result.similarity||C.order-w.order),x.map(C=>C.result)),()=>({topResults:x.length}))},()=>({minSimilarity:n,limit:r,scope:i,minCallees:o,crossFileOnly:s,scanLimit:a,semantic:c,corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:f,crossFileSkips:p,signatureSkips:g,insertedResults:y}))}function up(e,t={}){let{minSimilarity:n=.5,scope:r,minCallees:i=4,crossFileOnly:o=!1,scanLimit:s}=t,a=t.semantic!==!1,c=W(),l=0,u=0,d=0,m=0,f=0,p=0,g=0;return D("similar.all-count",()=>{let h=oo(e).calleeIndex({minCallees:i,scope:r,scanLimit:s,semantic:a}),S=h.corpus;l=S.length;let b=t.focusFiles;return D("similar.all-count.pair-scan",()=>{for(let R=0;R<S.length;R+=1){let x=S[R],v=b?.has(x.file)??!1,C=h.weightedMagnitudes[R],w=new Set;for(let I of x.callees){let P=h.candidateIndexesByCallee.get(I);if(P)for(let _ of P)_<=R||b&&!v&&!b.has(S[_].file)||w.add(_)}c&&(d+=w.size,w.size>0&&(u+=1));for(let I of w){let P=S[I];if(o&&x.file===P.file){c&&(f+=1);continue}if(MI(x,P)){c&&(p+=1);continue}c&&(m+=1),lz(x,P,h.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:h.medianIdf,magnitudeA:C,magnitudeB:h.weightedMagnitudes[I]})&&(g+=1)}}},()=>({corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:f,signatureSkips:p,insertedResults:g})),g},()=>({minSimilarity:n,scope:r,minCallees:i,crossFileOnly:o,scanLimit:s,semantic:a,corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:f,signatureSkips:p,insertedResults:g}))}function MI(e,t){if(e.paramCount<0||t.paramCount<0)return!1;let n=Math.abs(e.paramCount-t.paramCount),r=Math.max(2,Math.ceil(Math.max(e.paramCount,t.paramCount)*.5));return n>r}var NI=me({kind:"source-fingerprints",invalidation:re("source-fingerprints"),serialize:Gz,deserialize:Hz});function mz(e,t,n,r){if(n<=0)return;if(e.length<n){e.push({result:t,order:r});return}let i=0;for(let s=1;s<e.length;s+=1){let a=e[s],c=e[i];(a.result.similarity<c.result.similarity||a.result.similarity===c.result.similarity&&a.order>c.order)&&(i=s)}let o=e[i];t.similarity<=o.result.similarity||(e[i]={result:t,order:r})}var fz=["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 pz(e,t,n){let r=G(e,t);if(!r||!ae(r.symbol))return null;let i=new F(e),o=Bt(e,r,{semantic:n.semantic,semanticEvidence:q});return{symbol:r.symbol,file:r.relativePath,callees:Dl(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}var gz=z("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),hz=z("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function OI(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=t.semantic!==!1,a=gz.get(e,()=>new Map),c=`${n}|${r??""}|${o??""}|${s}`,l=!0,u=0,d=0;return D("similar.callee-fingerprints.resolve",()=>{let m=a.get(c);if(l=m!==void 0,m||(m=xz(e,{minCallees:n,scope:r,scanLimit:o,semantic:s}),a.set(c,m)),u=m.length,i===void 0)return m;let f=m.filter(p=>p.symbol!==i);return d=m.length-f.length,f},()=>({minCallees:n,scope:r,scanLimit:o,semantic:s,cacheHit:l,corpusSize:u,excludeSymbol:i!==void 0,excludedSymbols:d}))}function yz(e,t){let{minCallees:n,scope:r,scanLimit:i}=t,o=t.semantic!==!1,s=hz.get(e,()=>new Map),a=`${n}|${r??""}|${i??""}|${o}`,c=!0,l=0,u=0,d=0;return D("similar.callee-index.resolve",()=>{let m=s.get(a);return c=m!==void 0,m||(m=bz(OI(e,{minCallees:n,scope:r,scanLimit:i,semantic:o})),s.set(a,m)),l=m.corpus.length,u=m.docFreq.size,d=m.candidateIndexesByCallee.size,m},()=>({minCallees:n,scope:r,scanLimit:i,semantic:o,cacheHit:c,corpusSize:l,indexedCallees:u,candidateBuckets:d}))}function oo(e){return{calleeCorpus:t=>OI(e,t),calleeIndex:t=>yz(e,t),sourceCorpus:(t={})=>UI(e,t),sourceIndex:(t={})=>AI(e,t),sourceCandidates:(t,n)=>(n.candidateMode??"full")==="target-pruned"?Az(e,t,{minSimilarity:n.minSimilarity,scanLimit:n.scanLimit}):_z(t,AI(e,{scanLimit:n.scanLimit}))}}function bz(e){let t=W(),n=0,r=D("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})),i=Math.max(8,Math.ceil(Math.sqrt(e.length))),o=D("similar.callee-index.idf-weights",()=>op(r,e.length),()=>({corpusSize:e.length,uniqueCallees:r.size})),s=D("similar.callee-index.weighted-magnitudes",()=>e.map(m=>io(m.callees,o)),()=>({corpusSize:e.length})),a=0,c=0,l=0,u=D("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((r.get(g)??0)>i){t&&(c+=1);continue}let y=m.get(g);y||(y=[],m.set(g,y)),y.push(f),t&&(a+=1)}}return t&&(l=m.size),m},()=>({corpusSize:e.length,buckets:l,candidateRefs:a,ubiquitousSkips:c,ubiquityThreshold:i})),d=D("similar.callee-index.median-idf",()=>ro(o),()=>({uniqueCallees:o.size}));return{corpus:e,candidateIndexesByCallee:u,docFreq:r,idfWeights:o,weightedMagnitudes:s,medianIdf:d,ubiquityThreshold:i}}function Sz(e,t){let n=new Map;for(let r of e.callees)for(let i of t.candidateIndexesByCallee.get(r)??[]){let o=t.corpus[i];o.symbol!==e.symbol&&n.set(o.symbol,o)}return n.size>0?[...n.values()]:t.corpus.filter(r=>r.symbol!==e.symbol)}function xz(e,t){let{minCallees:n,scope:r,scanLimit:i,semantic:o}=t,s=W(),a=new F(e),c=0,l=D("similar.callee-fingerprints.candidates",()=>{let g=fe(a.productionCallableDefinitions({scope:r,minLoc:5,sortByLocDesc:typeof i=="number"&&i>0}),i);return c=g.length,g},()=>({scope:r,scanLimit:i,candidateCount:c})),u=0,d=D("similar.callee-fingerprints.callee-map",()=>{let g=a.calleeMap(l,{semantic:o});if(s)for(let y of g.values())u+=y.length;return g},()=>({candidateCount:c,semantic:o,calleeEdges:u})),m=0,f=0,p=0;return D("similar.callee-fingerprints.shape",()=>{let g=l.map(S=>({symbol:S.symbol,file:S.relativePath,callees:Dl((d.get(S.symbolId)??[]).map(b=>b.symbol)),paramCount:a.callableSignature(S)?.paramCount??-1})),y=Rz(g);s&&(p=y.filter((S,b)=>S.callees.size!==g[b].callees.size).length);let h=y.filter(S=>S.callees.size>=n);return m=h.length,s&&(f=h.reduce((S,b)=>S+b.callees.size,0)),h},()=>({candidateCount:c,fingerprintCount:m,retainedCalleeCount:f,minCallees:n,siblingSaturatedFingerprints:p}))}var BI=5;function Rz(e){let t=new Map;for(let n of e){let r=t.get(n.file);r||(r=new Map,t.set(n.file,r));for(let i of n.callees)r.set(i,(r.get(i)??0)+1)}return e.map(n=>{let r=t.get(n.file);if(!r)return n;let i=[...n.callees].filter(s=>(r.get(s)??0)>=BI);if(i.length===0)return n;let o=new Set(n.callees);for(let s of i)o.delete(s);return{...n,callees:o}})}function Cz(e,t){let n=new Map;for(let o of t)if(!(o.file!==e.file||o.symbol===e.symbol))for(let s of o.callees)n.set(s,(n.get(s)??0)+1);let r=[...e.callees].filter(o=>(n.get(o)??0)+1>=BI);if(r.length===0)return e;let i=new Set(e.callees);for(let o of r)i.delete(o);return{...e,callees:i}}function Dl(e){return new Set([...e].filter(t=>!vz(t)))}function vz(e){return fz.some(t=>e.includes(t))}function TI(e,t,n){let r=Dz(e,t);if(!r||r.tokens.size<3)return[];let i=n.minSimilarity>=.5?n.minSimilarity:.3,o=[],s=n.candidateMode??"full",a=0,c=0,l=0,u=0;return D("similar.source-shape",()=>{let m=oo(e).sourceCandidates(r,{minSimilarity:i,scanLimit:n.scanLimit,candidateMode:s});a=m.length;for(let f of m){if(f.symbol===r.symbol||f.tokens.size<3)continue;c+=1;let p=jt(r.tokens,f.tokens);if(p.size<2){l+=1;continue}let g=new Set([...r.tokens,...f.tokens]),y=g.size>0?p.size/g.size:0;if(y<i){u+=1;continue}o.push({symbolA:r.symbol,shortNameA:E(r.symbol),fileA:r.file,symbolB:f.symbol,shortNameB:E(f.symbol),fileB:f.file,similarity:y,similarityBasis:"source-tokens",sharedCallees:[...p].sort(),uniqueToA:[...ze(r.tokens,f.tokens)].sort(),uniqueToB:[...ze(f.tokens,r.tokens)].sort(),...jI([...p],"source-tokens")})}return o.sort((f,p)=>p.similarity-f.similarity||f.shortNameB.localeCompare(p.shortNameB)),o.slice(0,n.limit)},()=>({symbol:r.symbol,file:r.file,targetTokens:r.tokens.size,candidateMode:s,candidates:a,comparedPairs:c,sharedSkips:l,similaritySkips:u,results:o.length}))}function jI(e,t){let n=e.flatMap(ap),r=e.flatMap(y=>FI(y,t)),i=sp(n,$I),o=sp(n,HI),s=sp(r,cp),a=[...new Set(r.filter(_I))],c=e.filter(y=>{let h=FI(y,t);return h.some(S=>cp.has(S))&&h.some(_I)}).length,l=[];i.length>0&&l.push(`access/query scaffolding: ${i.slice(0,5).join(", ")}`),o.length>0&&l.push(`framework/generic scaffolding: ${o.slice(0,5).join(", ")}`),s.length>0&&l.push(`domain behavior verbs: ${s.slice(0,5).join(", ")}`),s.length>0&&a.length>0&&l.push(`domain-specific terms: ${a.slice(0,5).join(", ")}`);let u=t==="source-tokens"&&n.length>0&&n.every(y=>GI.has(y));u&&l.push("shared source tokens are generic scaffolding");let d=s.length>0&&a.length>0,m=i.length+o.length>0,f=t==="callees"&&d&&e.length>=4&&a.length>=4&&c>=2,p=f?"domain-behavior":d?m?"mixed":"domain-behavior":i.length>0?"access-query-scaffolding":o.length>0||u?"framework-scaffolding":"structural-overlap";p==="structural-overlap"&&e.length>0&&l.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:l,recommendation:Iz(p,g)}}function Iz(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 sp(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function ap(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function FI(e,t){if(t==="source-tokens")return ap(e);let n=T(e);return ap(n.length>0?n:wz(e))}function wz(e){return e.replace(/[()`]/g," ").replace(/\.[a-z][a-z0-9]+(?=\s|$)/gi," ").split(/[:/\\\s]+/).map(r=>r.trim()).filter(r=>/[A-Za-z]/.test(r)).at(-1)?.replace(/\.$/,"")??e}function _I(e){return e.length>3&&!cp.has(e)&&!$I.has(e)&&!HI.has(e)&&!GI.has(e)&&!Ez.has(e)}var cp=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),$I=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),HI=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"]),GI=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),Ez=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 Dz(e,t){let n=G(e,t);if(!n||!ae(n.symbol))return null;let r=Pz(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function Pz(e,t){let n=T(t.symbol),r=Bz(e,t.relativePath,t.startLine,t.endLine,n),i=WI(r,n);return i.size>0?i:null}var kz=z("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),Tz=z("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function qI(e){return`${e.scanLimit??""}`}function UI(e,t={}){let n=kz.get(e,()=>new Map),r=qI(t),i=n.get(r);return i||(i=Oz(e,t),n.set(r,i)),i}function AI(e,t={}){let n=Tz.get(e,()=>new Map),r=qI(t),i=n.get(r);return i||(i=Fz(UI(e,t)),n.set(r,i)),i}function Fz(e){let t=new Map;for(let i of e)for(let o of i.tokens)t.set(o,(t.get(o)??0)+1);let n=Math.max(8,Math.ceil(Math.sqrt(e.length))),r=new Map;for(let i of e)for(let o of i.tokens){if((t.get(o)??0)>n)continue;let s=r.get(o);s||(s=[],r.set(o,s)),s.push(i)}return{corpus:e,candidateByToken:r,docFreq:t,ubiquityThreshold:n}}function _z(e,t){let n=new Map;for(let r of e.tokens)for(let i of t.candidateByToken.get(r)??[])i.symbol!==e.symbol&&n.set(i.symbol,i);return n.size>0?[...n.values()]:t.corpus.filter(r=>r.symbol!==e.symbol)}function Az(e,t,n){let r=W(),i=new F(e),o=Lz(t.tokens.size,n.minSimilarity),s=0,a=0,c=0,l=D("similar.source-shape.target-files",()=>{let p=[...t.tokens],g=[];for(let y of L(e,{includeIgnored:!1})){s+=1;let h=k(e,y);h&&(a+=1,Mz(h,p,o)&&g.push(y))}return c=g.length,g},()=>({symbol:t.symbol,targetTokens:t.tokens.size,requiredSharedTokens:o,scannedFiles:s,readableFiles:a,candidateFiles:c})),u=0,d=D("similar.source-shape.target-definitions",()=>{let p=fe(i.productionCallableDefinitions({files:l,sortByLocDesc:typeof n.scanLimit=="number"&&n.scanLimit>0}),n.scanLimit);return u=p.length,p},()=>({symbol:t.symbol,candidateFiles:c,scanLimit:n.scanLimit,definitionCount:u})),m=0;return D("similar.source-shape.target-fingerprints",()=>{let p=VI(e,d);return r&&(m=p.length),p},()=>({symbol:t.symbol,definitionCount:u,fingerprintCount:m})).filter(p=>p.symbol!==t.symbol)}function Lz(e,t){return Math.max(2,Math.ceil(e*t))}function Mz(e,t,n){if(t.length<n)return!1;let r=e.toLowerCase(),i=0;for(let o of t)if(Nz(r,o)&&(i+=1,i>=n))return!0;return!1}function Nz(e,t){return t==="num"?/\b\d+\b/.test(e):e.includes(t)}function Oz(e,t={}){let n=new F(e),{scanLimit:r}=t,i=fe(n.productionCallableDefinitions({sortByLocDesc:typeof r=="number"&&r>0}),r);return VI(e,i)}function VI(e,t){let n=new Map;for(let i of t){let o=n.get(i.relativePath)??[];o.push(i),n.set(i.relativePath,o)}let r=new Map;for(let[i,o]of n){let s=k(e,i);if(!s)continue;let a=he(e,i,s),c=$z(e,i,a),l=!1,u=null;for(let d of o){let m=jz(d),f=c.get(m),p=f?new Set(f.tokens):null;p||(u??=Ne(e,i),p=WI(zI(u,d.startLine,d.endLine,d.leaf),d.leaf),c.set(m,{key:m,symbol:d.symbol,startLine:d.startLine,endLine:d.endLine,leaf:d.leaf,tokens:[...p].sort()}),l=!0),p.size>0&&r.set(d.symbol,{symbol:d.symbol,file:d.relativePath,tokens:p})}l&&qz(e,i,a,c)}return t.map(i=>r.get(i.symbol)).filter(i=>!!i)}function Bz(e,t,n,r,i){let o=Ne(e,t);return o.length===0?"":zI(o,n,r,i)}function zI(e,t,n,r){if(n>=t&&n-t<=12)return e.slice(t,n+1).join(`
|
|
724
|
+
`);let i=[new RegExp(`\\bdef\\s+${H(r)}\\b`),new RegExp(`\\bfun\\s+${H(r)}\\b`),new RegExp(`\\bfn\\s+${H(r)}\\b`),new RegExp(`\\bfunction\\s+${H(r)}\\b`),new RegExp(`\\b${H(r)}\\s*\\(`)],o=e.findIndex(s=>i.some(a=>a.test(s)));if(o>=0){let s=o;for(let a=o+1;a<e.length&&a<=o+8;a++){let c=e[a]??"";if(a>o&&Vz(c)||(s=a,c.trim()===""&&a>o+1))break}return e.slice(o,s+1).join(`
|
|
725
|
+
`)}return e.slice(t,Math.min(e.length,t+8)).join(`
|
|
726
|
+
`)}function jz(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function $z(e,t,n){return NI.read(e,t,n)??new Map}function Hz(e){try{let t=JSON.parse(e);if(!Array.isArray(t.entries))return null;let n=new Map;for(let r of t.entries){if(!r||typeof r.key!="string"||typeof r.symbol!="string"||typeof r.startLine!="number"||typeof r.endLine!="number"||typeof r.leaf!="string"||!Array.isArray(r.tokens)||!r.tokens.every(i=>typeof i=="string"))return null;n.set(r.key,r)}return n}catch{return null}}function Gz(e){let t={entries:[...e.values()].sort((n,r)=>n.key.localeCompare(r.key))};return JSON.stringify(t)}function qz(e,t,n,r){NI.write(e,t,n,new Map(r))}function WI(e,t){if(!e)return new Set;let n=new Set(["public","private","protected","final","static","class","def","fun","fn","function","return","string","bool","boolean","void","unit","self","this","new","const","let","var","end","pub"]),r=Uz(t),o=e.replace(/["'`]/g," ").replace(/\b\d+\b/g," NUM ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[^A-Za-z0-9_]+/g," ").replace(/_/g," ").toLowerCase().split(/\s+/).map(s=>s.trim()).filter(s=>s.length>1).filter(s=>!n.has(s)).filter(s=>!r.has(s));return new Set(o)}function Uz(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 Vz(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function un(e,t){let n=new Map;return e.forEach((r,i)=>{let o=new Set;for(let s of t(r)){if(o.has(s))continue;o.add(s);let a=n.get(s);a?a.push(i):n.set(s,[i])}}),{candidatesFor:(r,i)=>{let o=new Set;for(let s of t(r)){let a=n.get(s);if(a)for(let c of a)c!==i&&o.add(c)}return[...o].sort((s,a)=>s-a)}}}function dn(e){let t=KI(e.profile?.name),n=()=>{let r=[];t=KI(e.profile?.name,e);let i=(s,a)=>{let c=e.profiles[s],l=e.profiles[a];t.candidatePairs+=1,t.comparedPairs+=1;let u=e.compare(c,l);u&&r.push(u)};if(e.filePattern){let s=e.profiles.findIndex(a=>a.file.includes(e.filePattern));if(s>=0){let a=e.profiles[s];for(let c of zz(e,s)){let l=e.profiles[c];e.focusFiles&&!e.focusFiles.has(a.file)&&!e.focusFiles.has(l.file)||i(s,c)}}}else if(e.focusFiles?.size!==0){let s=typeof e.overrunFactor=="number"&&Number.isFinite(e.limit)?e.limit*e.overrunFactor:Number.POSITIVE_INFINITY;for(let a=0;a<e.profiles.length;a+=1){let c=e.profiles[a],l=e.focusFiles?.has(c.file)??!1;for(let u of Wz(e,a))e.focusFiles&&!l&&!e.focusFiles.has(e.profiles[u].file)||i(a,u);if(r.length>s){t.overrunApplied=!0;break}}}r.sort(e.sort??((s,a)=>a.similarity-s.similarity)),t.matchedResults=r.length;let o=r.slice(0,e.limit);return t.emittedResults=o.length,e.onProfile?.({...t}),o};return e.profile?D(`pairwise-profile:${e.profile.name}`,n,()=>({...Kz(e.profile?.metadata),...t})):n()}function zz(e,t){if(e.candidateIndex)return JI(e,t,-1);let n=[];for(let r=0;r<e.profiles.length;r+=1)r!==t&&n.push(r);return n}function Wz(e,t){if(e.candidateIndex)return JI(e,t,t);let n=[];for(let r=t+1;r<e.profiles.length;r+=1)n.push(r);return n}function JI(e,t,n){let r=e.profiles[t],i=new Set;for(let o of e.candidateIndex?.candidatesFor(r,t,e.profiles)??[])o<=n||o!==t&&(o<0||o>=e.profiles.length||i.add(o));return[...i].sort((o,s)=>o-s)}function KI(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 Kz(e){return typeof e=="function"?e():e??{}}function Jz(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=Yz(e,{scope:i,minDeps:s}),l=un(a,u=>u.deps);return dn({profiles:a,limit:r,filePattern:o,overrunFactor:5,candidateIndex:l,profile:{name:"similar-files"},compare:(u,d)=>Qz(u,d,n,c)})}function Yz(e,t){let{scope:n,minDeps:r}=t,i=le(e,n),{universalDeps:o,distinctiveDeps:s}=Xz(i),a=[];for(let[c,l]of i)l.size>=r&&a.push({file:c,deps:new Set([...l].filter(u=>!o.has(u)))});return{profiles:a,distinctiveDeps:s}}function Xz(e){let t=new Set,n=new Set,r=e.size;if(r===0)return{universalDeps:t,distinctiveDeps:n};let i=new Map;for(let s of e.values())for(let a of s)i.set(a,(i.get(a)??0)+1);let o=Math.max(3,Math.ceil(r*.03));for(let[s,a]of i)a>=5&&a/r>.3?t.add(s):a<=o&&n.add(s);return{universalDeps:t,distinctiveDeps:n}}function Qz(e,t,n,r){let i=new Set;for(let l of e.deps)t.deps.has(l)&&i.add(l);if(i.size<3||e.deps.size<4||t.deps.size<4)return null;let o=0;for(let l of i)r.has(l)&&o++;if(o<2)return null;let s=hr(e.deps,t.deps);if(s<n)return null;let a=[];for(let l of e.deps)t.deps.has(l)||a.push(l);let c=[];for(let l of t.deps)e.deps.has(l)||c.push(l);return{fileA:e.file,fileB:t.file,similarity:s,sharedDeps:[...i],uniqueToA:a,uniqueToB:c}}function yr(e){let t=[],n=[],r=[];for(let l of e.primitiveGroups)l.values.length!==0&&YI(l.bucket,n,r).push(`${l.reasonPrefix}: ${l.values.join(", ")}`);for(let l of e.nameGroups)Zz(l.names,l.label,e.genericWords,e.stripPrefixes??[],t,YI(l.fallbackBucket,n,r));let i=t.length>0,o=n.length>0,s=r.length>0,a=i?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...r,...n].slice(0,6),recommendation:e.recommendation(a)}}function Pl(e,t){if(e.size===0||t.size===0)return 0;let i=jt(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(hr(e,t),i)}function br(e,t){let n=Object.fromEntries(e.map(r=>[r.name,r.count]));for(let r of t)if(Object.entries(r.min).every(([o,s])=>(n[o]??0)>=s))return{pass:!0,reason:r.reason,counts:n};return{pass:!1,reason:"shared tokens did not meet calibrated overlap thresholds",counts:n}}function kl(e,t,n){let r=t.map(c=>{let l=c.value(e),u=c.weightedValue?c.weightedValue(e,l):l;return{axis:c,value:l,weighted:u,qualifies:c.qualifies?c.qualifies(e,l):l>0}}),i=r.filter(c=>c.qualifies&&c.axis.reason).map(c=>c.axis.reason(e,c.value)),o=r.filter(c=>c.qualifies&&c.axis.dominantEligible!==!1).sort((c,l)=>l.weighted-c.weighted)[0],s=o&&o.weighted>0?o.axis.axis:n,a=[...new Set(r.filter(c=>c.qualifies).map(c=>c.axis.axis).concat(i.length>0?[]:[s]))];return{dominantPressure:s,pressureKinds:a,reasons:i}}function Z(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function Ye(e){return[...e].sort()}function Zz(e,t,n,r,i,o){let s=[],a=[];for(let c of e)eW(c,r).filter(u=>!n.has(u)).length>0?s.push(c):a.push(c);s.length&&i.push(`${t} has domain term(s): ${s.slice(0,6).join(", ")}`),a.length&&o.push(`${t} is generic workflow: ${a.slice(0,6).join(", ")}`)}function eW(e,t){let n=e.replace(/([A-Z])([A-Z][a-z])/g,"$1 $2").replace(/([a-z0-9])([A-Z])/g,"$1 $2");for(let r of t)n=n.replace(r,"");return n.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}function YI(e,t,n){return e==="generic"?t:n}function js(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=kt(e).reactProfiles({scope:o,minJsxTokens:r,scanLimit:s}).filter(d=>d.kind==="component").map(d=>({file:d.file,component:d.name,tokens:d.jsxTokens,profile:d})),u=un(l,d=>d.tokens);return dn({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-component-duplicates"},compare:(d,m)=>tW(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 tW(e,t,n){let r=jt(e.tokens,t.tokens);if(r.size<6||!nW(r))return null;let i=hr(e.tokens,t.tokens);if(i<n)return null;let o=Z(r,"component:"),s=Z(r,"native:"),a=Z(r,"prop:"),c=Z(r,"event:"),l=Z(r,"binding:"),u=rW({sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:i,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:Ye(r),sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l,evidenceClass:u.evidenceClass,actionTier:u.actionTier,evidenceClassReasons:u.reasons,recommendation:u.recommendation,uniqueToA:Ye(ze(e.tokens,t.tokens)).slice(0,25),uniqueToB:Ye(ze(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function nW(e){let t=0,n=0;for(let r of e)r.startsWith("component:")&&(t+=1),(r.startsWith("prop:")||r.startsWith("event:")||r.startsWith("native:")||r.startsWith("jsx:"))&&(n+=1);return br([{name:"component",count:t},{name:"shape",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{shape:4},reason:"shared JSX structure"}]).pass}function rW(e){return yr({genericWords:oW,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:iW})}function iW(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 oW=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 $s(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=kt(e).reactProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,component:d.name,tokens:d.behaviorTokens,profile:d})),u=un(l,d=>d.tokens);return dn({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-hook-candidates"},compare:(d,m)=>sW(d,m,n,r),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.componentA.localeCompare(m.componentA)||d.fileB.localeCompare(m.fileB)||d.componentB.localeCompare(m.componentB)})}function sW(e,t,n,r){let i=jt(e.tokens,t.tokens);if(i.size<r||!lW(i))return null;let o=Pl(e.tokens,t.tokens);if(o<n)return null;let s=Z(i,"hook:"),a=Z(i,"react-hook:"),c=Z(i,"effect:"),l=Z(i,"state:"),u=Z(i,"request:"),d=Z(i,"handler:"),m=Z(i,"handler-verb:"),f=aW({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:Ye(i),sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m,evidenceClass:f.evidenceClass,actionTier:f.actionTier,evidenceClassReasons:f.reasons,recommendation:f.recommendation,uniqueToA:Ye(ze(e.tokens,t.tokens)).slice(0,25),uniqueToB:Ye(ze(t.tokens,e.tokens)).slice(0,25),reason:uW({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function aW(e){return yr({genericWords:dW,stripPrefixes:mW,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:cW})}function cW(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 lW(e){let t=0,n=0,r=0,i=0,o=0,s=0,a=0;for(let u of e)u.startsWith("hook:")?t+=1:u.startsWith("react-hook:")?n+=1:u.startsWith("effect:")?r+=1:u.startsWith("request:")?i+=1:u.startsWith("handler:")||u.startsWith("handler-verb:")?o+=1:u.startsWith("state:")?s+=1:u.startsWith("state-hook:")&&(a+=1);let c=s+a,l=t+n+r+i+o+c;return br([{name:"requests",count:i},{name:"customHooks",count:t},{name:"namedStates",count:s},{name:"handlers",count:o},{name:"effects",count:r},{name:"reactHooks",count:n},{name:"namedBehavior",count:l}],[{min:{requests:1,namedBehavior:4},reason:"shared request workflow"},{min:{customHooks:1,requests:1,namedBehavior:5},reason:"shared custom hook and request workflow"},{min:{customHooks:1,namedStates:1,namedBehavior:5},reason:"shared custom hook and state"},{min:{customHooks:1,handlers:2,namedBehavior:5},reason:"shared custom hook and handlers"},{min:{namedStates:1,handlers:2,effects:1,namedBehavior:5},reason:"shared stateful effects"},{min:{namedStates:1,handlers:2,reactHooks:2,namedBehavior:5},reason:"shared stateful React primitives"}]).pass}function uW(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 dW=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"]),mW=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function dp(e,t={}){let{minComponentLines:n=300,minFileLines:r=800,minJsxTokens:i=80,minBehaviorTokens:o=40,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return kt(e).reactProfiles({scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>fW(d,{minComponentLines:n,minFileLines:r,minJsxTokens:i,minBehaviorTokens:o})).filter(d=>d!==null).sort((d,m)=>m.componentLines-d.componentLines||m.fileLines-d.fileLines||d.file.localeCompare(m.file)).slice(0,s)}function fW(e,t){let n=Math.max(80,Math.floor(t.minComponentLines/2)),r=kl(e,pW({minComponentLines:t.minComponentLines,minFileLines:t.minFileLines,minJsxTokens:t.minJsxTokens,minBehaviorTokens:t.minBehaviorTokens,substantialComponentLines:n}),"component"),{reasons:i}=r;if(i.length===0)return null;let o=r.dominantPressure,s=r.pressureKinds,a=gW(e),c=hW(o,s,a);return{file:e.file,component:e.name,componentLines:e.loc,fileLines:e.fileLines,jsxTokens:e.jsxTokens.size,behaviorTokens:e.behaviorTokens.size,dominantPressure:o,pressureKinds:s,contextKind:a,recommendationKind:c,recommendation:yW(c,a),reasons:i,loc:e.loc}}function pW(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 gW(e){let t=e.file.split(/[\\/]+/).filter(Boolean),n=t.slice(0,-1).map(m=>m.toLowerCase()),r=(t.at(-1)??e.name).replace(/\.[^.]+$/,""),o=n.findIndex(m=>SW.has(m))>=0,s=n.some(m=>bW.has(m));if(XI(r)||XI(e.name))return"component";let c=xW.has(r.toLowerCase()),l=/(?:Page|Route|Screen)$/.test(e.name),u=o&&/View$/.test(e.name),d=!s&&r.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()===e.name.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()&&/(?:Page|Route|Screen|View)$/.test(r);return c||l||u||d?"route-page":"component"}function XI(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&QI.has(t.at(-1))?!0:[...QI].some(n=>e.endsWith(RW(n)))}function hW(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 yW(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 bW=new Set(["component","components","panel","panels","partial","partials"]),QI=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"]),SW=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),xW=new Set(["page","route","screen"]);function RW(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Hs(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=CW(e,{scope:o,minTokens:r,scanLimit:s}),u=un(l,d=>d.tokens);return dn({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-component-duplicates"},compare:(d,m)=>IW(d,m,n),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function CW(e,t){return kt(e).vueProfiles({scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:vW(n)}))}function vW(e){return e.totalLines}function IW(e,t,n){let r=jt(e.tokens,t.tokens);if(r.size<6||!wW(r))return null;let i=hr(e.tokens,t.tokens);if(i<n)return null;let o=Z(r,"component:"),s=Z(r,"prop:"),a=Z(r,"event:"),c=Z(r,"directive:"),l=Z(r,"slot:"),u=Z(r,"id:"),d=EW({sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:c,sharedSlots:l,sharedIdentifiers:u});return{fileA:e.file,fileB:t.file,similarity:i,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:Ye(r),sharedComponents:o,sharedProps:s,sharedEvents:a,sharedDirectives:c,sharedSlots:l,sharedIdentifiers:u,evidenceClass:d.evidenceClass,actionTier:d.actionTier,evidenceClassReasons:d.reasons,recommendation:d.recommendation,uniqueToA:Ye(ze(e.tokens,t.tokens)).slice(0,25),uniqueToB:Ye(ze(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function wW(e){let t=0,n=0;for(let r of e)r.startsWith("component:")&&(t+=1),(r.startsWith("prop:")||r.startsWith("event:")||r.startsWith("directive:")||r.startsWith("slot:"))&&(n+=1);return br([{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 EW(e){return yr({genericWords:PW,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:DW})}function DW(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 PW=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 Gs(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=kt(e).vueProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,tokens:d.behaviorTokens,profile:d})),u=un(l,d=>d.tokens);return dn({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-composable-candidates"},compare:(d,m)=>kW(d,m,n,r),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function kW(e,t,n,r){let i=jt(e.tokens,t.tokens);if(i.size<r||!_W(i))return null;let o=Pl(e.tokens,t.tokens);if(o<n)return null;let s=Z(i,"composable:"),a=Z(i,"store:"),c=Z(i,"reactivity:"),l=Z(i,"lifecycle:"),u=Z(i,"request:"),d=Z(i,"function:"),m=Z(i,"function-verb:"),f=Z(i,"template-binding:"),p=Z(i,"template-event:"),g=TW({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,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:Ye(i),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:p,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:Ye(ze(e.tokens,t.tokens)).slice(0,25),uniqueToB:Ye(ze(t.tokens,e.tokens)).slice(0,25),reason:AW({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function TW(e){return yr({genericWords:LW,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:FW})}function FW(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 _W(e){let t=0,n=0,r=0,i=0,o=0,s=0,a=0;for(let u of e)u.startsWith("composable:")?t+=1:u.startsWith("store:")?n+=1:u.startsWith("request:")?r+=1:u.startsWith("lifecycle:")?i+=1:u.startsWith("function:")?o+=1:u.startsWith("reactivity:")?s+=1:(u.startsWith("function-verb:")||u.startsWith("template-binding:")||u.startsWith("template-event:"))&&(a+=1);let c=t+n,l=c+r+i+o+a;return br([{name:"requests",count:r},{name:"lifecycle",count:i},{name:"functions",count:o},{name:"reusableHooks",count:c},{name:"reactivity",count:s},{name:"namedBehavior",count:l}],[{min:{requests:1,namedBehavior:4},reason:"shared request workflow"},{min:{lifecycle:1,functions:2,namedBehavior:4},reason:"shared lifecycle workflow"},{min:{reusableHooks:2,requests:1,namedBehavior:5},reason:"shared reusable Vue hooks and requests"},{min:{reusableHooks:2,functions:2,namedBehavior:5},reason:"shared reusable Vue hooks and functions"},{min:{functions:2,reactivity:1,namedBehavior:4},reason:"shared reactive functions"}]).pass}function AW(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 LW=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 mp(e,t={}){let{minTotalLines:n=800,minTemplateLines:r=300,minScriptLines:i=300,minStyleLines:o=500,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return kt(e).vueProfiles({scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>MW(d,{minTotalLines:n,minTemplateLines:r,minScriptLines:i,minStyleLines:o})).filter(d=>d!==null).sort((d,m)=>m.totalLines-d.totalLines||d.file.localeCompare(m.file)).slice(0,s)}function MW(e,t){let n=kl(e,NW(t),"total"),{reasons:r}=n;if(r.length===0)return null;let i=n.dominantPressure,o=n.pressureKinds.includes("total")?[...new Set([...n.pressureKinds,i])]:n.pressureKinds,s=OW(e.file),a=BW(i,s),c=e.totalLines+e.delegatedComposableLines;return{file:e.file,totalLines:c,sfcLines:e.sfcLines,templateLines:e.templateLines,scriptLines:e.scriptLines,styleLines:e.styleLines,externalScriptLines:e.externalScriptLines,externalScriptPaths:e.externalScriptPaths,customBlockLines:e.customBlockLines,delegatedComposableLines:e.delegatedComposableLines,delegatedComposablePaths:e.delegatedComposablePaths,dominantPressure:i,pressureKinds:o,contextKind:s,recommendationKind:a,recommendation:jW(a,s),reasons:r,loc:c}}function NW(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 OW(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(r=>$W.has(r))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function BW(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 jW(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 $W=new Set(["landing","page","pages","route","routes","view","views"]);function HW(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=le(e,i),c=JW(a,o,s);if(c.length===0)return[];let l=GW(c);return l.length<2?[]:KW(VW(l,n,r),r)}function GW(e){let t=qW(e),n=[];for(let r of e){let i=r.filter(o=>!t.has(o));i.length>=2&&n.push({original:r,filtered:i})}return n}function qW(e){let{nodeFreq:t,tailFreq:n}=UW(e),r=e.length*.9,i=e.length*.8,o=new Set;for(let[a,c]of t)c>r&&o.add(a);for(let[a,c]of n)c>i&&o.add(a);let s=["index.ts","index.js","cli.ts","main.ts","health.ts","health.js"];for(let a of t.keys()){let c=a.split("/").pop()??"";s.includes(c)&&o.add(a)}return o}function UW(e){let t=new Map,n=new Map;for(let r of e){let i=new Set;for(let o of r)i.has(o)||(t.set(o,(t.get(o)??0)+1),i.add(o));for(let o=Math.max(0,r.length-2);o<r.length;o++)n.set(r[o],(n.get(r[o])??0)+1)}return{nodeFreq:t,tailFreq:n}}function VW(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=zW(e[i],e[o],t);s&&r.push(s)}if(r.length>n*10)break}return r.sort((i,o)=>Math.abs(o.similarity-i.similarity)>.01?o.similarity-i.similarity:i.divergencePoints.length-o.divergencePoints.length),r}function zW(e,t,n){if(!WW(e.filtered,t.filtered))return null;let{distance:r,ops:i}=YW(e.filtered,t.filtered),o=Math.max(e.filtered.length,t.filtered.length);if(o===0)return null;let s=1-r/o;if(s<n||r===0)return null;let a=i.filter(l=>l.type==="substitute").map(l=>({index:l.indexA,nodeA:e.filtered[l.indexA],nodeB:t.filtered[l.indexB]}));return a.length===0||i.filter(l=>l.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:s,editDistance:r,divergencePoints:a,commonPrefix:XW(e.original,t.original),commonSuffix:QW(e.original,t.original)}}function WW(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function KW(e,t){let n=[];for(let r of e)if(n.some(o=>ZI(r.chainA,o.chainA)&&ZI(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function JW(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;ew(e,o,[o],new Set([o]),t,n,r,500)}return r}function ew(e,t,n,r,i,o,s,a){if(s.length>=a)return;if(n.length>=o){n.length>=i&&s.push([...n]);return}let c=e.get(t);if(!c||c.size===0){n.length>=i&&s.push([...n]);return}let l=!1;for(let u of c)if(!r.has(u)&&(r.add(u),n.push(u),ew(e,u,n,r,i,o,s,a),n.pop(),r.delete(u),l=!0,s.length>=a))return;!l&&n.length>=i&&s.push([...n])}function YW(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let c=0;c<=n;c++)i[c][0]=c;for(let c=0;c<=r;c++)i[0][c]=c;for(let c=1;c<=n;c++)for(let l=1;l<=r;l++)e[c-1]===t[l-1]?i[c][l]=i[c-1][l-1]:i[c][l]=1+Math.min(i[c-1][l],i[c][l-1],i[c-1][l-1]);let o=[],s=n,a=r;for(;s>0||a>0;)s>0&&a>0&&e[s-1]===t[a-1]?(o.unshift({type:"match",indexA:s-1,indexB:a-1}),s--,a--):s>0&&a>0&&i[s][a]===i[s-1][a-1]+1?(o.unshift({type:"substitute",indexA:s-1,indexB:a-1}),s--,a--):a>0&&i[s][a]===i[s][a-1]+1?(o.unshift({type:"insert",indexA:s,indexB:a-1}),a--):(o.unshift({type:"delete",indexA:s-1,indexB:a}),s--);return{distance:i[n][r],ops:o}}function XW(e,t){let n=[];for(let r=0;r<Math.min(e.length,t.length)&&e[r]===t[r];r++)n.push(e[r]);return n}function QW(e,t){let n=[],r=e.length-1,i=t.length-1;for(;r>=0&&i>=0&&e[r]===t[i];)n.unshift(e[r]),r--,i--;return n}function ZI(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function $t(e){let t=ZW(e.profile?.name),n=()=>{let r=e.candidates(),i=e.filterCandidate?r.filter(e.filterCandidate):r,o=e.orderCandidates?[...i].sort(e.orderCandidates):i,s=fe(o,e.scanLimit);t={pipeline:e.profile?.name,loadedCandidates:r.length,filteredCandidates:i.length,scannedCandidates:s.length,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:s.length<i.length,resultLimitApplied:!1};let a=e.prepare?.(s)??void 0,c=[];for(let u of s){t.evaluatedCandidates+=1;let d=e.evaluate(u,a);d&&c.push(d)}t.matchedResults=c.length,e.orderResults&&c.sort(e.orderResults);let l=typeof e.limit=="number"?c.slice(0,e.limit):c;return t.emittedResults=l.length,t.resultLimitApplied=l.length<c.length,e.onProfile?.({...t}),l};return e.profile?D(`candidate-pipeline:${e.profile.name}`,n,()=>({...eK(e.profile?.metadata),...t})):n()}function ZW(e){return{pipeline:e,loadedCandidates:0,filteredCandidates:0,scannedCandidates:0,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:!1,resultLimitApplied:!1}}function eK(e){return typeof e=="function"?e():e??{}}function qs(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new F(e);return $t({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:r,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,profile:{name:"extract-candidates"},prepare:c=>a.calleeMap(c,{semantic:t.semantic!==!1}),evaluate:(c,l)=>tK(c,l.get(c.symbolId)??[],i),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function tK(e,t,n){let r=new Set(t.map(l=>l.symbol));if(r.size<n)return null;let i=sK(r,t),o=aK(r,i);if(o.length<2)return null;let s=cK(o,i);if(s.length===0)return null;let a=E(e.symbol),c=nK(a,r.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:j(e),totalCallees:r.size,extractionKind:c.extractionKind,actionTier:"signal",evidenceReasons:c.evidenceReasons,recommendation:c.recommendation,clusters:s}}function nK(e,t,n,r){let i=Math.max(...r.map(c=>c.callees.length)),o=Math.max(...r.map(c=>c.isolation)),s=[`${t} distinct callees across ${n} co-occurrence cluster(s)`,`${r.length} extractable cluster(s) passed size and isolation thresholds`,`largest extractable cluster has ${i} callees at ${Math.round(o*100)}% isolation`],a=rK(e,t,n);return a!==null?{extractionKind:"workflow-orchestration",evidenceReasons:[...s,a],recommendation:"Review the isolated helper group as a possible private or feature-local helper, but keep the orchestration sequence together when it preserves the workflow."}:i>=6?{extractionKind:"broad-helper-cluster",evidenceReasons:[...s,"one isolated helper group is broad enough to deserve a named review"],recommendation:"Review whether the broad helper cluster has a stable concept name before extracting it; avoid creating a bag-of-helpers abstraction."}:{extractionKind:"cohesive-helper-cluster",evidenceReasons:s,recommendation:"Review the isolated callee group as a possible same-file or feature-local helper; extract only if the new name preserves the current behavior."}}function rK(e,t,n){if(t>=10)return`callee breadth suggests orchestration: ${t} callees`;if(n>=4)return`multiple disconnected callee groups suggest orchestration: ${n} groups`;let r=iK(e);return oK.has(r)?`caller verb suggests orchestration: ${r}`:null}function iK(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 oK=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function sK(e,t){let n=new Map;for(let i of e)n.set(i,new Set);let r=new Map;for(let i of t){let o=r.get(i.chunkId);o||(o=new Set,r.set(i.chunkId,o)),o.add(i.symbol)}for(let i of r.values()){let o=[...i];for(let s=0;s<o.length;s++)for(let a=s+1;a<o.length;a++)n.get(o[s]).add(o[a]),n.get(o[a]).add(o[s])}return n}function aK(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let o=new Set,s=[i];for(;s.length>0;){let a=s.pop();if(!n.has(a)){n.add(a),o.add(a);for(let c of t.get(a)??[])n.has(c)||s.push(c)}}r.push(o)}return r}function cK(e,t){return e.filter(n=>n.size>=3).map(n=>lK(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function lK(e,t,n){let r=new Set;for(let a of t)if(a!==e)for(let c of a)r.add(c);let i=0;for(let a of e)for(let c of n.get(a)??[])r.has(c)&&i++;let o=e.size*r.size,s=o>0?1-i/o:1;return{callees:[...e].map(E),isolation:s}}import{posix as so}from"path";import{spawnSync as uK}from"child_process";import{createHash as dK}from"crypto";import{existsSync as mK}from"fs";import{dirname as tw,join as fK}from"path";import{fileURLToPath as pK}from"url";var iw=$("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),nw=me({kind:"consumer-file-usage",invalidation:re("consumer-file-usage"),serialize:IK,deserialize:wK});function Bn(e,t){return{forDefinitions(n,r){return gK(e,t,n,r)}}}function jn(e){let t=new Map;for(let[n,r]of e)t.set(n,new Set(r.files.map(i=>i.file)));return t}function Fl(e,t,n){return sw(e,t,n).partition}function gK(e,t,n,r){let i=ow(n.length),o=W()?We(e):null,s=o?hK(n,r,o):void 0,a=s?{workIdentity:s,workOutcome:"computed"}:{};return D("consumer-evidence.product",()=>{let c=D("consumer-evidence.provenance",()=>yK(e,t,n,r),()=>({...a,definitions:n.length,semantic:r.semantic,sourceFallback:r.sourceFallback!==!1})),l=new Map;i={...i,...c.counters};let u=bK(n,c.sources);return D("consumer-evidence.classify",()=>{let d=SK(e,n,c.sources,u);for(let m of n){let f=d.get(m.symbolId)??RK();i.realFiles+=f.partition.realConsumers.length,i.reexportOnlyFiles+=f.partition.barrelConsumers,i.importOnlyFiles+=f.partition.importOnlyConsumers,l.set(m.symbolId,{definition:m,files:f.files,...f.partition})}},()=>({...a,...u,realFiles:i.realFiles,reexportOnlyFiles:i.reexportOnlyFiles,importOnlyFiles:i.importOnlyFiles})),l},()=>({...a,...i}))}function hK(e,t,n){let r=dK("sha256").update("consumer-evidence-v1\0").update(n).update("\0").update(t.semantic?"semantic\0":"indexed\0").update(t.sourceFallback===!1?"no-source-fallback":"source-fallback");for(let i of e.map(o=>o.symbol).sort())r.update("\0").update(i);return r.digest("hex").slice(0,24)}function ow(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function yK(e,t,n,r){let i=ow(n.length),o=new Map;return fp(o,i,"indexed",t.crossFileCallerMap(n,{semantic:!1})),r.semantic&&fp(o,i,"semantic",lr(e,n)),r.sourceFallback!==!1&&fp(o,i,"source-fallback",t.sourceFallbackCallerFiles(n)),i.totalFiles=[...o.values()].reduce((s,a)=>s+a.size,0),{sources:o,counters:i}}function bK(e,t){return{definitions:e.length,consumerFiles:[...t.values()].reduce((n,r)=>n+r.size,0),nativeAttempted:!1,nativeUsed:!1,nativeReason:"not-attempted"}}function fp(e,t,n,r){let i=0;for(let[o,s]of r){let a=e.get(o);a||(a=new Map,e.set(o,a));for(let c of s){i++;let l=a.get(c)??new Set;l.add(n),a.set(c,l)}}n==="indexed"?t.indexedFiles+=i:n==="semantic"?t.semanticFiles+=i:t.fallbackFiles+=i}function SK(e,t,n,r){let i=_K(e,t,n,r);return i||xK(e,t,n)}function xK(e,t,n){let r=new Map;for(let i of t){let o=n.get(i.symbolId)??new Map;r.set(i.symbolId,sw(e,i,[...o.keys()],o))}return r}function sw(e,t,n,r=new Map){let i=[],o=0,s=0,a=T(t.symbol),c=[];for(let l of n){let u;EK(e,l,t.relativePath,a)?(o++,u="reexport-only"):pp(e,l,a)?(s++,u="import-only"):(i.push(l),u="real"),c.push({file:l,sources:[...r.get(l)??[]],classification:u})}return{partition:{realConsumers:i,barrelConsumers:o,importOnlyConsumers:s},files:c}}function RK(){return{partition:{realConsumers:[],barrelConsumers:0,importOnlyConsumers:0},files:[]}}function pp(e,t,n){if(!n)return!1;let r=N(t);if(!r)return!1;let i=iw.get(e,t,()=>aw(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function aw(e,t,n){let r=Lt(e).forFile(t,{text:!0,ast:!0}),i=r.text;if(!i)return vK();let o=he(e,t,i),s=nw.read(e,t,o);if(s)return s;let a=CK(r.ast,n);return nw.write(e,t,o,a),a}function CK(e,t){let n=new Set,r=new Set;if(!e)return{importedLeaves:n,usedLeaves:r};let i=t==="rust"?new Set(["use_declaration"]):t==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),o=(s,a)=>{let c=a||i.has(s.type);(s.type==="identifier"||s.type==="type_identifier"||s.type==="property_identifier"||s.type==="field_identifier")&&(c?n.add(s.text):r.add(s.text));for(let l of s.children)o(l,c)};return o(e.rootNode,!1),{importedLeaves:n,usedLeaves:r}}function vK(){return{importedLeaves:new Set,usedLeaves:new Set}}function IK(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function wK(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 EK(e,t,n,r){if(!r)return!1;let i=Lt(e).forFile(t,{lines:!0,reexports:!0}),o=i.lines??[];if(o.length===0)return!1;let s=i.reexports??[];return cw(o,s,r)}function cw(e,t,n){if(e.length===0||t.length===0)return!1;let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\b${r}\\b`),o=0;for(let s=0;s<e.length;s++){if(!i.test(e[s]??""))continue;if(o++,!t.find(c=>c.startLine<=s&&s<=c.endLine))return!1}return o>0}var DK="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY",PK="SCIP_QUERY_NATIVE_KERNELS_BIN",kK="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY_MIN_FILES",rw=1e3,TK=5e3,FK=64*1024*1024,Tl;function _K(e,t,n,r){let i=process.env[DK]?.toLowerCase();if(i!=="1"&&i!=="true")return r.nativeReason=i==="0"||i==="false"?"disabled":"opt-in-required",null;if(r.consumerFiles<jK())return r.nativeReason="below-threshold",null;let o=$K();if(!o)return r.nativeReason="binary-missing",null;r.nativeAttempted=!0;let s=AK(e,t,n),a=uK(o,["consumer-classify"],{input:JSON.stringify(s),encoding:"utf8",timeout:TK,maxBuffer:FK});if(a.status!==0||a.error)return r.nativeReason=a.error?`spawn-error:${a.error.message}`:`exit-${a.status??"null"}`,null;try{let c=JSON.parse(a.stdout),l=MK(c,t);return l?(r.nativeUsed=!0,r.nativeReason="used",l):(r.nativeReason="invalid-response",null)}catch{return r.nativeReason="invalid-json",null}}function AK(e,t,n){let r=new Map,i=[];for(let a of t){let c=T(a.symbol),u=[...(n.get(a.symbolId)??new Map).entries()].map(([d,m])=>{let f=r.get(d)??new Set;return c&&f.add(c),r.set(d,f),{file:d,sources:[...m]}});i.push({symbol_id:a.symbolId,leaf:c,consumer_files:u})}let o={},s={};for(let[a,c]of r){let l=N(a);if(l){let d=iw.get(e,a,()=>aw(e,a,l));o[a]={imported_leaves:[...d.importedLeaves],used_leaves:[...d.usedLeaves]}}let u=LK(e,a,c);u.length>0&&(s[a]=u)}return{definitions:i,file_usages:o,reexport_only_leaves:s}}function LK(e,t,n){if(n.size===0)return[];let r=Lt(e).forFile(t,{lines:!0,reexports:!0}),i=r.lines??[],o=r.reexports??[];return i.length===0||o.length===0?[]:[...n].filter(s=>cw(i,o,s))}function MK(e,t){if(!Array.isArray(e.entries)||e.entries.length!==t.length)return null;let n=new Set(t.map(i=>i.symbolId)),r=new Map;for(let i of e.entries){let o=NK(i);if(!o||!n.has(o.symbol_id))return null;r.set(o.symbol_id,{partition:{realConsumers:o.real_consumers,barrelConsumers:o.barrel_consumers,importOnlyConsumers:o.import_only_consumers},files:o.files})}for(let i of n)if(!r.has(i))return null;return r}function NK(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.symbol_id!="number"||!Array.isArray(t.real_consumers)||typeof t.barrel_consumers!="number"||typeof t.import_only_consumers!="number"||!Array.isArray(t.files)||!t.real_consumers.every(r=>typeof r=="string"))return null;let n=[];for(let r of t.files){if(!r||typeof r!="object")return null;let i=r;if(typeof i.file!="string"||!Array.isArray(i.sources)||!i.sources.every(OK)||!BK(i.classification))return null;n.push({file:i.file,sources:i.sources,classification:i.classification})}return{symbol_id:t.symbol_id,real_consumers:t.real_consumers,barrel_consumers:t.barrel_consumers,import_only_consumers:t.import_only_consumers,files:n}}function OK(e){return e==="indexed"||e==="semantic"||e==="source-fallback"}function BK(e){return e==="real"||e==="reexport-only"||e==="import-only"}function jK(){let e=process.env[kK];if(!e)return rw;let t=Number(e);return Number.isFinite(t)&&t>=0?t:rw}function $K(){if(Tl!==void 0)return Tl;let e=process.env[PK],t=process.platform==="win32"?"scip-query-kernels.exe":"scip-query-kernels";return Tl=[...e?[e]:[],...HK().map(r=>fK(r,"target","release",t))].find(r=>mK(r))??null,Tl}function HK(){let e=new Set,t=tw(pK(import.meta.url));for(let n=0;n<5;n++)e.add(t),t=tw(t);return[...e]}var GK=20,qK=1,UK=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"]]),VK=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),zK=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 WK(e,t={}){let n=yp(t.limit,GK),r=yp(t.minConsumers,qK),i=new F(e),o=i.fileDependencyGraph(t.scope),s=f2(L(e,{includeIgnored:!1})),a=h2(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?KK(e,i,t.target):JK(e,t.scope,t.scanLimit)).map(u=>YK(e,i,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=r||t.target).sort(m2).slice(0,n)}function KK(e,t,n){let r=ZK(e,n);if(r)return[fw(r)];let i=G(e,n);if(!i)return[];let o=t.definitionsForFile(i.relativePath).find(s=>s.symbolId===i.symbolId);return o?[e2(o)]:[{unit:{kind:"symbol",file:i.relativePath,shortName:E(i.symbol),symbol:i.symbol,startLine:i.startLine,endLine:i.endLine}}]}function JK(e,t,n){let r=L(e,{scope:t,includeIgnored:!1}),i=yp(n,r.length);return r.slice(0,i).map(o=>fw(o))}function YK(e,t,n,r,i,o,s){let a=r.definition?XK(e,t,r.definition,i.semantic):QK(n,r.unit.file),c=r.definition?a.length>0?"exact":"none":a.length>0?"file-level":"none",l=r.unit.file,u=Kt(so.dirname(l)),d=n2(a),m=t2(u),f=Sp([...lw(u),...d?lw(d):[]]),p=r2(r.unit,u,d,a),g=i2(p,r.unit,u,d,a,o,s),y=l2(r.unit,c,d,a,u,g.whyNoSuggestedHome),h=u2(r.unit,u,d,a,g.suggestedHome,g.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:r.unit,candidatePath:l,currentDirectory:u,directoryAncestry:m,consumerFiles:a,consumerCoverage:c,nearestCommonOwner:d,boundaryMarkers:f,recommendedTier:p,suggestedHome:g.suggestedHome,destinationConfidence:g.confidence,whyNoSuggestedHome:g.whyNoSuggestedHome,counterevidence:y,reasons:h,recommendation:d2(p,g.suggestedHome,c)}}function XK(e,t,n,r){let i=jn(Bn(e,t).forDefinitions([n],{semantic:r!==!1,sourceFallback:!0}));return bw(i.get(n.symbolId)??[])}function QK(e,t){let n=[];for(let[r,i]of e.entries())r!==t&&i.has(t)&&n.push(r);return bw(n)}function ZK(e,t){let n=yn(t),r=L(e,{includeIgnored:!1}),i=r.find(s=>s===n);if(i)return i;let o=r.find(s=>s.endsWith(`/${n}`));return o||(r.find(s=>s.includes(n))??null)}function e2(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:E(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function fw(e){return{unit:{kind:"file",file:e,shortName:so.basename(e)}}}function t2(e){if(e===".")return[{path:".",depth:0,markers:[]}];let t=[],n=e.split("/").filter(Boolean);for(let r=0;r<n.length;r+=1){let i=n.slice(0,r+1).join("/");t.push({path:i,depth:r,markers:bp(i)})}return t}function lw(e){return e==="."?[]:pw(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function bp(e){return Sp(pw(e).map(({marker:t})=>t))}function pw(e){let t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){let i=UK.get(t[r]);i&&n.push({marker:i,prefix:t.slice(0,r+1).join("/")})}return n}function n2(e){if(e.length===0)return null;let t=e.map(r=>Kt(so.dirname(r))),n=t[0].split("/").filter(Boolean);for(let r of t.slice(1)){let i=r.split("/").filter(Boolean),o=[],s=Math.min(n.length,i.length);for(let a=0;a<s&&n[a]===i[a];a+=1)o.push(n[a]);n=o}return n.length===0?".":n.join("/")}function r2(e,t,n,r){return n?e.kind==="symbol"&&r.length===1?r[0]===e.file?"same-file":"sibling-folder":n==="."||n==="src"?"repository-level-review":dw(n,"package")?"package-level-shared":dw(n,"app")?"app-level-shared":mw(n,["feature","domain","module"])||mw(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function i2(e,t,n,r,i,o,s){let a=o2(e,r);if(a)return Sr(a);let c=p2(t.file),l=s2(e,n,c,i,s);if(l)return l;let u=r;if(Kt(n)===Kt(u))return Sr(`${n} is already the nearest common owner for its consumers.`);let d=a2(u,n,c,s);return d||c2(u,n,c,o,s)}function o2(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 s2(e,t,n,r,i){if(e==="same-file"){let o=r[0]??null;return o?gp(o):Sr("No same-file consumer path was available.")}if(e==="sibling-folder"&&r.length===1){let o=Kt(so.dirname(r[0])),s=yw(t,n,o,i);return s?Sr(s):gp(o)}return null}function a2(e,t,n,r){return b2(e)?gw(e,t,n,r,`Nearest shared owner ${e} is outside source root ${n}.`):null}function c2(e,t,n,r,i){if(e===".")return Sr("The nearest common owner is the repository root.");let o=`${e}/shared`,s=gw(o,t,n,i,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||r.has(o)?s:Sr(`${o} does not exist in the indexed project.`)}function gw(e,t,n,r,i){if(!hw(e,n))return Sr(i);let o=yw(t,n,e,r);return o?Sr(o):gp(e)}function gp(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function Sr(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function l2(e,t,n,r,i,o){let s=["Report-only signal; review ownership before moving files."];return t==="none"&&s.push("No consumers were found in the current index."),t==="file-level"&&s.push("File-level import evidence can hide which exported unit is actually used."),(n==="."||n==="src")&&s.push("Nearest common owner is broad, so this is not enough evidence for automatic placement."),r.length===1&&s.push("Only one consumer was found; inlining or same-folder placement may be better than shared extraction."),e.kind==="file"&&s.push("File targets describe module locality, not symbol-level usage."),n&&i.startsWith(`${n}/`)&&s.push("Candidate already lives under the nearest common owner."),o&&s.push(`No exact suggested home: ${o}`),s}function u2(e,t,n,r,i,o){let s=[];return s.push(`${e.shortName} currently lives in ${t}.`),n?s.push(`${r.length} consumer file(s) share ${n} as their nearest common owner.`):s.push("No consumer owner could be inferred from the current index."),i?s.push(`Suggested home is ${i}.`):o&&s.push(`No exact suggested home: ${o}`),s}function d2(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 m2(e,t){return uw(t)-uw(e)||e.candidatePath.localeCompare(t.candidatePath)}function uw(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 f2(e){let t=new Set(["."]);for(let n of e){let r=Kt(so.dirname(n));for(;!t.has(r)&&(t.add(r),r!==".");)r=Kt(so.dirname(r))}return t}function p2(e){let t=hp(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function hw(e,t){let n=Kt(e),r=Kt(t);return r==="."||n===r||n.startsWith(`${r}/`)}function g2(e,t,n){let r=hp(e),i=hp(t);return(hw(e,t)?r.slice(i.length):r).some(s=>n.has(s.toLowerCase()))}function yw(e,t,n,r){return Kt(e)===Kt(n)||!g2(e,t,r)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function h2(...e){let t=new Set(zK);for(let n of e)for(let r of n??[]){let i=y2(r);i&&t.add(i)}return t}function y2(e){let t=e.trim().toLowerCase();return t===""?null:t}function dw(e,t){return bp(e).includes(t)}function mw(e,t){let n=bp(e);return t.some(r=>n.includes(r))}function b2(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?VK.has(n):!1}function Kt(e){let t=yn(e);return t===""?".":t}function hp(e){let t=yn(e);return t==="."?[]:t.split("/").filter(Boolean)}function yp(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function bw(e){return Sp([...e]).sort((t,n)=>t.localeCompare(n))}function Sp(e){return[...new Set(e)]}function xp(e,t,n={}){let{maxDepth:r=5,scope:i}=n,o=G(e,t);if(!o)return[];let s=[],a=new Set([o.symbolId]),c=new Set,l=[o];for(let u=1;u<=r&&l.length!==0;u++){let d=[],m=_s(e,l,{limit:500,semanticEvidence:q});for(let f of l)for(let p of S2(e,f,i,m.get(f.symbolId)??[])){let g=`${p.file}|${p.shortName}`;if(p.symbolId!==null){if(a.has(p.symbolId))continue;a.add(p.symbolId)}else if(c.has(g))continue;c.add(g),s.push({symbol:p.symbol,shortName:p.shortName,file:p.file,depth:u}),p.symbolId!==null&&p.symbolMatch&&d.push(p.symbolMatch)}l=d}return s.sort((u,d)=>u.depth-d.depth||u.file.localeCompare(d.file)),s}function S2(e,t,n,r){let i=r.filter(u=>!e.isIgnored(u.file)).filter(u=>!n||u.file.includes(n)),o=new Set(i.map(u=>u.file)),s=[];for(let u of x2(e,t,n)){if(o.has(u))continue;let d=ie(e,u),m=d.length>0?tn(d,d[0].startLine):null;s.push({symbol:m?.symbol??u,file:u})}let a=[...i,...s],c=[],l=new Set;for(let u of a){let d=No(e,u.symbol);if(!d){let f=`${u.file}|${u.symbol}`;if(l.has(f))continue;l.add(f),c.push({symbolId:null,symbol:u.symbol,shortName:E(u.symbol),file:u.file,symbolMatch:null});continue}if(d.symbolId===t.symbolId||e.isIgnored(d.relativePath)||!R2(d))continue;let m=`${d.symbolId}|${d.relativePath}`;l.has(m)||(l.add(m),c.push({symbolId:d.symbolId,symbol:d.symbol,shortName:E(d.symbol),file:d.relativePath,symbolMatch:d}))}return c}function x2(e,t,n){let r=n?"AND consumer_d.relative_path LIKE ?":"",i=[t.symbolId,t.documentId];return n&&i.push(`%${n}%`),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
|
|
727
|
+
FROM mentions m
|
|
728
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
729
|
+
JOIN documents consumer_d ON consumer_d.id = c.document_id
|
|
730
|
+
WHERE m.symbol_id = ?
|
|
731
|
+
AND m.role != 1
|
|
732
|
+
AND c.document_id != ?
|
|
733
|
+
${e.pathExclusionsFor("consumer_d")}
|
|
734
|
+
${r}`,...i).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function R2(e){if(e.symbol.startsWith("scip-clojure ")||N(e.relativePath)==="clojure")return!0;let t=be(e.symbol);return t==="method"||t==="type"||e.symbol.endsWith("().")}function xw(e,t){let n=te(t),r=[],i="complete",o=U(n);o==="entry"&&$n(r,"operational-root","structural entrypoint path"),o==="worker"&&$n(r,"operational-root","worker launch convention"),Uf(n)&&$n(r,"operational-root","framework-discovered entrypoint"),C2(e,n)&&$n(r,"operational-root","configured entry root");let s=!1;try{s=Mn(e,n),s&&$n(r,"published-api","package manifest export");for(let a of Cv(e,n))$n(r,"operational-root",a)}catch(a){i="partial",$n(r,"metadata-unavailable",`package metadata unavailable: ${Sw(a)}`)}try{let a=de(e.config.projectRoot,n,{maxBytes:8388608,inputKind:"change-surface source"});v2(a)&&$n(r,"operational-root","module contains a direct-execution process guard")}catch(a){i="partial",$n(r,"metadata-unavailable",we(a)?"indexed source file is unavailable on disk":`source metadata unavailable: ${Sw(a)}`)}return{operationalRoot:r.some(a=>a.kind==="operational-root"),publishedApi:s,coverage:i,reasons:r}}function C2(e,t){let n=e.config.entryRoots;return n?n.files?.some(r=>te(r)===t)?!0:n.pathPrefixes?.some(r=>t.startsWith(te(r)))??!1:!1}function v2(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 $n(e,t,n){e.some(r=>r.kind===t&&r.detail===n)||e.push({kind:t,detail:n})}function Sw(e){return e instanceof Error?e.message:String(e)}function Rp(e,t,n={}){let r=it(e,t);if(!r)return null;let i=I2(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=0,a=w2(e,i.relative_path),c=xw(e,i.relative_path),l=n.semantic===!1?new Map:lr(e,a);for(let u of a){let d=E2(e,i,u,l.get(u.symbolId)??new Set);s+=d;let m=D2(d),f=[...c.reasons,...d>0?[{kind:"external-consumers",detail:`${d} external consumer${d===1?"":"s"}`}]:[]];o.push({symbol:u.symbol,shortName:E(u.symbol),startLine:u.startLine,endLine:u.endLine,externalConsumers:d,externalConsumerRiskLevel:m,riskLevel:P2(m,c),riskReasons:f})}return{file:i.relative_path,symbols:o,totalExternalConsumers:s,fileRisk:c}}function I2(e,t){return e.get(`SELECT id, relative_path FROM documents
|
|
735
|
+
WHERE relative_path = ?
|
|
736
|
+
${e.pathExclusionsFor("documents")}
|
|
737
|
+
LIMIT 1`,t)??null}function w2(e,t){return new F(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function E2(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
|
|
738
|
+
FROM mentions m
|
|
739
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
740
|
+
JOIN documents consumer_d ON consumer_d.id = c.document_id
|
|
741
|
+
WHERE m.symbol_id = ?
|
|
742
|
+
AND m.role != 1
|
|
743
|
+
AND c.document_id != ?`,n.symbolId,t.id);return new Set([...i.map(o=>o.relative_path),...[...r].filter(o=>o!==t.relative_path)]).size}function D2(e){return e>10?"high":e>0?"medium":"low"}function P2(e,t){return e==="high"?"high":e==="medium"||t.operationalRoot||t.publishedApi||t.coverage==="partial"?"medium":"low"}function k2(e,t={}){let{scope:n,minLoc:r=1,maxDepth:i=5,scanLimit:o}=t,s=new F(e),a=T2(e,n,r,o),c=new Cp;for(let g of a)c.add(g);let l=[],u=[];a.length>0&&l.push(Rw(e,0,a,c));let d=a.map(g=>g.definition).filter(g=>g!==null),m=new Set(a.map(g=>g.symbol));for(let g=1;g<=i&&d.length>0;g++){let y=s.calleeMap(d,{semantic:!1}),h=new Set;for(let b of d)for(let R of y.get(b.symbolId)??[])m.has(R.symbol)||h.add(R.symbol);let S=[];for(let b of h){m.add(b);let R=Cw(e,b);if(!R||e.isIgnored(R.relativePath)||Ue(e,R.relativePath)||Re(e,R.symbol,R.relativePath)||s.fileKind(R.relativePath)==="test"||s.hasSuppressionComment(R))continue;let x=_2(e,R,c);x.removable?S.push(F2(R,"cascade")):x.blockingFiles.length>0&&u.push({shortName:E(R.symbol),file:R.relativePath,blockingFiles:x.blockingFiles.slice(0,3)})}if(S.length===0)break;for(let b of S)c.add(b);l.push(Rw(e,g,S,c)),d=S.map(b=>b.definition).filter(b=>b!==null)}let f=l.reduce((g,y)=>g+y.loc,0),p=l.reduce((g,y)=>g+y.entries.length,0);return{batches:l,totalSymbols:p,totalLoc:f,blocked:u}}function T2(e,t,n,r){let i=ei(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:r,semantic:!1}),o=[];for(let s of i.symbols)s.kind==="dead-code"&&(Ue(e,s.relativePath)||Re(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:Cw(e,s.symbol)}));return o}function F2(e,t){return{symbol:e.symbol,shortName:E(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function Cw(e,t){let n=e.get(`SELECT d.relative_path
|
|
744
|
+
FROM global_symbols gs
|
|
745
|
+
JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
746
|
+
JOIN documents d ON d.id = der.document_id
|
|
747
|
+
WHERE gs.symbol = ?
|
|
748
|
+
LIMIT 1`,t);return n?ie(e,n.relative_path).find(r=>r.symbol===t)??null:null}function _2(e,t,n){let r=Td(e,t);if(r.length===0)return{removable:!1,blockingFiles:[]};let i=new Set;for(let o of r)o.file===t.relativePath&&o.line>=t.startLine&&o.line<=t.endLine||n.contains(o.file,o.line)||i.add(o.file);return{removable:i.size===0,blockingFiles:[...i]}}function Rw(e,t,n,r){let i=[...n].sort((a,c)=>a.file.localeCompare(c.file)||a.startLine-c.startLine),o=new Set(i.map(a=>a.file)),s=[];for(let a of o){let c=ie(e,a);c.length>0&&c.every(l=>r.contains(a,l.startLine))&&s.push(a)}return{depth:t,entries:i.map(({definition:a,...c})=>c),loc:i.reduce((a,c)=>a+c.loc,0),filesEmptied:s.sort()}}var Cp=class{ranges=new Map;add(t){let n=this.ranges.get(t.file)??[];n.push({start:t.startLine,end:t.endLine}),this.ranges.set(t.file,n)}contains(t,n){let r=this.ranges.get(t);return r?r.some(i=>n>=i.start&&n<=i.end):!1}};import{createHash as KE}from"crypto";import{existsSync as Yl}from"fs";import{execFileSync as A2}from"child_process";var Dw=2e3,_l=50,L2=64,M2=8,N2=3,O2=2160*60*60,B2=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,j2=3,$2=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,H2=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function G2(e){let t=z(e,{clearGroups:["whole-project"]});return(n,r,i)=>{let o=i??vp(n.config.projectRoot);if(!o)return null;let s=t.has(n)?t.get(n,()=>({head:"",value:null})):null;return s&&s.head===o?s.value:(t.invalidate(n),t.get(n,()=>({head:o,value:r(n.config.projectRoot,o)})).value)}}function Al(e){let t=z(e,{clearGroups:["whole-project"]});return(n,r,i,o)=>{let s=o??vp(n.config.projectRoot);if(!s)return null;let a=t.has(n)?t.get(n,()=>({head:"",values:new Map})):null;(!a||a.head!==s)&&t.invalidate(n);let c=t.get(n,()=>({head:s,values:new Map}));if(c.values.has(r))return c.values.get(r)??null;let l=i(n.config.projectRoot,s);return c.values.set(r,l),l}}var q2=Al("git-commit-history");function ft(e,t={}){let n=t.historyMode??"bounded",r=t.head;return{capability:i=>U2(e,i,r),commitHistory:()=>Us(e,n,r),fileChurn:()=>W2(e,n,r),changeAmplification:()=>K2(e,n,r),trackedFiles:()=>Y2(e,r),fileAddRecords:()=>Q2(e,n,r),coChangePairs:(i={})=>oJ(e,i,n,r),coChangePairsForFiles:(i,o={})=>kw(e,i,o,n,r),directionalCoChangePairsForFiles:(i,o={})=>sJ(e,i,o,n,r)}}function Us(e,t="bounded",n){return q2(e,ao(t),(r,i)=>V2(r,i,t),n)}function U2(e,t,n){let r=n??vp(e.config.projectRoot);return r?{slot:t,available:!0,head:r}:{slot:t,available:!1,head:null,reason:"git history is unavailable for this project"}}function vp(e){try{return mn(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function mn(e,t){return A2("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"})}function V2(e,t,n){let r;try{r=mn(e,["log","--no-merges","--name-only",...Ll(n),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}return{head:t,...Dp(r,_l)}}function z2(e){return B2.test(e.subject)}function W2(e,t,n){let r=Us(e,t,n);if(!r)return null;let i=new Map;for(let o of r.commits){let s=z2(o);for(let a of o.files){let c=i.get(a)??{changes:0,fixChanges:0,lastChangedAt:0};c.changes+=1,s&&(c.fixChanges+=1),o.timestamp>c.lastChangedAt&&(c.lastChangedAt=o.timestamp),i.set(a,c)}}return i}function K2(e,t,n){let r=Us(e,t,n);if(!r||r.commits.length===0)return null;let i=r.commits.map(o=>o.files.length).filter(o=>o>0).sort((o,s)=>o-s);return i.length===0?null:{medianFilesPerCommit:vw(i,.5),p90FilesPerCommit:vw(i,.9),commitsAnalyzed:i.length}}function vw(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var J2=G2("git-tracked-files");function Y2(e,t){return J2(e,n=>{try{let r=mn(n,["ls-files"]);return new Set(r.split(`
|
|
749
|
+
`).map(i=>i.trim()).filter(i=>i!==""))}catch{return null}},t)}var X2=Al("git-file-adds"),Iw="__git__/file-adds",ww=me({kind:"git-file-adds",invalidation:re("git-file-adds"),serialize:eJ,deserialize:tJ});function Ip(e){return ft(e).fileAddRecords()}function Q2(e,t,n){let r=ao(t);return X2(e,r,(i,o)=>Z2(e,i,o,t),n)}function Z2(e,t,n,r){let i=ww.read(e,Ew(r),n);if(i)return i;let o=nJ(t,r);return o&&ww.write(e,Ew(r),n,o),o}function eJ(e){return JSON.stringify([...e.entries()])}function tJ(e){if(!e)return null;try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=new Map;for(let r of t){if(!Array.isArray(r)||r.length!==2||typeof r[0]!="string")return null;let i=r[1];if(!i||typeof i.commitsAgo!="number"||!Number.isFinite(i.commitsAgo)||typeof i.addedAt!="number"||!Number.isFinite(i.addedAt))return null;n.set(r[0],{commitsAgo:i.commitsAgo,addedAt:i.addedAt})}return n}catch{return null}}function nJ(e,t){let n;try{n=mn(e,["log","--no-merges","--find-renames","--name-status",...Ll(t),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}let r=new Map,i=new Map,o=-1;for(let s of n.split("")){if(s.trim()==="")continue;o+=1;let a=s.indexOf(`
|
|
750
|
+
`),c=a>=0?s.slice(0,a):s,[,l]=c.split("\0"),u=Number(l)||0;if(!(a<0))for(let d of s.slice(a+1).split(`
|
|
751
|
+
`)){let m=rJ(d);if(!m)continue;if(m.status==="R"&&m.from&&m.to){let p=i.get(m.to)??new Set([m.to]);i.set(m.from,p);continue}if(m.status!=="A"||!m.to)continue;let f={commitsAgo:o,addedAt:u};r.set(m.to,f);for(let p of i.get(m.to)??[])r.set(p,f)}}return r}function rJ(e){let t=e.trim().split(" "),n=t[0]??"";if(!n)return null;let r=n[0]??"";if(r==="R"){let o=t[1],s=t[2];return o&&s?{status:r,from:o,to:s}:null}let i=t[1];return i?{status:r,to:i}:null}var Pw=Al("git-co-change-pairs"),iJ=Al("git-directional-co-change-pairs");function oJ(e,t,n,r){let i=`all\0${ao(n)}\0${wp(t)}`,o=Pw(e,i,()=>{let s=Us(e,n,r);return s?Ep(s,t):null},r);return o&&[...o]}function kw(e,t,n,r,i){if(t.size===0)return[];let o=`files\0${ao(r)}\0${Tw(t)}\0${wp(n)}`,s=Pw(e,o,()=>{let a=Us(e,r,i);return a?Ep(a,n,t):null},i);return s&&[...s]}function sJ(e,t,n,r,i){if(t.size===0)return[];let o=n.maxFilesPerCommit??_l;if(t.size>L2)return kw(e,t,n,r,i);let s=`directional\0${ao(r)}\0${Tw(t)}\0${wp({...n,maxFilesPerCommit:o})}`,a=iJ(e,s,(c,l)=>{let u=aJ(c,l,t,o,r);return u?Ep(u,n,t):null},i);return a&&[...a]}function wp(e){let t=e.minTogether??4,n=e.minConfidence??.6,r=e.maxFilesPerCommit??_l;return`${t}\0${n}\0${r}`}function Tw(e){return[...e].sort().join("\0")}function Ep(e,t,n){let{minTogether:r=4,minConfidence:i=.6,maxFilesPerCommit:o=_l}=t,s=new Map,a=new Map,c=e.newestAnalyzedAt??0;for(let d of e.commits){let m=[...new Set(d.files)].sort();if(m.length>o)continue;e.newestAnalyzedAt===void 0&&d.timestamp>c&&(c=d.timestamp);let f=uJ(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 y=g+1;y<m.length;y++){if(n&&!n.has(m[g])&&!n.has(m[y]))continue;let h=`${m[g]}\0${m[y]}`,S=a.get(h)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};S.together+=1,f?S.broadTogether+=1:S.focusedTogether+=1,d.timestamp>S.lastTogetherAt&&(S.lastTogetherAt=d.timestamp),S.timestamps.push(d.timestamp),S.subjects.push(d.subject),a.set(h,S)}}let l=[],u=c-O2;for(let[d,m]of a){let f=m.together;if(f<r)continue;let[p,g]=d.split("\0"),y=s.get(p)??f,h=s.get(g)??f,S=Math.max(f/y,f/h);if(S<i)continue;let b=m.broadTogether/f,R=m.timestamps.filter(x=>x>=u).length;l.push({fileA:p,fileB:g,together:f,confidence:S,changesA:y,changesB:h,focusedTogether:m.focusedTogether,broadTogether:m.broadTogether,broadCommitRatio:b,lastTogetherAt:m.lastTogetherAt,recentTogether:R,commitScope:mJ(m.broadTogether,f),recency:R>0?"recent":"stale",subjectContext:fJ(m.subjects)})}return l.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),l}function aJ(e,t,n,r,i){let o;try{o=cJ(e,i)}catch{return null}if(o.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:0};let s;try{s=mn(e,["log","--no-merges","--format=%H",...Ll(i),"--",...[...n].sort()])}catch{return null}let a=new Set(o.map(m=>m.hash)),c=s.split(`
|
|
752
|
+
`).map(m=>m.trim()).filter(m=>m!==""&&a.has(m)),l=lJ(e,o,r);if(c.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:l};let u;try{u=mn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...c])}catch{return null}let d=Dp(u,r);return{head:t,...d,newestAnalyzedAt:l}}function cJ(e,t){return mn(e,["log","--no-merges","--format=%H%x00%ct",...Ll(t)]).split(`
|
|
753
|
+
`).map(r=>r.trim()).filter(r=>r!=="").map(r=>{let[i,o]=r.split("\0");return{hash:i??"",timestamp:Number(o)||0}}).filter(r=>r.hash!=="")}function Ll(e){return e==="full"?[]:["-n",String(Fw())]}function Fw(){return er(process.env.SCIP_QUERY_GIT_HISTORY_MAX_COMMITS)??Dw}function ao(e){return e==="full"?"full":`bounded:${Fw()}`}function Ew(e){let t=ao(e);return t===`bounded:${Dw}`?Iw:`${Iw}:${t}`}function lJ(e,t,n){for(let i=0;i<t.length;i+=20){let o=t.slice(i,i+20),s;try{s=mn(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...o.map(c=>c.hash)])}catch{return t[0]?.timestamp??0}let a=Dp(s,n);if(a.commits.length>0)return a.commits[0].timestamp}return 0}function Dp(e,t){let n=[],r=0;for(let i of e.split("")){if(i.trim()==="")continue;let o=i.indexOf(`
|
|
754
|
+
`),s=o>=0?i.slice(0,o):i,[a,c,l]=s.split("\0");if(!a||!c)continue;let u=o>=0?i.slice(o+1).split(`
|
|
755
|
+
`).map(d=>d.trim()).filter(d=>d!==""):[];if(u.length>t){r+=1;continue}n.push({hash:a,timestamp:Number(c)||0,subject:l??"",files:u})}return{commits:n,skippedBulkCommits:r}}function uJ(e){return e.length>=M2?!0:dJ(e).size>=N2}function dJ(e){let t=new Set;for(let n of e){let r=n.indexOf("/");t.add(r>=0?n.slice(0,r):".")}return t}function mJ(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function fJ(e){let t=new Set,n=[],r=[];for(let i of e){!r.includes(i)&&r.length<j2&&r.push(i);for(let o of pJ(i))t.add(o);for(let o of i.match($2)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:r,externalIssueLabelStatus:"unavailable"}}function pJ(e){let t=new Set,n=H2.exec(e)?.[1]?.toLowerCase();return n&&t.add(gJ(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 gJ(e){return e==="feat"?"feature":e}function kp(e){return Pp.test(e)}var Pp=/(?:^|\/)(?: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 Vs(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=ft(e,{historyMode:n.historyMode,...n.head?{head:n.head}:{}}),c=a.commitHistory(),l=t!==void 0,u=a.coChangePairs({minTogether:l?Math.min(r,2):r,minConfidence:l?0:i,maxFilesPerCommit:s});if(!c||!u)return{available:!1,commitsAnalyzed:0,findings:[]};let d=typeof n.scanLimit=="number"?u.slice(0,n.scanLimit):u,m=le(e),f=Nw(e),p=_p(e,m,f),g=n.includeLinked===!0||l,y=[];for(let h of d){if(Pp.test(h.fileA)||Pp.test(h.fileB)||!_w(e,h.fileA)||!_w(e,h.fileB)||l&&!h.fileA.includes(t)&&!h.fileB.includes(t)||!l&&(U(h.fileA)==="test"||U(h.fileB)==="test"||SJ(h.fileA,h.fileB)||yJ(h.fileA,h.fileB)))continue;let S=p(h.fileA,h.fileB);if(!g&&S)continue;let b=Tp(h.fileA,h.fileB),R=Fp(h,b,S);if(y.push({...h,structurallyLinked:S,partnerClass:b.partnerClass,partnerClassReasons:b.reasons,...R?{declaredCouplingSuggestion:R}:{}}),y.length>=o)break}return{available:!0,commitsAnalyzed:c.commits.length,findings:y}}function _w(e,t){return st(e.config.projectRoot,t)}function Tp(e,t){let n=Lw(e),r=Lw(t),i=[],o=c=>{i.includes(c)||i.push(c)},s=(c,l)=>n.tags.has(c)&&r.tags.has(l)||n.tags.has(l)&&r.tags.has(c);if(s("doc","code"))return o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:i};if(n.tags.has("test")||r.tags.has("test"))return o("one side is classified as a test file"),{partnerClass:"test-code",reasons:i};if(s("schema","script"))return o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:i};if(s("model","view"))return o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:i};if(s("config","code"))return o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:i};let a=TJ(n.tokens,r.tokens).filter(c=>!PJ.has(c));return Mw(e,t)||a.length>=2?(o(Mw(e,t)?"both files live in the same directory":`files share feature tokens: ${a.slice(0,4).join(", ")}`),{partnerClass:"same-feature",reasons:i}):(o("no specific relationship pattern matched"),{partnerClass:"unknown",reasons:i})}function Fp(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!DJ.has(t.partnerClass))return;let r=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${FJ(r)}`,files:r,reason:`${t.partnerClass} pair changed together ${e.together}x with ${Math.round(e.confidence*100)}% confidence; declare it if future edits should require both sides.`}}function _p(e,t=le(e),n=Nw(e)){return(r,i)=>xJ(t,n,r,i)}var hJ=/(?:^|\/)(?:locales|i18n)\//i;function Aw(e){return hJ.test(e)}function yJ(e,t){return Aw(e)&&Aw(t)?!0:bJ(e,t)}function bJ(e,t){if(!e.endsWith(".json")||!t.endsWith(".json"))return!1;let n=e.lastIndexOf("/"),r=t.lastIndexOf("/");if(n<0||r<0)return!1;let i=e.slice(0,n),o=t.slice(0,r);if(i===o)return!1;let s=e.slice(n+1),a=t.slice(r+1);if(s!==a)return!1;let c=i.lastIndexOf("/"),l=o.lastIndexOf("/"),u=c>=0?i.slice(0,c):"",d=l>=0?o.slice(0,l):"";return u===d}function SJ(e,t){let n=e.lastIndexOf("/"),r=t.lastIndexOf("/");if(e.slice(0,n)!==t.slice(0,r))return!1;let i=e.slice(n+1).split(".")[0],o=t.slice(r+1).split(".")[0];return i!==""&&i===o}function Nw(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function xJ(e,t,n,r){return e.get(n)?.has(r)===!0||e.get(r)?.has(n)===!0?!0:t.some(i=>i.has(n)&&i.has(r))}var RJ=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,CJ=/(?:^|\/)(?:\.[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,vJ=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,IJ=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,wJ=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,EJ=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,DJ=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),PJ=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 Lw(e){let t=e.replace(/\\/g,"/"),n=new Set;return RJ.test(t)&&n.add("doc"),CJ.test(t)&&n.add("config"),vJ.test(t)&&n.add("schema"),IJ.test(t)&&n.add("script"),wJ.test(t)&&n.add("model"),EJ.test(t)&&n.add("view"),U(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:kJ(t)}}function Mw(e,t){let n=e.lastIndexOf("/"),r=t.lastIndexOf("/"),i=n>=0?e.slice(0,n):"",o=r>=0?t.slice(0,r):"";return i!==""&&i===o}function kJ(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 TJ(e,t){let n=new Set(t);return[...new Set(e.filter(r=>n.has(r)))].sort()}function FJ(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}import{execFileSync as co}from"child_process";import{existsSync as _J}from"fs";import{basename as Ow}from"path";function Ml(e){let t=new Map;for(let n of e){let r=t.get(n.file);r||(r=[],t.set(n.file,r)),r.push(n)}return t}var zs="Unable to compute git diff.",AJ={semanticConsumers:lr,sourceFallbackConsumers:As},Op={resolveCommit:ku,readBatch({projectRoot:e,resolvedBase:t,relativePaths:n}){let r=n.map(i=>`${t}:./${i}
|
|
756
|
+
`).join("");return co("git",["cat-file","--batch"],{cwd:e,input:r,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"]})}};function lo(e,t={}){let n=t.plan??xr(e,t);return n.note?LJ(n.note,n.changedFileLines):n.changedFiles.length===0?MJ(n.changedFileLines):Nl(n.changedFiles,[Hw(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function xr(e,t={}){let{base:n="HEAD"}=t;try{let r=ku(e.config.projectRoot,n),i=NJ(e.config.projectRoot,r),o=i.changedFileLines,s=GJ(e,o),a=qJ(e,i.changedRanges);return{changedFileLines:o,changedFiles:s,changedRanges:a,renamedFiles:jJ(e.config.projectRoot,r,s,i),note:o.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:zs}}}function Hw(e,t,n,r=[],i={}){let o=i.evidenceRuntime??AJ,s=new F(e),a=new Set(n),c=Ml(r),l=[],u=new Map,d=t.flatMap(w=>s.definitionsForFile(w)).filter(oY),m=d.filter(w=>VJ(w,c)),f=WJ(e,d,m,c),p=YJ([...m,...f.definitions]).sort((w,I)=>w.relativePath.localeCompare(I.relativePath)||w.startLine-I.startLine),g=p.map(w=>w.symbolId),y=nY(e,g),h=rY(e,g,n),S=p.filter(w=>(y.get(w.symbolId)??0)===0),b=$w("semantic-consumers",S.length,()=>o.semanticConsumers(e,S)),R=b.values,x=S.filter(w=>(R.get(w.symbolId)?.size??0)===0),v=$w("source-fallback-consumers",x.length,()=>o.sourceFallbackConsumers(e,x)),C=v.values;for(let w of p)ZJ(e,w,a,l,u,R.get(w.symbolId)??new Set,C.get(w.symbolId)??new Set,y.get(w.symbolId)??0,h.get(w.symbolId)??new Set);return{changedSymbols:l,consumerEntries:[...u.entries()].map(([w,I])=>({file:w,symbols:[...I].sort()})),attributionNotes:f.notes,evidenceTiers:[b.status,v.status]}}function Nl(e,t){let n=new Map,r=t.flatMap(a=>a.changedSymbols),i=t.flatMap(a=>a.attributionNotes??[]),o=eY(t);for(let a of t)for(let c of a.consumerEntries){let l=n.get(c.file);l||(l=new Set,n.set(c.file,l));for(let u of c.symbols)l.add(u)}let s=iY(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:s,attributionNotes:i,evidenceTiers:o,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:s.length}}}function LJ(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:Ww(),summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function MJ(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:Ww(),summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function NJ(e,t){let n=co("git",["diff","--name-status","--find-renames",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864}),r=co("git",["diff","--name-status","--find-renames","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),i=co("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),o=co("git",["diff","--unified=0",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),s=co("git",["diff","--unified=0","--cached",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),a=$J([n,r]);return{changedFileLines:[...new Set([...a.changedFiles,...qw(i)])],changedRanges:Vw([...jw(o),...jw(s)]),renamedFiles:a.renamedFiles,deletedFiles:a.deletedFiles}}function OJ(e,t,n){let r=typeof e=="string"?{projectRoot:e,base:t,relativePath:n}:e;if(typeof r.projectRoot!="string"||typeof r.base!="string"||typeof r.relativePath!="string")throw new TypeError("fileContentAtBase requires projectRoot, base, and relativePath.");let i={projectRoot:r.projectRoot,base:r.base,relativePath:r.relativePath},{relativePath:o}=i,s=Bp(i);if(s.state==="unavailable")throw new Error(`Base content unavailable for ${o}: ${s.reason}`);return s.state==="present"?s.content:null}function Bp(e,t=Op){return Gw(e.relativePath),jp({projectRoot:e.projectRoot,base:e.base,relativePaths:[e.relativePath]},t).get(e.relativePath)??{state:"unavailable",reason:`Base-content lookup omitted ${e.relativePath}.`}}function jp(e,t=Op){for(let s of e.relativePaths)Gw(s);let n=[...new Set(e.relativePaths)];if(n.length===0)return new Map;let r;try{r=t.resolveCommit(e.projectRoot,e.base)}catch(s){return Ap(n,Lp(s))}let i;try{i=t.readBatch({projectRoot:e.projectRoot,resolvedBase:r,relativePaths:n})}catch(s){return Ap(n,Lp(s))}let o;try{o=BJ(i,n)}catch(s){return Ap(n,`Malformed git cat-file batch output: ${Lp(s)}`)}return new Map(n.map(s=>{let a=o.get(s)??null;return[s,a===null?{state:"absent"}:{state:"present",content:a}]}))}function uo(e,t=Op){let n=jp({projectRoot:e.projectRoot,base:e.base,relativePaths:e.preloadPaths??[]},t);return r=>(n.has(r)||n.set(r,Bp({projectRoot:e.projectRoot,base:e.base,relativePath:r},t)),n.get(r)??{state:"unavailable",reason:`Base-content reader omitted ${r}.`})}function Ws(e,t=e.changedFiles){let n=new Map(e.renamedFiles.map(r=>[r.to,r.from]));return[...new Set(t.map(r=>n.get(r)??r))]}function Gw(e){ht(e)}function Ap(e,t){return new Map(e.map(n=>[n,{state:"unavailable",reason:t}]))}function Lp(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 BJ(e,t){let n=new Map,r=0;for(let i of t){let o=e.indexOf(10,r);if(o<0)throw new Error("git cat-file batch output ended before object header");let s=e.subarray(r,o).toString("utf-8");if(r=o+1,s.endsWith(" missing")){n.set(i,null);continue}let a=/^[0-9a-f]+ ([^ ]+) (\d+)$/.exec(s);if(!a)throw new Error(`unexpected git cat-file batch header: ${s}`);let[,c,l]=a,u=Number(l);if(!Number.isFinite(u)||u<0)throw new Error(`unexpected git cat-file batch size: ${s}`);if(r+u>e.length)throw new Error("git cat-file batch output ended before blob payload");let d=e.subarray(r,r+u);n.set(i,c==="blob"?d.toString("utf-8"):null),r+=u,e[r]===10&&(r+=1)}return n}function jJ(e,t,n,r){if(n.length===0)return[];let i=new Map,o=new Set;for(let a of r.renamedFiles)n.includes(a.to)&&(i.set(a.to,a),o.add(a.from));let s=r.deletedFiles;if(s.length===0)return[...i.values()].sort((a,c)=>a.to.localeCompare(c.to));for(let a of n){if(i.has(a)||!_J(`${e}/${a}`))continue;let c=s.filter(d=>!o.has(d)).filter(d=>Ow(d)===Ow(a));if(c.length===0)continue;let l=de(e,a),u=c.map(d=>({from:d,to:a,similarity:HJ(OJ({projectRoot:e,base:t,relativePath:d})??"",l)})).sort((d,m)=>m.similarity-d.similarity)[0];u&&u.similarity>=.45&&(i.set(a,u),o.add(u.from))}return[...i.values()].sort((a,c)=>a.to.localeCompare(c.to))}function $J(e){let t=new Set,n=new Map,r=new Set;for(let i of e.flatMap(o=>qw(o))){let[o,s,a]=i.split(" ");if(!(!o||!s)){if(o.startsWith("R")&&a){t.add(a),n.set(a,{from:s,to:a,similarity:Number(o.slice(1))/100});continue}t.add(s),o.startsWith("D")&&r.add(s)}}return{changedFiles:[...t],renamedFiles:[...n.values()],deletedFiles:[...r]}}function HJ(e,t){let n=new Set(Bw(e)),r=new Set(Bw(t));if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let i=0;for(let o of n)r.has(o)&&(i+=1);return 2*i/(n.size+r.size)}function Bw(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function qw(e){return e.split(`
|
|
757
|
+
`).map(t=>t.trim()).filter(t=>t.length>0)}function GJ(e,t){let n=Uw(e),r=[];for(let i of t){let o=n(i);o&&!e.isIgnored(o)&&r.push(o)}return r}function qJ(e,t){let n=Uw(e),r=[];for(let i of t){let o=n(i.file);o&&!e.isIgnored(o)&&r.push({...i,file:o})}return Vw(r)}function Uw(e){let t=e.all(`SELECT relative_path FROM documents
|
|
758
|
+
ORDER BY id`).map(r=>r.relative_path),n=new Map(t.map(r=>[r,r]));return r=>{let i=r.replace(/\\/g,"/"),o=n.get(i);return o||(t.find(s=>s.endsWith(i))??null)}}function jw(e){let t=[],n=null;for(let r of e.split(`
|
|
759
|
+
`)){if(r.startsWith("+++ ")){n=UJ(r.slice(4).trim());continue}if(!n||!r.startsWith("@@ "))continue;let i=/@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(r);if(!i)continue;let o=Math.max(0,Number(i[1])-1),s=i[2]===void 0?1:Number(i[2]);t.push({file:n,startLine:o,endLine:Math.max(o,o+Math.max(s,1)-1)})}return t}function UJ(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function Vw(e){let t=new Set,n=[];for(let r of e){let i=`${r.file}:${r.startLine}:${r.endLine}`;t.has(i)||(t.add(i),n.push(r))}return n}function VJ(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(r=>$p(e.startLine,e.endLine,r.startLine,r.endLine))}function zJ(e,t,n){let r=new Map,i=[],o=zw(e),s=XJ(n);for(let a of t){let c=o.get(a.file)??[];if(c.some(d=>$p(d.startLine,d.endLine,a.startLine,a.endLine)))continue;let l=s.get(a.file)??[],u=QJ(l,a);if(u){let d=c.find(m=>m.startLine>=u.startLine&&m.startLine<=u.endLine);if(d){r.set(d.symbolId,d),i.push(Mp(a,"ast-widened"));continue}}if(l.length===0){let d=[...c].filter(m=>m.startLine<=a.startLine).sort((m,f)=>f.startLine-m.startLine||m.endLine-f.endLine)[0];if(d){r.set(d.symbolId,d),i.push(Mp(a,"nearest-preceding"));continue}}i.push(Mp(a,"unattributed"))}return{definitions:[...r.values()],notes:i}}function WJ(e,t,n,r){let i=zw(n),o=[],s=[],a=[...new Set(t.map(c=>c.relativePath))];for(let c of a){let l=r.get(c)??[];if(l.length===0)continue;let u=i.get(c)??[];for(let d of l)u.some(m=>$p(m.startLine,m.endLine,d.startLine,d.endLine))||o.push(d);o.some(d=>d.file===c)&&s.push(...KJ(e,c))}return zJ(t,o,s)}function KJ(e,t){let n=ne(e,t);return n?n.rootNode.namedChildren.filter(JJ).map(r=>({file:t,startLine:r.startPosition.row,endLine:r.endPosition.row})).filter(r=>r.endLine>=r.startLine):[]}function JJ(e){return e.endPosition.row<e.startPosition.row?!1:!new Set(["import_statement","comment"]).has(e.type)}function YJ(e){let t=new Map;for(let n of e)t.set(n.symbolId,n);return[...t.values()]}function zw(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath)??[];r.push(n),t.set(n.relativePath,r)}return t}function XJ(e){let t=new Map;for(let n of e){let r=t.get(n.file)??[];r.push(n),t.set(n.file,r)}return t}function QJ(e,t){return e.filter(n=>n.startLine<=t.startLine&&n.endLine>=t.endLine).sort((n,r)=>n.endLine-n.startLine-(r.endLine-r.startLine))[0]}function Mp(e,t){return{file:e.file,startLine:e.startLine,endLine:e.endLine,method:t}}function $p(e,t,n,r){return e<=r&&n<=t}function ZJ(e,t,n,r,i,o,s,a,c){let l=Math.max(a,o.size,s.size);if(!sY(t,l))return;let u=E(t.symbol);r.push({symbol:t.symbol,shortName:u,file:t.relativePath,startLine:t.startLine,endLine:t.endLine,fanIn:l});for(let d of c)Np(e,n,i,d,u);for(let d of o)Np(e,n,i,d,u);for(let d of s)Np(e,n,i,d,u)}function $w(e,t,n){try{return{values:n(),status:{tier:e,state:"complete",attemptedSymbols:t}}}catch(r){return{values:new Map,status:{tier:e,state:"failed",attemptedSymbols:t,reason:tY(r)}}}}function eY(e){return["semantic-consumers","source-fallback-consumers"].map(t=>{let n=e.map(o=>o.evidenceTiers?.find(s=>s.tier===t)??{tier:t,state:"failed",attemptedSymbols:0,reason:"isolated diff-impact batch omitted its evidence-tier status"}),r=n.reduce((o,s)=>o+s.attemptedSymbols,0),i=[...new Set(n.filter(o=>o.state==="failed").map(o=>o.reason))];return i.length===0?{tier:t,state:"complete",attemptedSymbols:r}:{tier:t,state:"failed",attemptedSymbols:r,reason:i.join("; ").slice(0,500)}})}function Ww(){return[{tier:"semantic-consumers",state:"complete",attemptedSymbols:0},{tier:"source-fallback-consumers",state:"complete",attemptedSymbols:0}]}function tY(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 nY(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
|
|
760
|
+
FROM mentions m
|
|
761
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
762
|
+
WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
|
|
763
|
+
AND m.role != 1
|
|
764
|
+
GROUP BY m.symbol_id`,...t);return new Map(n.map(r=>[r.symbol_id,r.fan_in]))}function rY(e,t,n){if(t.length===0||n.length===0)return new Map;let r=e.all(`SELECT DISTINCT m.symbol_id, ref_d.relative_path
|
|
765
|
+
FROM mentions m
|
|
766
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
767
|
+
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
768
|
+
WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
|
|
769
|
+
AND m.role != 1
|
|
770
|
+
AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
|
|
771
|
+
${e.pathExclusionsFor("ref_d")}`,...t,...n),i=new Map;for(let o of r){let s=i.get(o.symbol_id);s||(s=new Set,i.set(o.symbol_id,s)),s.add(o.relative_path)}return i}function Np(e,t,n,r,i){if(e.isIgnored(r)||t.has(r))return;let o=n.get(r);o||(o=new Set,n.set(r,o)),o.add(i)}function iY(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function oY(e){return!(Wn(e.symbol)||e.parentTypeName!==null&&!ye(e.symbol))}function sY(e,t){return ye(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}function Hp(e){let[t,n]=mo(e,":"),r=t||"unknown",i=(o={})=>{let s=o.actionTier??aY(r);return{sourceAnalyzer:r,actionTier:s,rootCauseKey:o.rootCauseKey??(n||e),label:o.label??`${r} finding`,relatedFiles:o.relatedFiles??[],why:o.why??[],remediation:o.remediation??cY(s,r),file:o.file}};if(!n)return i({rootCauseKey:e,why:["Baseline identity did not include analyzer payload."]});if(["dead","isolated","extract","wrapper","passthrough","stale"].includes(r)){let[o,s]=mo(n,":");return i({file:o,relatedFiles:o?[o]:[],rootCauseKey:s?`${o}:${s}`:n,label:`${r} finding`,why:s?[`Baseline subject: ${s}.`]:[]})}if(r==="cycle"){let o=n.split(">").filter(Boolean);return i({relatedFiles:o,rootCauseKey:n,label:"cycle finding",why:o.length>0?[`Cycle path: ${o.join(" > ")}.`]:[]})}if(r==="similar"){let o=n.split("|").filter(Boolean);return i({relatedFiles:[],rootCauseKey:n,label:"similarity finding",why:o.length>0?[`Similar symbols: ${o.join(" | ")}.`]:[]})}if(r==="architecture"){let[o,s]=mo(n,":");if(o==="forbidden-edge"){let[a,c]=mo(s,":"),l=Ol(a),u=Ol(c);return i({actionTier:"direct",rootCauseKey:n,label:"architecture boundary violation",why:[`Declared boundary rule rejects ${l} -> ${u}.`],remediation:`Move the dependency behind an allowed boundary, or deliberately update the ${l} dependency rule and baseline.`})}if(o==="cycle"){let a=s.split("|").filter(Boolean).map(Ol);return i({actionTier:"direct",rootCauseKey:n,label:"forbidden architecture cycle",why:[`requireAcyclic rejects the connected boundary group: ${a.join(", ")}.`],remediation:"Break the boundary cycle, or deliberately revise the acyclicity rule and baseline."})}if(o==="missing-policy-row"){let a=Ol(s);return i({actionTier:"direct",rootCauseKey:n,label:"incomplete architecture policy",why:[`requireCompletePolicy rejects the missing outgoing dependency row for ${a}.`],remediation:`Declare the allowed outgoing dependencies for ${a}, including an empty row when it must depend on nothing.`})}}if(r==="drift"){let[o,s]=mo(n,":"),[a,c]=mo(s,":");return i({actionTier:o==="unused-import"?"direct":"signal",file:a,relatedFiles:[...new Set([a,c].filter(Boolean))],rootCauseKey:n,label:`${o||"drift"} finding`,why:[...o?[`Drift kind: ${o}.`]:[],...c?[`Related dependency: ${c}.`]:[]]})}return i({why:["Baseline analyzer prefix is not recognized by this diff-gate version."]})}function aY(e){switch(e){case"dead":case"isolated":case"cycle":case"passthrough":case"architecture":return"direct";case"similar":case"extract":case"wrapper":case"stale":return"signal";default:return"signal"}}function cY(e,t){return e==="direct"?`Fix the new ${t} baseline finding, or knowingly accept it via health --write-baseline.`:`Review the new ${t} baseline signal; fix it if it reflects real debt, or knowingly accept it via health --write-baseline.`}function mo(e,t){let n=e.indexOf(t);return n<0?[e,""]:[e.slice(0,n),e.slice(n+t.length)]}function Ol(e){try{return decodeURIComponent(e)}catch{return e}}function $l(e,t){let n=lY(e,t)??uY(e,t)??dY(e,t)??mY(e,t);return fY(e,n,t)}function lY(e,t){let n=-1,r=null;for(let i=0;i<=t;i+=1){let o=Gp(e[i]??"");o&&(r===null?(r=o,n=i):o===r&&(r=null,n=-1))}if(r===null||n<0)return null;for(let i=t+1;i<e.length;i+=1)if(Gp(e[i]??"")===r)return{start:n,end:i+1};return{start:n,end:e.length}}function Gp(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function uY(e,t){if(!Bl(e[t]??""))return null;let n=t;for(;n>0&&Bl(e[n-1]??"");)n-=1;let r=t+1;for(;r<e.length&&Bl(e[r]??"");)r+=1;return{start:n,end:r}}function Bl(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function dY(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if(jl(o)!==null)break;if(qp(o)!==null)return null;n-=1}if(n<0)return null;let r=jl(e[n]??"");if(r===null)return null;let i=n+1;for(;i<e.length;){let o=e[i]??"",s=jl(o);if(s!==null){if(s<=r)break;i+=1;continue}if(qp(o)!==null)break;i+=1}return{start:n,end:i}}function jl(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function mY(e,t){let n=e[t]??"";if(Jw(n)||n.trim().length===0)return{start:t,end:t+1};let r=t;for(;r>0&&Kw(e[r-1]??"");)r-=1;let i=t+1;for(;i<e.length&&Kw(e[i]??"");)i+=1;return{start:r,end:i}}function Kw(e){return qp(e)===null}function qp(e){return e.trim().length===0?"blank":Jw(e)?"heading":Gp(e)?"fence":Bl(e)?"table":jl(e)!==null?"list":null}function Jw(e){return/^#{1,6}\s+/.test(e.trim())}function fY(e,t,n){let{start:r,end:i}=t;if(i-r>40){let s=Math.floor(20);r=Math.max(r,n-s),i=Math.min(i,r+40),r=Math.max(t.start,i-40)}let o=e.slice(r,i).join(`
|
|
772
|
+
`).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function ni(e,t){return t.filter(n=>e.includes(n))}var pY=/<!--\s*scip-query:\s*snapshot\s*-->/i;function Hl(e,t){if((e.config.docs?.snapshotPaths??[]).some(i=>gr(i,t)))return!0;let r=k(e,t);return r.length>0&&pY.test(r)}var Hn={classifyCitation:hY,citationContexts:yY,citationKindLabel:SY,citationRemediation:xY,referenceTargets:RY,hasLineAnchoredCitation:gY};function gY(e){return e.some(t=>(t.lineReferences?.length??0)>0)}function hY(e){let t=e.join(`
|
|
773
|
+
`).toLowerCase(),n=[],r=ni(t,[".scipquery","declaredcouplings","suppression","suppressions","config","configuration","json"]);if(r.length>0)return n.push(`configuration/example terms near citation: ${r.join(", ")}`),{citationKind:"configuration-example",actionTier:"support",reasons:n};let i=ni(t,["accepted","intentional","intentionally","retained","historical"]);if(i.length>0)return n.push(`intentional-record terms near citation: ${i.join(", ")}`),{citationKind:"intentional-record",actionTier:"support",reasons:n};let o=ni(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 yY(e,t,n){let r=k(e,t);if(!r&&!st(e.config.projectRoot,t))return[];let i=r.split(/\r?\n/),o=n.flatMap(bY),s=[];for(let a=0;a<i.length;a+=1){let c=i[a]??"";o.some(l=>c.includes(l))&&s.push($l(i,a))}return s}function bY(e){let t=e.split("/");return[e,`./${e}`,t.slice(-3).join("/"),t.slice(-2).join("/")].filter((n,r,i)=>n.length>0&&i.indexOf(n)===r)}function SY(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 xY(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 RY(e,t,n){let r=Ml(n),i=new Set;for(let o of t)CY(e,o,r.get(o)??[])&&i.add(o);return i}function CY(e,t,n){if(!vY.test(t)||!st(e.config.projectRoot,t))return!0;if(n.length===0)return!1;let r=de(e.config.projectRoot,t,{inputKind:"changed source file"}).split(/\r?\n/),i=IY(r);for(let o of n)for(let s=o.startLine;s<=o.endLine;s+=1)if((r[s]??"").trim()!==""&&!i.has(s))return!0;return!1}var vY=/\.(?:[cm]?[jt]sx?)$/i;function IY(e){let t=new Set,n=!1;for(let r=0;r<e.length;r+=1){let i=e[r].trim();!n&&wY(i)&&(n=!0),n&&(t.add(r),i.endsWith(";")&&(n=!1))}return t}function wY(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}var Yw=me({kind:"doc-path-evidence",invalidation:re("doc-path-evidence"),serialize:$Y,deserialize:HY}),Ks=/\.(?:md|mdx|rst|txt)$/i;function EY(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var DY=3,PY=/([A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6})(?::([1-9][0-9]*))?\b/g;function kY(e,t={}){let{doc:n,limit:r=20,minCoupling:i=DY,includeSnapshotExcluded:o=!1}=t,s=AY(e,t.historyMode??"bounded");if(!s)return{available:!1,commitsAnalyzed:0,docsScanned:0,findings:[]};let a=[];for(let c of s.docFiles){if(n!==void 0&&!c.includes(n)||n===void 0&&!Qw(e,c)||n!==void 0&&!st(e.config.projectRoot,c))continue;let l=Hl(e,c);if(l&&!o)continue;let{value:u,estimated:d}=TY(e,c,s.changeTimes.get(c)),m=FY(e,c),f=new Map,{resolved:p,broken:g,citations:y}=NY(e,c,s.tracked,s.trackedBySuffix,s.everSeenInHistory),h=new Map(y.map(b=>[b.file,b]));for(let b of p){if(b===c||Ks.test(b))continue;let R=(s.changeTimes.get(b)??[]).filter(v=>v>u).length;if(R===0)continue;let x=h.get(b);f.set(b,{file:b,evidence:"reference",coChanges:0,changesSinceDocUpdate:R,...Up("reference",m,x?.contexts),citationContexts:x?.contexts,citedLines:x?.lineReferences})}for(let[b,R]of s.coupling.get(c)??[]){if(R<i||!s.tracked.has(b))continue;let x=(s.changeTimes.get(b)??[]).filter(C=>C>u).length;if(x===0)continue;let v=f.get(b);v?(v.evidence="both",v.coChanges=R,Object.assign(v,Up("both",m,v.citationContexts))):f.set(b,{file:b,evidence:"co-change",coChanges:R,changesSinceDocUpdate:x,...Up("co-change",m)})}if(f.size===0&&g.length===0)continue;let S=[...f.values()].sort((b,R)=>R.changesSinceDocUpdate-b.changesSinceDocUpdate);a.push({doc:c,docLastChangedAt:u,staleness:S.reduce((b,R)=>b+R.changesSinceDocUpdate,0)+g.length*10,subjects:S.slice(0,8),brokenReferences:g,...l?{snapshotExcluded:!0}:{},...d?{docLastChangedAtEstimated:!0}:{}})}return a.sort((c,l)=>l.staleness-c.staleness),{available:!0,commitsAnalyzed:s.historyCommitCount,docsScanned:s.docFiles.length,findings:a.slice(0,r)}}function TY(e,t,n){if(n&&n.length>0)return{value:Math.max(...n),estimated:!1};try{return{value:Math.floor(bn(e.config.projectRoot,t).mtimeMs/1e3),estimated:!0}}catch(r){if(st(e.config.projectRoot,t))throw r;return{value:0,estimated:!1}}}function FY(e,t){let n=k(e,t).slice(0,6e3);if(!n)return{docIntent:"unknown",reasons:["doc text unavailable"]};let r=`${t}
|
|
774
|
+
${n}`.toLowerCase(),i=ni(r,["historical note","historical record","history note","retrospective","postmortem","post-mortem","archived","archive","previously","legacy","recorded","record of","snapshot","as of","migration note","decision record"]);if(i.length>0)return{docIntent:"historical-note",reasons:[`historical-note terms: ${i.join(", ")}`]};let o=ni(r,["current","standard","standards","must","should","policy","guide","guidance","workflow","contract","invariant","source of truth"]);return o.length>0?{docIntent:"current-guidance",reasons:[`current-guidance terms: ${o.join(", ")}`]}:{docIntent:"unknown",reasons:["no current-guidance or historical-note markers found"]}}function Up(e,t,n=[]){let r=e==="co-change"||n.length===0?null:Hn.classifyCitation(n);return{actionTier:_Y(e,t.docIntent,r?.actionTier),docIntent:t.docIntent,docIntentReasons:t.reasons,...r?{citationKind:r.citationKind,citationKindReasons:r.reasons}:{}}}function _Y(e,t,n){return t==="historical-note"?"support":n||(e==="co-change"?"signal":"direct")}function AY(e,t){let n=ft(e,{historyMode:t}),r=n.commitHistory();if(!r)return null;let i=n.trackedFiles()??new Set,o=new Map,s=new Map,a=new Set;for(let c of r.commits){let l=[...new Set(c.files)],u=l.filter(m=>Ks.test(m)),d=l.filter(m=>!Ks.test(m));for(let m of l){a.add(m);let f=o.get(m)??[];f.push(c.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:[...i].filter(c=>Ks.test(c)),everSeenInHistory:a,historyCommitCount:r.commits.length,tracked:i,trackedBySuffix:Zw(i)}}function Xw(e,t){if(t.size===0)return[];let n=W(),r=0,i=0,o=0,s=0,a=0,c=0;return D("doc-reference.docs-citing-files",()=>{let l=ft(e).trackedFiles()??new Set;r=l.size;let u=Zw(l),d=LY(t,u),m=[];for(let f of l){if(!Qw(e,f))continue;n&&(i+=1);let p=k(e,f);if(!p&&!st(e.config.projectRoot,f)){n&&(o+=1);continue}if(!BY(p,d)){n&&(s+=1);continue}let g=eE(e,f,p);if(!g)continue;n&&(a+=1);let y=MY(g.candidates,t,d,l,u);if(y.size===0)continue;let h=[...new Set([...y.values()].flatMap(x=>[...x]))],S=OY(g.contextsByCandidate,h),b=[...y].map(([x,v])=>({file:x,contexts:Gl([...v].flatMap(C=>S.get(C)??[])).slice(0,3),lineReferences:ql([...v].flatMap(C=>g.lineReferencesByCandidate.get(C)??[]))})).filter(x=>x.contexts.length>0),R=[...y.keys()];if(R.length>0){n&&(c+=1);let x=R.sort();m.push({doc:f,cited:x,citations:b,citedClaims:Gl(b.flatMap(v=>v.contexts)).slice(0,3)})}}return m},()=>({targets:t.size,trackedFiles:r,livingDocs:i,unreadableDocs:o,candidateMisses:s,evidenceDocs:a,citedDocs:c}))}function Qw(e,t){return Ks.test(t)&&!EY(t)&&st(e.config.projectRoot,t)}function Zw(e){let t=new Map;for(let n of e){let r=n.split("/");for(let i of[2,3]){if(r.length<i)continue;let o=r.slice(-i).join("/"),s=t.get(o)??[];s.push(n),t.set(o,s)}}return t}function LY(e,t){let n=new Set(e);for(let r of e){let i=r.split("/");for(let o of[2,3]){if(i.length<o)continue;let s=i.slice(-o).join("/"),a=t.get(s);a?.length===1&&a[0]===r&&n.add(s)}}return n}function MY(e,t,n,r,i){let o=new Map;for(let s of e){if(!n.has(s))continue;let a;if(t.has(s))a=s;else if(r.has(s))a=s;else{let l=i.get(s);l?.length===1&&(a=l[0])}if(!a||!t.has(a))continue;let c=o.get(a)??new Set;c.add(s),o.set(a,c)}return o}function NY(e,t,n,r,i){let o=new Set,s=new Set,a=eE(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let c=a.candidates,l=a.contextsByCandidate,u=a.lineReferencesByCandidate,d=new Map,m=new Map,f=(p,g)=>{let y=l.get(g);if(y&&y.length>0){let S=d.get(p)??[];S.push(...y),d.set(p,Gl(S).slice(0,3))}let h=u.get(g);h&&h.length>0&&m.set(p,ql([...m.get(p)??[],...h]))};for(let p of c){if(n.has(p)){o.add(p),f(p,p);continue}let g=r.get(p);if(g&&g.length===1){o.add(g[0]),f(g[0],p);continue}g&&g.length>1||i.has(p)&&s.add(p)}return{resolved:o,broken:[...s],citations:[...d].map(([p,g])=>({file:p,contexts:g,lineReferences:m.get(p)}))}}function OY(e,t){let n=new Map;for(let r of t){let i=e.get(r);i&&i.length>0&&n.set(r,[...i])}return n}function eE(e,t,n){let r=n;if(r===void 0&&(r=k(e,t),!r&&!st(e.config.projectRoot,t)))return null;let i=he(e,t,r),o=Yw.read(e,t,i);if(o)return o;let s=jY(r);return Yw.write(e,t,i,s),s}function BY(e,t){for(let n of t)if(e.includes(n))return!0;return!1}function jY(e){let t=e.split(/\r?\n/),n=new Set,r=new Map,i=new Map;for(let o=0;o<t.length;o+=1){let s=t[o]??"";for(let a of s.matchAll(PY)){let c=(a[1]??"").replace(/^\.?\//,"");if(c.length===0)continue;n.add(c);let l=a[2]?Number(a[2]):null;l!==null&&Number.isSafeInteger(l)&&i.set(c,ql([...i.get(c)??[],l]));let u=$l(t,o);if(u.length===0)continue;let d=r.get(c)??[];d.push(u),r.set(c,Gl(d).slice(0,3))}}return{candidates:[...n],contextsByCandidate:r,lineReferencesByCandidate:i}}function $Y(e){let t={candidates:e.candidates,contextsByCandidate:[...e.contextsByCandidate.entries()],lineReferencesByCandidate:[...e.lineReferencesByCandidate.entries()]};return JSON.stringify(t)}function HY(e){try{let t=JSON.parse(e);if(!en(t))return null;let n=et(t.candidates),r=qY(t.contextsByCandidate),i=GY(t.lineReferencesByCandidate);return!n||!r?null:{candidates:n,contextsByCandidate:new Map(r),lineReferencesByCandidate:new Map(i??[])}}catch{return null}}function GY(e){if(e===void 0)return[];if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||!Array.isArray(n[1]))return null;let r=[];for(let i of n[1]){if(typeof i!="number"||!Number.isSafeInteger(i))return null;r.push(i)}t.push([n[0],ql(r)])}return t}function qY(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string")return null;let r=et(n[1]);if(!r)return null;t.push([n[0],r])}return t}function Gl(e){let t=[];for(let n of new Set(e))t.some(r=>UY(r,n))||t.push(n);return t}function ql(e){return[...new Set(e)].sort((t,n)=>t-n)}function UY(e,t){if(e===t)return!0;let n=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),r=t.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),i=Math.min(n.length,r.length);if(i===0)return!1;if(i<3)return e.includes(t)||t.includes(e);let o=new Set(r),s=n.filter(a=>o.has(a)).length;return s>=3&&s/i>=.6}import{createHash as VY}from"crypto";var nE=3;function Js(e,t={}){let{scope:n,maxLoc:r=15,minLoc:i=nE,limit:o,scanLimit:s}=t,a=Ip(e),c=oE(e,{scope:n,maxLoc:r,scanLimit:s}).map(u=>sE(e,u,a,i)).filter(u=>u!==null),l=iE(c);return o?l.slice(0,o):l}function Vp(e,t,n={}){let{scope:r,maxLoc:i=15,minLoc:o=nE,scanLimit:s}=n,a=Ip(e),c=oE(e,{scope:r,maxLoc:i,scanLimit:s}).map(u=>sE(e,u,a,o)).filter(u=>u!==null),l=c.find(u=>u.symbol===t);return l?c.filter(u=>u.symbol!==l.symbol&&u.normalizedBody===l.normalizedBody&&u.file!==l.file).sort(aE).map(({normalizedBody:u,...d})=>d):[]}function rE(e){let t=fn(e);return Tt(t).replace(/\s+/g,"")}function iE(e){let t=new Map;for(let r of e){if(r.normalizedBody.length<8)continue;let i=WY(r.normalizedBody),o=t.get(i)??[];o.push(r),t.set(i,o)}let n=[];for(let[r,i]of t){let o=new Set(i.map(a=>a.file));if(i.length<2||o.size<2)continue;let s=[...i].sort(aE).map(({normalizedBody:a,...c})=>c);n.push({hash:r,canonical:s[0],functions:s})}return n.sort((r,i)=>{let o=i.functions.length-r.functions.length;if(o!==0)return o;let s=tE(i)-tE(r);return s!==0?s:r.canonical.file.localeCompare(i.canonical.file)}),n}function oE(e,t){let n=Oe(e,{scope:t.scope}).filter(r=>r.isFunctionLike&&!e.isIgnored(r.relativePath)).filter(r=>!xa(e,r.relativePath,r.startLine,"similar")).filter(r=>j(r)<=t.maxLoc);return n.sort((r,i)=>j(i)-j(r)||r.relativePath.localeCompare(i.relativePath)),fe(n,t.scanLimit)}function sE(e,t,n,r){let i=Gn(e,t);if(!i||zY(i)<r)return null;let o=zp(e,t);return o?{symbol:t.symbol,shortName:E(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:j(t),ageCommits:n?.get(t.relativePath)?.commitsAgo??null,normalizedBody:o}:null}function zp(e,t){let n=Gn(e,t);return n&&rE(n)||null}function Gn(e,t){let n=Ne(e,t.relativePath);return n.length===0?null:n.slice(t.startLine,t.endLine+1).join(`
|
|
775
|
+
`)}function fn(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(t>=0&&n>t)return e.slice(t+1,n);let r=e.indexOf("=>");return r>=0?e.slice(r+2).replace(/;+\s*$/,""):e}function zY(e){return fn(e).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0).length}function WY(e){return VY("sha256").update(e).digest("hex").slice(0,16)}function aE(e,t){let n=e.ageCommits??-1;return(t.ageCommits??-1)-n||e.file.localeCompare(t.file)||e.startLine-t.startLine}function tE(e){return e.functions.reduce((t,n)=>t+n.loc,0)}var KY=new Set(ln());function JY(e,t={}){let{includeHomonyms:n=!1,limit:r}=t,i=fo(e,t).filter(o=>o.relationship==="divergent"||n&&o.relationship==="homonym");return r?i.slice(0,r):i}function fo(e,t={}){let{scope:n,minSimilarity:r=.3,scanLimit:i}=t,o=QY(e,{scope:n,scanLimit:i});return uE(o,{minSimilarity:r,isDelegatePair:x5(e)}).filter(s=>!s.members.some(a=>xa(e,a.file,a.startLine,"twin")))}function uE(e,t={}){let n=t.minSimilarity??.3,r=t.isDelegatePair,i=e.filter(l=>!yE(l.leaf)&&!l5(l.leaf)&&U(l.file)!=="test"&&!$e(l.symbol)&&!mE(l.symbol)&&!fE(l.symbol,l.leaf)),{recordsByLeaf:o,recordOrder:s}=D("twin-drift.group-by-leaf",()=>YY(i),()=>({records:i.length})),a=D("twin-drift.cluster-leaf-names",()=>dE([...o.keys()]),()=>({leaves:o.size}));return D("twin-drift.compare-clusters",()=>{let l=[];for(let u of a){let d=XY(u,o,s);if(d.length<2||new Set(d.map(S=>S.file)).size<2)continue;let m=null,f=!1,p=!1,g=new Set;for(let S=0;S<d.length;S+=1)for(let b=S+1;b<d.length;b+=1){let R=d[S],x=d[b];if(R.file===x.file||!f5(R,x)||r?.(R,x,d)||r?.(x,R,d))continue;if(f=!0,g.add(R.symbol),g.add(x.symbol),R.normalizedBody===x.normalizedBody){p=!0;continue}let v=o5(R.tokens,x.tokens);(!m||v>m.similarity)&&(m={a:R,b:x,similarity:v})}if(!f)continue;let y=d.filter(S=>g.has(S.symbol)).sort((S,b)=>S.file.localeCompare(b.file)||S.startLine-b.startLine).map(i5);if(!m){l.push({leaf:lE(u),relationship:p?"identical":"homonym",maxDivergence:0,members:y});continue}let h=m.similarity>=n?"divergent":"homonym";l.push({leaf:lE(u),relationship:h,maxDivergence:Math.round((1-m.similarity)*1e3)/1e3,members:y,...h==="divergent"?{firstDivergentTokens:s5(m.a.tokens,m.b.tokens)}:{}})}return l},()=>({clusters:a.length,records:i.length})).sort((l,u)=>u.members.length-l.members.length||u.maxDivergence-l.maxDivergence||l.leaf.localeCompare(u.leaf))}function YY(e){let t=new Map,n=new Map;for(let[r,i]of e.entries()){let o=t.get(i.leaf)??[];o.push(i),t.set(i.leaf,o),n.set(i,r)}return{recordsByLeaf:t,recordOrder:n}}function XY(e,t,n){let r=[...e].flatMap(i=>t.get(i)??[]);return e.size>1&&r.sort((i,o)=>(n.get(i)??0)-(n.get(o)??0)),r}function QY(e,t){let n=D("twin-drift.load-definitions",()=>Oe(e,{scope:t.scope}).filter(o=>ZY(o)&&!e.isIgnored(o.relativePath)).filter(o=>!Qi(o.relativePath)));D("twin-drift.sort-definitions",()=>n.sort((o,s)=>o.relativePath.localeCompare(s.relativePath)||o.startLine-s.startLine),()=>({definitions:n.length}));let r=fe(n,t.scanLimit),i=D("twin-drift.select-candidates",()=>e5(r),()=>({scanned:r.length}));return D("twin-drift.build-records",()=>{let o=[];for(let s of i){let a=t5(e,s);a&&o.push(a)}return o},()=>({candidates:i.length,scanned:r.length}))}function ZY(e){return e.isFunctionLike?e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&KY.has(e.kind):!0:!1}function e5(e){let t=e.filter(o=>o.leaf&&!yE(o.leaf)&&!$e(o.symbol)&&!mE(o.symbol)&&!fE(o.symbol,o.leaf)),n=new Map;for(let o of t){let s=n.get(o.leaf)??[];s.push(o),n.set(o.leaf,s)}let r=dE([...n.keys()]),i=new Set;for(let o of r){let s=[...o].flatMap(a=>n.get(a)??[]);if(!(s.length<2)&&!(new Set(s.map(a=>a.relativePath)).size<2)&&!s.every(a=>U(a.relativePath)==="test"))for(let a of s)i.add(a)}return e.filter(o=>i.has(o))}function t5(e,t){if(!t.leaf)return null;let n=Gn(e,t);if(!n||!ye(t.symbol)&&!n5(n,t.leaf))return null;let r=Tt(fn(n)),i=r.replace(/\s+/g,"");if(!i||i.length<8)return null;let o=r.match(r5)??[];return o.length===0?null:{leaf:t.leaf,symbol:t.symbol,shortName:E(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:j(t),normalizedBody:i,tokens:o,isThinForwarder:gE(r)}}function n5(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 r5=/[A-Za-z_$][A-Za-z0-9_$]*|\d+(?:\.\d+)?|[^\sA-Za-z0-9_$]/g;function i5(e){return{symbol:e.symbol,shortName:e.shortName,file:e.file,startLine:e.startLine,endLine:e.endLine,loc:e.loc}}function o5(e,t){let n=new Set(e),r=new Set(t);if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let i=0;for(let s of n)r.has(s)&&(i+=1);let o=n.size+r.size-i;return o===0?0:i/o}function s5(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;let i=e.slice(r,r+6).join(" "),o=t.slice(r,r+6).join(" ");return!i&&!o?"(bodies differ only in trailing length)":`A: ${i||"(end)"} | B: ${o||"(end)"}`}function dE(e){let t=new Map;for(let s of e)t.set(s,s);let n=s=>{let a=s;for(;t.get(a)!==a;)a=t.get(a);let c=s;for(;t.get(c)!==a;){let l=t.get(c);t.set(c,a),c=l}return a},r=(s,a)=>{let c=n(s),l=n(a);c!==l&&t.set(c,l)},i=new Map;for(let s of e){let a=s.slice(0,2).toLowerCase(),c=i.get(a)??[];c.push(s),i.set(a,c)}for(let s of i.values())for(let a=0;a<s.length;a+=1)for(let c=a+1;c<s.length;c+=1)a5(s[a],s[c])&&r(s[a],s[c]);let o=new Map;for(let s of e){let a=n(s),c=o.get(a)??new Set;c.add(s),o.set(a,c)}return[...o.values()]}function a5(e,t){return e===t||e.toLowerCase()===t.toLowerCase()?!0:e.length<8||t.length<8||Math.abs(e.length-t.length)>2||c5(e.toLowerCase(),t.toLowerCase())/Math.max(e.length,t.length)<.8?!1:p5(e.toLowerCase(),t.toLowerCase(),2)}function c5(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;return r}function l5(e){return/^[A-Z][A-Z0-9_]*$/.test(e)||/^__[^_].*__$/.test(e)||u5.has(e.toLowerCase())}var u5=new Set(["main","row"]),d5=new Set(["app","component","components","feature","features","impl","index","lib","route","routes","shared","src","tsx","typescript","ui"]);function mE(e){return e.startsWith("rust-analyzer ")&&/\/(?:tests?|benches?)\//.test(e)}var m5=new Set(["default","new","reset"]);function fE(e,t){return e.startsWith("rust-analyzer ")&&m5.has(t.toLowerCase())}function f5(e,t){if(e.leaf.toLowerCase()!==t.leaf.toLowerCase()||e.leaf.length>4)return!0;let n=cE(e);return[...cE(t)].some(r=>n.has(r))}function cE(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&&!d5.has(n)))}function p5(e,t,n){if(Math.abs(e.length-t.length)>n)return!1;let r=Array.from({length:t.length+1},(i,o)=>o);for(let i=1;i<=e.length;i+=1){let o=[i],s=o[0];for(let a=1;a<=t.length;a+=1){let c=e[i-1]===t[a-1]?0:1,l=Math.min(r[a]+1,o[a-1]+1,r[a-1]+c);o.push(l),s=Math.min(s,l)}if(s>n)return!1;r=o}return r[t.length]<=n}function pE(e){return gE(Tt(fn(e)))}function gE(e){let t=e.trim();if(!t||g5.test(t))return!1;let n=b5(t);return n.length===0||n.length>2?!1:y5(n[n.length-1])}var g5=/\b(?:if|else|for|while|switch|try|catch|do)\b/,h5=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^[\]]*\])*\((?:[^()]|\([^()]*\))*\)$/;function y5(e){let t=e.trim().replace(/^return\s+/,"").replace(/^await\s+/,"").replace(/;\s*$/,"").trim();return h5.test(t)}function b5(e){let t=[],n=0,r="";for(let i of e){if(i==="("||i==="["||i==="{"?n+=1:(i===")"||i==="]"||i==="}")&&(n=Math.max(0,n-1)),i===";"&&n===0){t.push(r),r="";continue}r+=i}return r.trim()&&t.push(r),t.map(i=>i.trim()).filter(i=>i.length>0)}var S5=3;function x5(e){let t=new Map;return(n,r,i)=>{if(!n.isThinForwarder)return!1;let o=`${n.symbol}\0${r.symbol}`,s=t.get(o);if(s!==void 0)return s;let a=hE(e,n,r,i,S5,new Set);return t.set(o,a),a}}function hE(e,t,n,r,i,o){if(i<=0||o.has(t.symbol)||(o.add(t.symbol),(Kn(e,t.file)??[]).filter(c=>c.line>=t.startLine&&c.line<=t.endLine&&c.calleeLeaf===n.leaf).length===0))return!1;let a=new Set(oe(e,t.file).filter(c=>c.sourcePath&&(c.kind!=="namespace"||c.usedMembers.includes(n.leaf))).map(c=>c.sourcePath));if([...a].some(c=>gt(c,n.file)))return!0;for(let c of r)if(!(c.symbol===t.symbol||c.symbol===n.symbol||!c.isThinForwarder)&&[...a].some(l=>gt(l,c.file))&&hE(e,c,n,r,i-1,o))return!0;return!1}function yE(e){return e.startsWith("<")&&e.endsWith(">")}function lE(e){return[...e].sort()[0]}import{readdirSync as R5}from"fs";import{basename as C5,join as bE}from"path";function v5(e,t,n={}){let r=new Set(e),i=new Set(t),o=[...i].filter(a=>!r.has(a)).sort(),s=n.allowExtra?[]:[...r].filter(a=>!i.has(a)).sort();return{missing:o,extra:s}}function Wp(e,t){let n=I5(e,t.file,t.keys);if(!n.ok)return{name:t.name,file:t.file,status:"unavailable",missing:[],extra:[],unavailableReason:n.reason};let r=T5(e.config.projectRoot,t.mustEqual),i=v5(n.keys,r,{allowExtra:t.allowExtra??!1}),o=i.missing.length>0||i.extra.length>0?"violated":"ok";return{name:t.name,file:t.file,status:o,missing:i.missing,extra:i.extra}}function xE(e,t){return t.map(n=>Wp(e,n))}function RE(e,t){if(t.has(e.file))return!0;let n=e.mustEqual;switch(n.type){case"top-level-dirs":return[...t].some(r=>r===n.path||r.startsWith(`${n.path}/`));case"file-glob":return[...t].some(r=>gr(n.pattern,r));case"registered-commands":return t.has("docs/COMMAND_REFERENCE.md");case"builtin-skills":return[...t].some(r=>r.startsWith("skills/"))}}function CE(e){if(e.status==="unavailable")return`[coverage-contract] ${e.name}: DISCLOSED \u2014 could not evaluate (${e.unavailableReason})`;let t=[];return e.missing.length>0&&t.push(`missing ${e.missing.join(", ")}`),e.extra.length>0&&t.push(`extra ${e.extra.join(", ")}`),`[coverage-contract] ${e.name}: ${t.join("; ")}`}function I5(e,t,n){return n.type==="markdown-list"?k5(e,t,n.marker):w5(e,t,n)}function w5(e,t,n){if(!k(e,t))return{ok:!1,reason:`file not found: ${t}`};let i=N(t);if(!i)return{ok:!1,reason:`unsupported file type for ${n.type} extraction: ${t}`};let o=ne(e,t);if(!o)return{ok:!1,reason:`tree-sitter parser unavailable for ${i} (${t}) \u2014 contract skipped, not silently passed`,disclosedUnavailable:{language:i,reason:"parser-unavailable"}};let s=n.type==="object-literal-keys"?E5(o,n.identifier):P5(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 vE(e){let t=e.childForFieldName("value");return t?t.type==="as_expression"||t.type==="satisfies_expression"?t.namedChild(0):t:null}function E5(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=vE(n);if(i?.type==="object")return D5(i)}return null}function D5(e){let t=new Set;for(let n of e.namedChildren)if(n.type==="pair"){let r=n.childForFieldName("key");r&&t.add(IE(r.text))}else n.type==="shorthand_property_identifier"&&t.add(n.text);return[...t].sort()}function P5(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=vE(n);if(i?.type!=="array")continue;let o=new Set;for(let s of i.namedChildren)s.type==="string"&&o.add(IE(s.text));return[...o].sort()}return null}function IE(e){return e.length>=2&&(e[0]==="'"&&e.endsWith("'")||e[0]==='"'&&e.endsWith('"'))?e.slice(1,-1):e}function k5(e,t,n){let r=k(e,t);if(!r)return{ok:!1,reason:`file not found: ${t}`};let i=wE(r,n);return i===null?{ok:!1,reason:`no <!-- BEGIN GENERATED ${n} --> ... <!-- END GENERATED ${n} --> block in ${t}`}:{ok:!0,keys:EE(i)}}function wE(e,t){let n=H(t),i=new RegExp(`<!--\\s*BEGIN GENERATED ${n}\\s*-->([\\s\\S]*?)<!--\\s*END GENERATED ${n}\\s*-->`).exec(e);return i?i[1]:null}function EE(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 T5(e,t){switch(t.type){case"top-level-dirs":return SE(bE(e,t.path));case"file-glob":return[...new Set(Il(e,t.pattern).map(n=>C5(n)))].sort();case"registered-commands":return F5(e);case"builtin-skills":return SE(bE(e,"skills"))}}function SE(e){let t;try{t=R5(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort()}function F5(e){let t;try{t=de(e,"docs/COMMAND_REFERENCE.md",{maxBytes:8*1024*1024,inputKind:"generated command reference"})}catch(r){if(!we(r))throw r;return[]}let n=wE(t,"COMMAND REFERENCE");return n?EE(n):[]}var Ce={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 _5}from"fs";import{isAbsolute as A5,join as L5}from"path";var M5=".scipquery-baseline.json";function Kp(e){if(e.startsWith("similar:")){let t=e.slice(8).split("|");return t.length!==2?e:`similar:${t.map(E).sort().join("|")}`}if(e.startsWith("duplicate-bodies:")){let t=e.slice(17),n=t.indexOf(":");if(n<0)return e;let r=t.slice(0,n),i=t.slice(n+1).split("|");return i.length<2?e:`duplicate-bodies:${r}:${i.map(E).sort().join("|")}`}return e}function po(e,t){return t&&A5(t)?t:L5(e.config.projectRoot,t??M5)}function Ul(e,t,n={}){let r=po(e,n.path);if(!_5(r))throw new Error(`No baseline found at ${r}. Create one with: scip-query health --write-baseline`);let o=(JSON.parse(O(r,"health baseline")).findings??[]).map(Kp),s=new Set(n.accept?o.filter(n.accept):o),a=new Set(t);return{baselinePath:r,baselineCount:s.size,current:[...t],newFindings:t.filter(c=>!s.has(c)),fixedFindings:[...s].filter(c=>!a.has(c))}}import Ys from"path";function Qs(e,t){let{scope:n,minDeviation:r=5,limit:i=50}=t??{},o=t?.semantic!==!1,s=t?.includePatternDeviations===!0,c=new F(e).fileDependencyGraph(n),l=ti(e,{scope:n}),u=$5([...N5(e,c,{scope:n,semantic:o}),...B5(l.forbiddenEdges),...s?j5(c,r):[]]);return t?.includeArchitecture===!0&&(u.architecture=l),i<=0||u.results.length<=i?u:{...u,results:u.results.slice(0,i),totalResults:u.results.length}}function N5(e,t,n){let r=q5(e,n.scope),i=[],o=new Set;for(let[a,c]of t){if(Xs(a))continue;let l=r.get(a)??new Set;for(let u of c)Xs(u)||l.has(u)||O5(e,a,u,n)||(i.push({file:a,dep:u}),o.add(a))}o.size>0&&z5(e,r,{paths:[...o]});let s=[];for(let{file:a,dep:c}of i)(r.get(a)??new Set).has(c)||s.push({file:a,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c,actionTier:"direct",evidenceReasons:[`dependency edge exists from ${a} to ${c}`,"no semantic, source, type-only, side-effect, or Vue-template usage survived the conservative skip gates"],recommendation:"Remove the unused import or dependency edge after running the project checks."});return s}function O5(e,t,n,r){return J5(e,t,n)||Y5(e,t,n)||W5(n)||Q5(e,t,n)||X5(n)?!0:r.semantic&&K5(e,t,n)}function B5(e){return e.flatMap(t=>{let n=t.examples[0];return n?[{file:n.fromFile,kind:"architecture-violation",description:`${t.from} depends on forbidden boundary ${t.to} through ${t.fileEdgeCount} file edge(s)`,dep:n.toFile,detail:`${t.from} may not depend on ${t.to}`,actionTier:"direct",policyBasis:"explicit",architecture:{fromBoundary:t.from,toBoundary:t.to,fileEdgeCount:t.fileEdgeCount,importerCount:t.importerCount,importedFileCount:t.importedFileCount,examples:t.examples},evidenceReasons:[`configured dependency row for ${t.from} does not allow ${t.to}`,`${t.fileEdgeCount} file edge(s) connect ${t.importerCount} importer(s) to ${t.importedFileCount} imported file(s)`,...t.examples.map(r=>`${r.fromFile} imports ${r.toFile}`)],recommendation:"Move the dependency behind an allowed boundary, reverse the dependency through an owned interface, or deliberately update the project architecture rule."}]:[]})}function j5(e,t){let n=[];for(let[r,i]of H5(e)){let o=i.filter(a=>!Xs(a));if(o.length<t)continue;let s=G5(e,o);for(let a of o)for(let c of e.get(a)??[])Xs(c)||(s.get(c)??0)===1&&Ys.dirname(c)!==r&&Ys.dirname(c)!==Ys.dirname(r)&&n.push({file:a,kind:"pattern-deviation",description:`Only file in ${r}/ that depends on ${c}`,dep:c,actionTier:"signal",evidenceReasons:[`${o.length} sibling file(s) in ${r}/ were compared`,`${a} is the only non-skipped sibling depending on ${c}`],recommendation:"Review sibling ownership before changing this import; unique dependency shape can be intentional specialization."})}return n}function $5(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 H5(e){let t=new Map;for(let n of e.keys()){let r=Ys.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function G5(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])Xs(i)||n.set(i,(n.get(i)??0)+1);return n}function q5(e,t){let n=new Map;return U5(e,n,t),n}function U5(e,t,n){for(let r of V5(e,n))DE(e,t,r.from_file,r.to_file)}function V5(e,t){let n=t?"AND d1.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`SELECT DISTINCT d1.relative_path AS from_file, d2.relative_path AS to_file
|
|
776
|
+
FROM mentions m
|
|
777
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
778
|
+
JOIN documents d1 ON c.document_id = d1.id
|
|
779
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
780
|
+
JOIN (
|
|
781
|
+
SELECT m2.symbol_id, c2.document_id
|
|
782
|
+
FROM mentions m2
|
|
783
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
784
|
+
WHERE m2.role = 1
|
|
785
|
+
GROUP BY m2.symbol_id
|
|
786
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
787
|
+
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
788
|
+
WHERE d1.id != d2.id
|
|
789
|
+
AND m.role != 1
|
|
790
|
+
${e.pathExclusionsFor("d1","d2")}
|
|
791
|
+
${n}`,...r)}function z5(e,t,n={}){new F(e).scanSourceReferences({paths:n.paths??L(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},i=>{i.target.relativePath!==i.sourceFile&&(e.isIgnored(i.target.relativePath)||DE(e,t,i.sourceFile,i.target.relativePath))})}function DE(e,t,n,r){if(e.isIgnored(n)||e.isIgnored(r))return;let i=t.get(n);i||(i=new Set,t.set(n,i)),i.add(r)}function W5(e){return e.includes("types")||e.endsWith(".d.ts")}function K5(e,t,n){let r=ds(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.isUsed)}function J5(e,t,n){let r=oe(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.used)}function Y5(e,t,n){let r=oe(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function X5(e){return e.endsWith(".vue")}function Q5(e,t,n){let r=oe(e,t).filter(i=>i.sourcePath===n);return r.length===0?!1:r.every(i=>i.kind==="side-effect"||i.kind==="namespace"&&i.usedMembers.length===0&&!i.used)}function Xs(e){let t=U(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||Z5(Ys.basename(e)))}function Z5(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")}import{basename as PE,extname as kE}from"path";function Vl(e,t,n,r,i,o){let s=new Set;tX(e,t,n,r)&&s.add(i);for(let a of o)a.value&&eX(s,a.label,a.value);return[...s].slice(0,6)}function eX(e,t,n){let r=nX(n);t.endsWith("name")&&rX(r)&&e.add(`${t} has type-guard boundary shape`);for(let i of r){let o=iX.get(i);o&&e.add(`${t} has ${o} term: ${i}`)}}function tX(e,t,n,r){if(n<=0)return!1;let i=Ne(e,t);if(i.length===0)return!1;for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(i[o]??"").trim();if(s!==""){if(vo(s)===r)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function nX(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 rX(e){return e.some(t=>oX.has(t))&&e.some(t=>sX.has(t))}var iX=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"]]),oX=new Set(["can","has","is","should"]),sX=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function Zs(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new F(e);return $t({candidates:()=>pX(e,s,n,r),orderCandidates:xl,scanLimit:o,profile:{name:"passthrough-candidates"},prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>aX(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:i})}function aX(e,t,n){let r=fX(n);if(r.size!==1||!Ju(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0],o=cX(e,t,i),s=uX(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:E(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:j(t),forwardsTo:i.symbol,forwardsToShort:E(i.symbol),forwardsToFile:i.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:lX(a,o,s)}}function cX(e,t,n){return Vl(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:E(t.symbol)},{label:"callee name",value:E(n.symbol)},{label:"passthrough module",value:PE(t.relativePath,kE(t.relativePath))},{label:"callee module",value:PE(n.file,kE(n.file))}])}function lX(e,t,n){if(e==="signal"){if(n.length>0)return`Review the public API before inlining; public-facade evidence: ${n.slice(0,2).join("; ")}.`;let r=t.filter(mX);return r.length>0?`Review the public API before inlining; public-surface evidence: ${r.slice(0,2).join("; ")}.`:`Review the boundary before inlining; boundary evidence: ${t.slice(0,2).join("; ")}.`}return"Inline or remove this passthrough unless an external API or runtime registration depends on the forwarding name."}function uX(e,t){return ea(e,t)?Mn(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:Re(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function ea(e,t){let n=Ne(e,t.relativePath);if(n.length===0)return!1;let r=T(t.symbol);if(!r)return!1;let i=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
|
|
792
|
+
`),o=H(r);return new RegExp(`^\\s*export\\s+(?:default\\s+)?(?:(?:async\\s+)?function\\s+${o}\\b|(?:const|let|var)\\s+${o}\\b)`,"m").test(i)?!0:dX(n,r)}function dX(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${H(t)}\\b`);return e.some(r=>n.test(r))}function mX(e){return e.includes("public surface")}function fX(e){let t=e.some(r=>ae(r.symbol))?e.filter(r=>ae(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function pX(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:3,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0}).filter(i=>!Do(e,i))}function ta(e,t){let{scope:n,minLoc:r=3,maxLoc:i=80,limit:o=30,includeLowConfidence:s=!1,scanLimit:a}=t??{},c=t?.semantic!==!1,l=new F(e),u=l.scopedDefinitions(n),d=EX(l,n),m={high:0,medium:1,low:2};return $t({candidates:()=>gX(e,l,u,{minLoc:r,maxLoc:i}),orderCandidates:(f,p)=>j(p)-j(f)||f.relativePath.localeCompare(p.relativePath),scanLimit:a,profile:{name:"stale-abstractions"},prepare:f=>{let p=yX(f),g=hX(e,l,f,p,{semantic:c}),y=f.filter(h=>{let S=zl(e,h,g,p);return S.realConsumers.length<=1&&!S.transitivelyReachable&&TE(h,S.realConsumers.length,d)});return{consumerFileMap:g,singletonBackedClassIds:xX(e,l,u,y,{semantic:c}),candidateIndex:p}},evaluate:(f,p)=>{if(p.singletonBackedClassIds.has(f.symbolId))return null;let g=zl(e,f,p.consumerFileMap,p.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!TE(g.definition,g.realConsumers.length,d))return null;let y=bX(e,g);return!s&&y.confidence==="low"?null:y},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 gX(e,t,n,r){return n.filter(i=>i.isTypeLike&&j(i)>=r.minLoc).filter(i=>j(i)<=r.maxLoc).filter(i=>!e.isIgnored(i.relativePath)).filter(i=>!i.relativePath.endsWith(".d.ts")).filter(i=>U(i.relativePath)!=="test").filter(i=>!Re(e,i.symbol,i.relativePath)).filter(i=>!DX(i.symbol)).filter(i=>!t.hasSuppressionComment(i))}function Jp(e,t,n,r){return jn(Bn(e,t).forDefinitions(n,{semantic:r.semantic,sourceFallback:r.sourceFallback}))}function hX(e,t,n,r,i){let o=Jp(e,t,n,{semantic:!1,sourceFallback:!1}),s=n.filter(l=>{let u=zl(e,l,o,r);return u.realConsumers.length<=1&&!(u.realConsumers.length>0&&Yp(l.relativePath))}),a=i.semantic&&s.length>0?On(o,Jp(e,t,s,{semantic:!0,sourceFallback:!1})):o,c=s.filter(l=>zl(e,l,a,r).realConsumers.length<=1);return On(a,Jp(e,t,c,{semantic:!1,sourceFallback:!0}))}function yX(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);r||(r=new Map,t.set(n.relativePath,r));let i=T(n.symbol);i&&r.set(i,n)}return t}function zl(e,t,n,r){let o=[...n.get(t.symbolId)??new Set].filter(u=>u!==t.relativePath&&!e.isIgnored(u)),{realConsumers:s,barrelConsumers:a,importOnlyConsumers:c}=Fl(e,t,o),l=PX(e,t,n,r);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function bX(e,t){let n=_E(e,t.definition.relativePath,t.definition.startLine),r=Yp(t.definition.relativePath)?!0:kX(e,t.definition),{confidence:i,reason:o}=TX(t.realConsumers.length,n,r),s=SX(t.realConsumers.length,n,r);return{symbol:t.definition.symbol,shortName:E(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:j(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:r,confidence:i,reason:o,actionTier:s.actionTier,stalenessKind:s.stalenessKind,recommendation:s.recommendation}}function SX(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 xX(e,t,n,r,i){let o=CX(e,RX(n),r),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=jn(Bn(e,t).forDefinitions(s,{semantic:i.semantic,sourceFallback:!0})),c=new Set;for(let{singleton:l,classId:u}of o)IX(e,l,a)&&c.add(u);return c}function RX(e){let t=new Map;for(let n of e){let r=T(n.symbol);r&&t.set(FE(n.relativePath,r),n)}return t}function CX(e,t,n){let r=[];for(let i of n){let o=vX(e,t,i);o&&r.push({singleton:o,classId:i.symbolId})}return r}function vX(e,t,n){if(_E(e,n.relativePath,n.startLine)!=="class")return null;let r=T(n.symbol);if(!r)return null;let i=wX(e,n.relativePath,r);return i?t.get(FE(n.relativePath,i))??null:null}function IX(e,t,n){let r=T(t.symbol),i=n.get(t.symbolId);return!r||!i?!1:[...i].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!pp(e,o,r))}function FE(e,t){return`${e}\0${t}`}function wX(e,t,n){let r=k(e,t);if(!r)return null;let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\bexport\\s+const\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*new\\s+${i}\\s*\\(`);return r.match(o)?.[1]??null}function EX(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function DX(e){let t=Te(e);if("kind"in t)return!1;let n=t.descriptors;if(n.length<2)return!1;let r=n[n.length-1],i=n[n.length-2];return r?.suffix==="type"&&i?.suffix==="type"}function Yp(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 TE(e,t,n){return!(Yp(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function PX(e,t,n,r){let i=Xu(e,t.relativePath),o=T(t.symbol);if(!o)return!1;let s=r.get(t.relativePath);if(!s)return!1;let a=[...i.get(o)??[]],c=new Set;for(;a.length>0;){let l=a.pop();if(c.has(l))continue;c.add(l);let u=s.get(l);if(!u)continue;let d=n.get(u.symbolId);if(d){for(let m of d)if(m!==t.relativePath&&!e.isIgnored(m))return!0}for(let m of i.get(l)??[])a.push(m)}return!1}function _E(e,t,n){let r=k(e,t);if(!r)return"other";let i=r.split(`
|
|
793
|
+
`),o=Math.max(0,n-2),s=Math.min(i.length-1,n+2);for(let a=o;a<=s;a++){let l=(i[a]??"").replace(/^\s*\/\/.*$/g,"");if(/\b(?:export\s+)?(?:abstract\s+)?class\s+\w/.test(l))return"class";if(/\b(?:export\s+)?interface\s+\w/.test(l))return"interface";if(/\b(?:export\s+)?type\s+\w/.test(l))return"type";if(/\b(?:export\s+)?(?:const\s+)?enum\s+\w/.test(l))return"enum"}return"other"}function kX(e,t){let n=k(e,t.relativePath);if(!n)return!1;let r=T(t.symbol);if(!r)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${i}\\b`),s=n.split(`
|
|
794
|
+
`);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function TX(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 go,extname as Wl}from"path";function na(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new F(e),a=NX(s.fileDependencyGraph(n));return $t({candidates:()=>AX(e,s,n,r),orderCandidates:xl,scanLimit:o,profile:{name:"wrapper-candidates"},prepare:c=>({callerFileMap:FX(e,s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>_X(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:i})}function FX(e,t,n,r){let i=Bn(e,t),o=jn(i.forDefinitions(n,{semantic:!1,sourceFallback:!1})),s=[];r.semantic&&D("wrapper.semantic-candidates",()=>{s=n.filter(m=>Xp(e,t,m,o).length<=1)},()=>({symbols:n.length,semanticCandidates:s.length}));let a=s.length===0?new Map:jn(i.forDefinitions(s,{semantic:!0,sourceFallback:!1})),c=a.size===0?o:On(o,a),l=new Map(n.map(m=>[m.symbolId,m])),u=new Map;for(let m of n){let f=Xp(e,t,m,c);if(f.length>1||(u.set(m.symbolId,m),f.length!==1))continue;let p=f[0],g=AE(e,m.symbolId,p);if(!g)continue;let y=LE(t,e,p,m.symbol,g);y?.isFunctionLike&&l.has(y.symbolId)&&u.set(y.symbolId,l.get(y.symbolId))}let d=[...u.values()];return d.length===0?c:On(c,jn(i.forDefinitions(d,{semantic:!1,sourceFallback:!0})))}function _X(e,t,n,r){let i=Xp(e,t,n,r.callerFileMap);if(i.length!==1)return null;let o=i[0],s=AE(e,n.symbolId,o);if(!s)return null;let a=LE(t,e,o,n.symbol,s);if(a&&di(a.symbol))return null;let{fanIn:c,source:l}=LX(r.callerFileMap,r.reverseFanIn,o,a);if(l==="function"?c<=3:c<=5)return null;let u=BX(e,n,o,a);return{symbol:n.symbol,shortName:E(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:j(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?E(a.symbol):go(o),callerFanIn:c,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function AX(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:2,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0}).filter(i=>!Do(e,i))}function Xp(e,t,n,r){let i=go(n.relativePath,Wl(n.relativePath)),o=[...r.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>go(s,Wl(s))!==i).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return Fl(e,n,o).realConsumers}function AE(e,t,n){return e.get(`SELECT c.start_line, c.end_line
|
|
795
|
+
FROM mentions m
|
|
796
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
797
|
+
JOIN documents d ON c.document_id = d.id
|
|
798
|
+
WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
|
|
799
|
+
LIMIT 1`,t,n)}function LE(e,t,n,r,i){let o=e.definitionsForFile(n),s=MX(t,n,r,i.start_line,i.end_line);return tn(o,s)}function LX(e,t,n,r){if(r?.isFunctionLike){let i=[...e.get(r.symbolId)??[]].filter(o=>o!==r.relativePath);if(i.length>0)return{fanIn:i.length,source:"function"}}return{fanIn:OX(t,n),source:"file"}}function MX(e,t,n,r,i){let o=T(n);if(!o)return r;let s=Pn(e,t).get(o);if(!s||s.length===0)return r;for(let a of s)if(a>=r&&a<=i)return a;return r}function NX(e){let t=new Map;for(let[n,r]of e){t.has(n)||t.set(n,t.get(n)??0);for(let i of r)t.set(i,(t.get(i)??0)+1)}return t}function OX(e,t){let n=e.get(t)??0;if(n>0)return n;let r=go(t,Wl(t)),i=0;for(let[o,s]of e)o!==t&&go(o,Wl(o))===r&&s>i&&(i=s);return i}function BX(e,t,n,r){return Vl(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:E(t.symbol)},{label:"caller name",value:r?.symbol?E(r.symbol):go(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var jX=25e3,$X=2500,HX=2500;function GX(e){let t=Zr(e);return t.symbols>=jX||t.documents>=$X?HX:void 0}function Qp(e,t={}){let{scope:n}=t,r=GX(e),i=[],o=ei(e,{scope:n,...Ce.dead,scanLimit:r});for(let s of o.symbols)Ue(e,s.relativePath)||Re(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&i.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of Os(e,{scope:n,...Ce.isolated,scanLimit:r}))Ue(e,s.relativePath)||Re(e,s.symbol,s.relativePath)||i.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of Ms(e,{scope:n}))s.kind==="real"&&i.push(`cycle:${qX(s.path)}`);for(let s of Bs(e,{scope:n,...Ce.similar,scanLimit:r}))i.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of Js(e,{scope:n,...Ce.duplicateBodies,scanLimit:r}))i.push(`duplicate-bodies:${s.hash}:${s.functions.map(a=>a.symbol).sort().join("|")}`);for(let s of qs(e,{scope:n,...Ce.extract,scanLimit:r}))i.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of na(e,{scope:n,...Ce.wrappers,scanLimit:r}))i.push(`wrapper:${s.file}:${s.shortName}`);for(let s of Zs(e,{scope:n,...Ce.passthroughs,scanLimit:r}))i.push(`passthrough:${s.file}:${s.shortName}`);for(let s of ta(e,{scope:n,...Ce.stale,scanLimit:r}))i.push(`stale:${s.file}:${s.shortName}`);for(let s of Qs(e,{scope:n,...Ce.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY}).results)s.kind!=="architecture-violation"&&i.push(`drift:${s.kind}:${s.file}:${s.dep}`);return i.push(...wl(ti(e,{scope:n}))),[...new Set(i.map(Kp))].sort()}function qX(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 UX(e,t={}){let n=Qp(e,{scope:t.scope}),r=po(e,t.path);return vt(r,{version:1,findings:n},{spacing:2,trailingNewline:!0}),{path:r,findingCount:n.length}}function Zp(e,t={}){return Ul(e,Qp(e,{scope:t.scope}),{path:t.path})}function ME(e,t={}){let n=wl(ti(e,{scope:t.scope}));return Ul(e,n,{path:t.path,accept:r=>r.startsWith(Wt)})}var VX=5;function tg(e,t={}){let{base:n="HEAD",minContainment:r=.7,minCallees:i=3,minSiteCoverage:o=.4,maxHelpers:s=Number.POSITIVE_INFINITY,limit:a=20,scanLimit:c}=t,l=t.semantic!==!1,u=t.diffPlan??xr(e,{base:n}),d={available:u.note!==zs,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 F(e),f=new Set(u.changedFiles),p=new Map(u.renamedFiles.map(C=>[C.to,C.from]));if(t.baseContentAt&&t.baseContentResultAt)throw new Error("Specify only one of baseContentAt or baseContentResultAt.");let g=t.baseContentResultAt?t.baseContentResultAt:t.baseContentAt?QX(t.baseContentAt):uo({projectRoot:e.config.projectRoot,base:n,preloadPaths:Ws(u)}),y=XX(m,f,p,g);if(y.unavailable)return d.available=!1,d.note=`Base content unavailable: ${y.unavailable.reason}`,d;if(y.definitions.length===0)return d;let h=y.definitions.slice(0,s);y.definitions.length>s&&(d.note=`helper scoring capped at ${s} of ${y.definitions.length} new symbols`);let S=m.calleeMap(h,{semantic:l}),b=h.map(C=>({def:C,callees:Dl((S.get(C.symbolId)??[]).map(w=>w.symbol))})),R=oo(e),x,v=()=>(x??=R.calleeIndex({minCallees:Math.min(3,i),scanLimit:c,semantic:l}),x);for(let{def:C,callees:w}of b){let I=E(C.symbol);if(w.size<i){d.skipped.push({helperShortName:I,helperFile:C.relativePath,reason:`fewer than ${i} meaningful callees \u2014 too small to score`});continue}let P=v(),_=YX(w,P);if(_===0){d.skipped.push({helperShortName:I,helperFile:C.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let se=ZX(e,C.symbolId);if(se.length===0){d.skipped.push({helperShortName:I,helperFile:C.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}d.helpersChecked+=1;let ee=zX({candidateIndex:P,changed:f,helperCallees:w,helperFile:C.relativePath,helperSymbol:C.symbol,minContainment:r,minSiteCoverage:o,migratedFiles:se});ee.length!==0&&(ee.sort((A,ge)=>NE(ge.migrationScope)-NE(A.migrationScope)||ge.containment-A.containment||ge.siteCoverage-A.siteCoverage||A.file.localeCompare(ge.file)),d.findings.push({helperSymbol:C.symbol,helperShortName:I,helperFile:C.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:w.size,specificHelperCalleeCount:_,migratedFiles:se.sort(),leftovers:ee.slice(0,VX)}))}return d.findings.sort((C,w)=>(w.leftovers[0]?.containment??0)-(C.leftovers[0]?.containment??0)||C.helperFile.localeCompare(w.helperFile)),d.findings=d.findings.slice(0,a),d}function zX(e){let t=[],n=WX(e.helperSymbol,e.helperFile,e.migratedFiles),r=new Set;for(let i of e.helperCallees)for(let o of e.candidateIndex.candidateIndexesByCallee.get(i)??[])r.add(o);for(let i of r){let o=e.candidateIndex.corpus[i];if(o.symbol===e.helperSymbol||e.changed.has(o.file)||o.callees.has(e.helperSymbol))continue;let s=DI(e.helperCallees,o.callees);if(s<e.minContainment)continue;let a=[...e.helperCallees].filter(u=>o.callees.has(u)),c=o.callees.size===0?0:a.length/o.callees.size;if(c<e.minSiteCoverage||!a.some(u=>(e.candidateIndex.docFreq.get(u)??0)<=e.candidateIndex.ubiquityThreshold))continue;let l=KX(n,o.symbol,o.file);t.push({symbol:o.symbol,shortName:E(o.symbol),file:o.file,...l,containment:s,siteCoverage:c,uniqueSiteCalleeCount:Math.max(0,o.callees.size-a.length),sharedCallees:a.map(E).sort()})}return t}function NE(e){return e==="same-scope"?2:e==="unknown"?1:0}function WX(e,t,n){let r=new Set([...eg(t),...ng(T(e))]);for(let i of n)for(let o of eg(i))r.add(o);return r}function KX(e,t,n){let r=new Set([...eg(n),...ng(T(t))]);if(e.size===0||r.size===0)return{migrationScope:"unknown",migrationScopeReasons:["insufficient path/name tokens to infer migration scope"]};let i=[...r].filter(o=>e.has(o)).sort();return i.length>0?{migrationScope:"same-scope",migrationScopeReasons:[`shares migration-scope token(s): ${i.slice(0,5).join(", ")}`]}:{migrationScope:"possible-subtype",migrationScopeReasons:["no path/name tokens shared with the helper or already migrated files"]}}var JX=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 eg(e){return ng(e.replace(/\.[^.]+$/,""))}function ng(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!JX.has(t))}function YX(e,t){let n=0;for(let r of e)(t.docFreq.get(r)??0)<=t.ubiquityThreshold&&(n+=1);return n}function XX(e,t,n,r){let i=[];for(let o of e.productionCallableDefinitions({files:[...t],requireFunctionLikeSymbol:!0})){if(!t.has(o.relativePath))continue;let s=n.get(o.relativePath)??o.relativePath,a=r(s);if(a.state==="unavailable")return{definitions:[],unavailable:a};(a.state==="absent"||!new RegExp(`\\b${H(o.leaf)}\\b`).test(a.content))&&i.push(o)}return{definitions:i}}function QX(e){return t=>{let n=e(t);return n===null?{state:"absent"}:{state:"present",content:n}}}function ZX(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
|
|
800
|
+
FROM mentions m
|
|
801
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
802
|
+
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
803
|
+
WHERE m.symbol_id = ?
|
|
804
|
+
AND m.role != 1
|
|
805
|
+
${e.pathExclusionsFor("ref_d")}`,t).map(r=>r.relative_path)}function rg(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new F(e);return $t({candidates:()=>o.productionCallableDefinitions({scope:n,files:t.files,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}),filterCandidate:s=>eQ(s.relativePath),scanLimit:i,profile:{name:"unused-params"},evaluate:s=>{let a=Y(e,s.relativePath)?.callables.find(u=>u.startLine===s.startLine&&u.endLine===s.endLine);if(!a||a.params.length===0||a.params.some(u=>!u.simple)||a.paramsEndLine>=a.endLine)return null;let c=Pn(e,s.relativePath),l=[];for(let u=a.params.length-1;u>=0;u--){let d=a.params[u];if(d.name===""||d.name.startsWith("_")||tQ(c.get(d.name),a.paramsEndLine,a.endLine))break;l.unshift(d.name)}return l.length===0?null:{symbol:s.symbol,shortName:E(s.symbol),file:s.relativePath,startLine:s.startLine,endLine:s.endLine,paramCount:a.paramCount,unusedTrailing:l}},orderResults:(s,a)=>a.unusedTrailing.length-s.unusedTrailing.length||s.file.localeCompare(a.file)||s.startLine-a.startLine,limit:r})}function eQ(e){let t=N(e);return t==="typescript"||t==="tsx"||t==="javascript"}function tQ(e,t,n){return e?e.some(r=>r>t&&r<=n):!1}import{existsSync as nQ,readdirSync as rQ}from"fs";import{createHash as iQ}from"crypto";import{join as sg}from"path";function og(e){let t=0,n=0,r=0,i=0,o=0,s=[];for(let l of e)switch(l.state){case"legacy":t+=1;break;case"current":n+=1;break;case"unsupported-older":r+=1,s.push(ig(l));break;case"unsupported-future":i+=1,s.push(ig(l));break;case"malformed":o+=1,s.push(ig(l));break}let a=t+n,c=r+i+o;return{complete:c===0,total:e.length,accepted:a,legacy:t,current:n,unsupportedOlder:r,unsupportedFuture:i,malformed:o,omitted:c,issues:s}}function NCe(e,t){if(!t.complete)return`${e} coverage is incomplete: accepted ${t.accepted} of ${t.total} record(s); omitted ${t.omitted} (${t.unsupportedOlder} unsupported older, ${t.unsupportedFuture} unsupported future, ${t.malformed} malformed).`}function ig(e){if(e.state==="legacy"||e.state==="current")throw new Error(`accepted record ${e.path} cannot become a compatibility issue`);return{path:e.path,state:e.state,reason:e.reason??e.state}}var jE=sg(".scipquery","suppressions"),OE="scip-query-suppression",BE=1,Kl=2;function oQ(e){return sg(e,jE)}function sQ(e){if(e.id&&e.id.trim()!=="")return`${e.id.trim()}.json`;let t=`${e.check??""}\0${e.file??""}`;return`CHECK-${iQ("sha256").update(t).digest("hex").slice(0,12).toUpperCase()}.json`}function aQ(e){return sQ(e).slice(0,-5)}function cQ(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return{state:"malformed",error:"not a suppression object"};let n=e;if(n.schemaVersion===void 0&&(n.kind!==void 0||n.suppressionIdentity!==void 0||n.writer!==void 0))return{state:"malformed",error:"suppression envelope metadata requires schemaVersion"};if(n.schemaVersion!==void 0){if(!Number.isSafeInteger(n.schemaVersion))return{state:"malformed",error:"schemaVersion must be a positive safe integer"};if(n.schemaVersion!==BE&&n.schemaVersion!==Kl)return{state:n.schemaVersion>Kl?"unsupported-future":"unsupported-older",error:`unsupported schemaVersion ${String(n.schemaVersion)}`};if(n.kind!==void 0&&n.kind!==OE)return{state:"malformed",error:`kind must be ${OE}`}}if(n.schemaVersion===BE&&n.decision!==void 0)return{state:"malformed",error:"schemaVersion 1 cannot carry automated adjudication metadata"};if(n.schemaVersion===Kl&&!Xc(n.decision))return{state:"malformed",error:"schemaVersion 2 requires a valid automated adjudication decision"};if(typeof n.reason!="string"||n.reason.trim()==="")return{state:"malformed",error:"missing reason"};if(!n.id&&!n.check)return{state:"malformed",error:"needs an id or a check"};let r=lQ(n);if(n.schemaVersion===void 0)return{state:"legacy",suppression:r,record:n,schemaVersion:0};let i=aQ(r);return n.suppressionIdentity!==i||t!==void 0&&n.suppressionIdentity!==t?{state:"malformed",error:"suppressionIdentity does not match the suppression target or filename"}:!n.writer||n.writer.tool!=="scip-query"||typeof n.writer.version!="string"||n.writer.version.trim()===""?{state:"malformed",error:"missing valid writer metadata"}:typeof n.createdAt!="string"||!Number.isFinite(Date.parse(n.createdAt))?{state:"malformed",error:"missing valid createdAt timestamp"}:n.updatedAt!==void 0&&(typeof n.updatedAt!="string"||!Number.isFinite(Date.parse(n.updatedAt)))?{state:"malformed",error:"invalid updatedAt timestamp"}:{state:n.schemaVersion===Kl?"current":"legacy",suppression:r,record:n,schemaVersion:n.schemaVersion}}function $E(e){let t=oQ(e);if(!nQ(t))return{suppressions:[],compatibility:og([]),warnings:[]};let n=[],r=[];for(let o of rQ(t).sort()){if(!o.endsWith(".json"))continue;let s=sg(t,o),a=`${jE}/${o}`,c;try{c=JSON.parse(O(s,"suppression record"))}catch{r.push({path:a,state:"malformed",reason:"malformed JSON"});continue}let l=cQ(c,o.slice(0,-5));if("error"in l){r.push({path:a,state:l.state,reason:l.error});continue}r.push({path:a,state:l.state}),n.push(l.suppression)}let i=og(r);return{suppressions:n,compatibility:i,warnings:i.issues.map(o=>`${o.path}: ${o.reason} \u2014 ignored`)}}function lQ(e){return{...typeof e.id=="string"?{id:e.id}:{},...typeof e.check=="string"?{check:e.check}:{},...typeof e.file=="string"?{file:e.file}:{},reason:e.reason,...typeof e.expiresAt=="string"?{expiresAt:e.expiresAt}:{},...typeof e.createdAt=="string"?{createdAt:e.createdAt}:{},...e.decision?{decision:e.decision}:{}}}var ra;function VCe(e,t){let n=ra;ra=e;try{return t()}finally{ra=n}}function HE(e){ra?.onCheckStart?.(e)}function GE(e){ra?.onCheckComplete?.(e)}var uQ=["echo","incomplete-migration","co-change-partner","twin-partner","coverage-contract","architecture","doc-reference","unused-params","new-dead","baseline"];function dQ(e,t={}){let n=t.base??"HEAD",{minTogether:r=6,minConfidence:i=.6,maxEchoChecks:o=Number.POSITIVE_INFINITY,maxHelpers:s=Number.POSITIVE_INFINITY,minSimilarity:a=.8,includeBaseline:c=!1,scanLimit:l}=t,u=t.semantic!==!1,d=t.historyMode??"bounded",m=new Set(t.skip??[]),f=$E(e.config.projectRoot),p=xr(e,{base:n}),g=lo(e,{base:n,plan:p}),y=g.changedFiles,h=new Set(y),S=new Set(p.changedFileLines),b=new Set([...h,...S]),R=Ws(p,y),x=uo({projectRoot:e.config.projectRoot,base:n,preloadPaths:R},t.baseContentRuntime);for(let I of R){let P=x(I);if(P.state==="unavailable")throw new Error(`Base content unavailable for ${I}: ${P.reason}`)}let v=GQ(e.config.projectRoot,n,p,x),C={base:n,changedFiles:y,changedSymbols:g.changedSymbols.length,checksRun:[],skipped:[],suppressed:[],policyEscalations:[],outcome:"pass",suppressionSummary:QE(),findings:[],attributionNotes:g.attributionNotes,evidenceTiers:g.evidenceTiers,rootCauseGroups:[],recordCompatibility:{suppressions:f.compatibility},note:g.summary.note};if(y.length===0)return C;let w=(I,P)=>{if(m.has(I)){C.skipped.push({check:I,reason:"skipped via --skip"});return}let _=C.findings.length,se=C.skipped.length,ee=C.checksRun.length;HE(I);try{D(`diff-gate.check.${I}`,P,()=>({check:I,changedFiles:y.length,changedSymbols:g.changedSymbols.length,findingsAdded:C.findings.length-_,skippedAdded:C.skipped.length-se,checksRunAdded:C.checksRun.length-ee}))}finally{GE(I)}};return w("echo",()=>SQ(e,g.changedSymbols,h,v,o,a,l,u,C)),w("incomplete-migration",()=>wQ(e,n,p,s,l,u,x,C)),w("co-change-partner",()=>EQ(e,b,r,i,d,C)),w("twin-partner",()=>DQ(e,g.changedSymbols,h,l,C)),w("coverage-contract",()=>PQ(e,b,C)),w("architecture",()=>VQ(e,C)),w("doc-reference",()=>AQ(e,h,S,p.changedRanges,p.renamedFiles,C)),w("unused-params",()=>OQ(e,y,C)),w("new-dead",()=>{let I=g.evidenceTiers.filter(P=>P.state==="failed");if(I.length>0){C.skipped.push({check:"new-dead",reason:`required consumer evidence unavailable: ${I.map(P=>P.tier).join(", ")}`});return}BQ(e,g.changedSymbols,v,C)}),c&&w("baseline",()=>UQ(e,C)),gQ(C,[...e.config.suppressions??[],...f.suppressions],e.config.projectRoot,f.compatibility.complete),C.rootCauseGroups=pQ(C.findings),C}function mQ(e){return JE(e)!==void 0}function JE(e){if(e.checksRun.length===0&&e.note===zs)return"git diff unavailable - zero checks ran; the gate fails closed";if(!Array.isArray(e.evidenceTiers))return"required consumer evidence status unavailable";let t=e.evidenceTiers.filter(n=>n.state==="failed");if(t.length!==0)return`required consumer evidence unavailable: ${t.map(n=>`${n.tier} (${n.reason})`).join("; ")}`}function fQ(e){return e.filter(t=>!t.advisory)}function pQ(e){let t=new Map;for(let n of e){let r=n.groupKey??`${n.check}:${n.id}`,i=t.get(r);i||(i={groupKey:r,check:n.check,severity:n.severity,actionTier:n.actionTier,sourceAnalyzer:n.sourceAnalyzer,rootCauseKey:n.rootCauseKey,count:0,findingIds:[],files:new Set,relatedFiles:new Set,message:n.message,remediation:n.remediation},t.set(r,i)),i.count+=1,i.findingIds.push(n.id),i.severity=YE(i.severity,n.severity),i.actionTier=XE(i.actionTier,n.actionTier),n.file&&i.files.add(n.file);for(let o of n.relatedFiles??[])i.relatedFiles.add(o)}return[...t.values()].map(n=>({...n,files:[...n.files].sort(),relatedFiles:[...n.relatedFiles].sort()})).sort((n,r)=>r.count-n.count||Jl(r.severity)-Jl(n.severity)||n.groupKey.localeCompare(r.groupKey))}function YE(e,t){return Jl(t)>Jl(e)?t:e}function Jl(e){return e==="error"?2:e==="warning"?1:0}function XE(e,t){return e?t&&qE(t)>qE(e)?t:e:t}function qE(e){return e==="direct"?2:e==="signal"?1:0}function gQ(e,t,n,r){let i=e.suppressionSummary??QE();if(e.suppressionSummary=i,e.policyEscalations??=[],t.length===0||e.findings.length===0){e.outcome=e.findings.length>0?"findings":"pass";return}let o=[...e.findings],s=new Map,a=new Map,c=Date.now(),l=p=>{try{return KE("sha256").update(de(n,p)).digest("hex")}catch{return}};for(let p of o){let g=t.filter(h=>hQ(h,p));if(g.length===0)continue;let y=new Set;for(let h of g){let S=jR(h,p,{now:c,contentHash:l});if(S.kind==="accepted"&&r){s.set(p.id,h);break}let b=S.kind==="accepted"?["suppression-record-coverage-incomplete"]:S.reasons;for(let R of b)y.add(R);S.kind==="expired"&&(i.expiredCount+=1),S.kind==="invalidated"&&(i.invalidatedCount+=1),b.includes("legacy-unadjudicated")&&(i.legacyUnadjudicatedCount+=1)}s.has(p.id)||a.set(p.id,y)}let u=yQ(o),d=bQ(o,s),m=new Set;for(let[p,g]of d){let y=u.get(p)??g;Yc(g,y)&&m.add(p)}let f=[];for(let p of o){let g=s.get(p.id);if(g&&!m.has(p.check)){e.suppressed.push({finding:p,suppression:g}),i.automaticSuppressionCount+=1;continue}f.push(p);let y=a.get(p.id)??new Set;g&&m.has(p.check)&&y.add("automatic-suppression-rate-anomaly"),y.size>0&&e.policyEscalations.push({findingId:p.id,check:p.check,...g?.id?{suppressionId:g.id}:{},reasons:[...y].sort()})}e.findings=f,i.policyEscalationCount=e.policyEscalations.length,e.outcome=e.findings.length>0?"findings":e.suppressed.length>0?"pass-with-suppressions":"pass"}function hQ(e,t){return!e.reason||e.reason.trim()===""||e.id&&e.id!==t.id&&!t.legacySuppressionIds?.includes(e.id)||e.check&&e.check!==t.check||e.file&&e.file!==t.file?!1:!!(e.id||e.check)}function QE(){return{automaticSuppressionCount:0,policyEscalationCount:0,expiredCount:0,invalidatedCount:0,legacyUnadjudicatedCount:0}}function yQ(e){let t=new Map;for(let n of e)t.set(n.check,(t.get(n.check)??0)+1);return t}function bQ(e,t){let n=new Map;for(let r of e)t.has(r.id)&&n.set(r.check,(n.get(r.check)??0)+1);return n}function pn(e,t){e.findings.push({...t,suppressionHint:`scip-query: ignore ${t.check} ${t.id} -- <reason>`})}function SQ(e,t,n,r,i,o,s,a,c){c.checksRun.push("echo");for(let l of t.slice(0,i)){if(!ye(l.symbol)||r(l))continue;let u=Vp(e,l.symbol,{maxLoc:15,scanLimit:s}).filter(h=>!n.has(h.file)).slice(0,5).map(h=>({otherFile:h.file,otherShort:h.shortName,otherSymbol:h.symbol,similarity:1,similarityBasis:"exact-body",sharedEvidence:[`exact normalized body (${h.loc} LOC)`]}));if(u.length>0){let h=je("echo",l.symbol,l.file),S=je("echo",l.symbol,l.file,...u.map(R=>`${R.otherSymbol}|${R.otherFile}`).sort()),b=u[0];pn(c,{id:h,legacySuppressionIds:S===h?void 0:[S],groupKey:h,actionTier:"direct",check:"echo",severity:"warning",evidence:"heuristic",confidence:1,file:l.file,symbol:l.symbol,relatedFiles:[...new Set(u.map(R=>R.otherFile))].sort(),sourceAnalyzer:"duplicate-bodies",rootCauseKey:`${l.symbol}:${b.otherSymbol}`,message:VE(l,u),why:zE(l,u),remediation:WE("direct",l.shortName,b.otherShort)});continue}let d=El(e,l.symbol,{minSimilarity:o,limit:5,scanLimit:s,semantic:a,sourceCandidateMode:"target-pruned"}),m=[];for(let h of d){let S=h.fileA===l.file?h.fileB:h.fileA,b=h.fileA===l.file?h.shortNameB:h.shortNameA,R=h.fileA===l.file?h.symbolB:h.symbolA;n.has(S)||m.push({otherFile:S,otherShort:b,otherSymbol:R,similarity:h.similarity,similarityBasis:h.similarityBasis??"callees",sharedEvidence:h.sharedCallees})}if(m.length===0)continue;let f=m[0],p=je("echo",l.symbol,l.file,...m.map(h=>`${h.otherSymbol}|${h.otherFile}`).sort()),g=je("echo",l.symbol,l.file),y=xQ(l,m);pn(c,{id:g,legacySuppressionIds:p===g?void 0:[p],groupKey:g,actionTier:y,check:"echo",severity:"warning",evidence:"heuristic",confidence:f.similarity,file:l.file,symbol:l.symbol,relatedFiles:[...new Set(m.map(h=>h.otherFile))].sort(),message:VE(l,m),why:zE(l,m),remediation:WE(y,l.shortName,f.otherShort)})}t.length>i&&c.skipped.push({check:"echo",reason:`echo check capped at ${i} of ${t.length} changed symbols`})}function xQ(e,t){return t.some(r=>RQ(e.symbol,r))?"direct":"signal"}function RQ(e,t){if(t.similarityBasis==="exact-body")return!0;if(t.similarityBasis!=="source-tokens"||t.similarity<.98||t.sharedEvidence.length>8)return!1;let n=T(e),r=T(t.otherSymbol);return!n||!r?!1:n===r?!0:IQ(t.sharedEvidence)?!1:CQ(n,r)}function CQ(e,t){let n=UE(e),r=UE(t);if(n.length===0||r.length===0)return!1;let i=new Set(r),o=n.filter(s=>i.has(s)).length;return o>=2&&o/Math.min(n.length,r.length)>=.5}function UE(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)}var vQ=new Set(["bytes","crypto","hex","num","random","secret","to","token"]);function IQ(e){return e.length>=3&&e.every(t=>vQ.has(t.toLowerCase()))}function VE(e,t){let n=t[0],r=Math.round(n.similarity*100);return t.length===1?`${e.shortName} (${e.file}) is ${r}% similar to established ${n.otherShort} (${n.otherFile})`:`${e.shortName} (${e.file}) resembles ${t.length} established symbol(s); strongest is ${r}% similar to ${n.otherShort} (${n.otherFile})`}function zE(e,t){let n=[`${e.shortName} was changed in this diff.`];for(let r of t.slice(0,3))n.push(`${r.otherShort} is outside this diff and scored ${Math.round(r.similarity*100)}% similar by ${r.similarityBasis} evidence.`),n.push(`Shared evidence: ${r.sharedEvidence.slice(0,5).join(", ")||"(none listed)"}.`);return t.length>3&&n.push(`${t.length-3} additional similar match(es) grouped into this finding.`),n}function WE(e,t,n){return e==="direct"?`Extract or reuse the shared behavior with ${n}, or keep the duplicate with a suppression reason.`:`Review whether ${t} is intentionally parallel to the established implementation(s); extract shared behavior only if the product semantics match.`}function wQ(e,t,n,r,i,o,s,a){let c=tg(e,{base:t,maxHelpers:r,diffPlan:n,scanLimit:i,semantic:o,baseContentResultAt:s});if(!c.available){a.skipped.push({check:"incomplete-migration",reason:c.note??"no git history"});return}a.checksRun.push("incomplete-migration"),c.note&&a.skipped.push({check:"incomplete-migration",reason:c.note});for(let l of c.findings){let u=l.leftovers.map(h=>`${h.shortName} (${h.file}, ${Math.round(h.containment*100)}% helper / ${Math.round(h.siteCoverage*100)}% site, ${h.migrationScope})`).join(", "),d=l.leftovers.map(h=>`${h.shortName}: ${h.migrationScope} (${h.migrationScopeReasons[0]})`).join("; "),m=[...l.migratedFiles,...l.leftovers.map(h=>h.file)],f=l.leftovers.length===0?void 0:Math.max(...l.leftovers.map(h=>Math.min(h.containment,h.siteCoverage))),p=l.leftovers.some(h=>h.migrationScope==="possible-subtype"),g=je("incomplete-migration",l.helperSymbol,l.helperFile,m.join("|")),y=je("incomplete-migration",l.helperSymbol,l.helperFile);pn(a,{id:y,legacySuppressionIds:g===y?void 0:[g],check:"incomplete-migration",severity:"warning",evidence:"heuristic",confidence:f,file:l.helperFile,symbol:l.helperSymbol,relatedFiles:m,message:`new helper ${l.helperShortName} (${l.helperFile}) is wired into ${l.migratedFiles.length} file(s), but ${l.leftovers.length} similar un-migrated site(s) remain: ${u}`,why:[`${l.helperShortName} is new in this diff and already referenced by ${l.migratedFiles.join(", ")}.`,`Helper shape: ${l.helperShape}; ${l.specificHelperCalleeCount}/${l.helperCalleeCount} helper callees are specific enough to score.`,`Unchanged site(s) still contain the helper's callee pattern: ${u}.`,`Migration scope hints: ${d}.`],remediation:p?`Migrate same-scope sites to ${l.helperShortName}; review possible subtype/variant sites before applying the helper.`:`Migrate the remaining sites to ${l.helperShortName}, or confirm they are intentionally different.`})}}function EQ(e,t,n,r,i,o){let s=ft(e,{historyMode:i}).directionalCoChangePairsForFiles(t,{minTogether:n,minConfidence:0,maxFilesPerCommit:20});if(!s){o.skipped.push({check:"co-change-partner",reason:"no git history"});return}o.checksRun.push("co-change-partner");let a=new Set,c;for(let l of s){let u=t.has(l.fileA),d=t.has(l.fileB);if(u===d)continue;let m=u?l.fileA:l.fileB,f=u?l.fileB:l.fileA,p=u?l.changesA:l.changesB,g=p>0?l.together/p:0;if(g<r||kp(f)||kp(m)||!Yl(`${e.config.projectRoot}/${f}`))continue;let y=`${m}|${f}`;if(a.has(y))continue;a.add(y);let h=je("co-change-partner",m,f,String(l.together)),S=je("co-change-partner",m,f),b=Tp(m,f),R=Fp({fileA:m,fileB:f,together:l.together,confidence:g,commitScope:l.commitScope,recency:l.recency,subjectContext:l.subjectContext},b,(c??=_p(e))(m,f)),x=[m,f].sort().join("|");o.findings.push({id:S,legacySuppressionIds:h===S?void 0:[h],check:"co-change-partner",severity:"warning",evidence:"change-graph",actionTier:"signal",groupKey:`co-change-partner:${x}`,confidence:g,file:m,relatedFiles:[f],sourceAnalyzer:"co-change",rootCauseKey:x,partnerClass:b.partnerClass,partnerClassReasons:b.reasons,commitScope:l.commitScope,recency:l.recency,focusedTogether:l.focusedTogether,broadTogether:l.broadTogether,broadCommitRatio:l.broadCommitRatio,lastTogetherAt:l.lastTogetherAt,recentTogether:l.recentTogether,subjectContext:l.subjectContext,...R?{declaredCouplingSuggestion:R}:{},message:`${m} changed, but ${f} did not \u2014 they change together ${l.together}x (${Math.round(g*100)}% of the time)`,why:[`${m} is in this diff and ${f} is not.`,`Git history shows ${l.together} co-change(s), which is ${Math.round(g*100)}% of changes to the edited side.`,`History context: ${kQ(l)}.`,`Subject context: ${TQ(l.subjectContext)}.`,...FQ(l),`Partner class: ${b.partnerClass} (${b.reasons.join("; ")}).`],remediation:R?`Update ${f} alongside this change, declare the coupling "${R.name}", or confirm the coupling no longer holds.`:`Update ${f} alongside this change, or confirm the coupling no longer holds.`})}}function DQ(e,t,n,r,i){i.checksRun.push("twin-partner");let o=fo(e,{scanLimit:r}).filter(c=>c.relationship==="divergent"||c.relationship==="identical");if(o.length===0)return;let s=new Map;for(let c of o)for(let l of c.members)s.set(l.symbol,c);let a=new Set;for(let c of t){if(!ye(c.symbol))continue;let l=s.get(c.symbol);if(!l)continue;let u=l.members.filter(p=>p.symbol!==c.symbol&&!n.has(p.file));if(u.length===0)continue;let d=[c.symbol,...u.map(p=>p.symbol)].sort().join("|");if(a.has(d))continue;a.add(d);let m=u[0],f=je("twin-partner",c.symbol,c.file,m.symbol);pn(i,{id:f,groupKey:`twin-partner:${d}`,check:"twin-partner",severity:"warning",evidence:"heuristic",actionTier:"signal",advisory:!0,confidence:l.relationship==="identical"?1:Math.max(0,1-l.maxDivergence),file:c.file,symbol:c.symbol,relatedFiles:u.map(p=>p.file).sort(),sourceAnalyzer:"twin-drift",rootCauseKey:d,message:`${c.shortName} (${c.file}) changed but its same-name twin ${m.shortName} (${m.file}) did not \u2014 verify the change shouldn't apply to both, or consolidate them.`,why:[`${c.symbol} is in this diff.`,`${m.symbol} shares its (near-)name and is classified '${l.relationship}' with it, but ${m.file} is not in this diff.`,l.relationship==="divergent"?`The two bodies already diverge (~${Math.round(l.maxDivergence*100)}% token difference) \u2014 this diff may widen or narrow that drift.`:"The two bodies were byte-identical before this diff.","Advisory: twin-partner never fails the gate by itself \u2014 see the twin-partner entry in the diff-gate checks table."],remediation:`Update ${m.file} alongside this change, consolidate ${c.shortName}/${m.shortName} into one helper, or confirm the twin should diverge on purpose.`})}}function PQ(e,t,n){n.checksRun.push("coverage-contract");let r=e.config.coverageContracts??[];for(let i of r){if(!RE(i,t))continue;let o=Wp(e,i);if(o.status==="ok")continue;let s=je("coverage-contract",i.name,i.file);pn(n,{id:s,groupKey:`coverage-contract:${i.name}`,check:"coverage-contract",severity:o.status==="unavailable"?"warning":"error",evidence:"graph-fact",actionTier:"direct",file:i.file,sourceAnalyzer:"coverage-contracts",rootCauseKey:i.name,message:CE(o),why:[`Contract "${i.name}" declares that ${i.file} (${i.keys.type}) must track ${i.mustEqual.type}.`,o.status==="unavailable"?`The declared side could not be evaluated: ${o.unavailableReason}.`:`Missing: ${o.missing.join(", ")||"none"}. Extra: ${o.extra.join(", ")||"none"}.`,"Either side of this contract changed in this diff."],remediation:o.status==="unavailable"?"Investigate why the declared key set could not be parsed (see the reason above) \u2014 do not treat this as a pass.":`Update ${i.file} so its ${i.keys.type==="object-literal-keys"||i.keys.type==="string-array"?i.keys.identifier:i.keys.marker} matches ${i.mustEqual.type}, or fix the ground-truth source if the declared set is right.`})}}function kQ(e){return`${e.commitScope}/${e.recency}; ${e.focusedTogether} focused, ${e.broadTogether} broad-sweep (${Math.round(e.broadCommitRatio*100)}% broad), ${e.recentTogether} recent, last ${_Q(e.lastTogetherAt)}`}function TQ(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",r=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(i=>`"${i}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${r}; external issue/PR labels ${e.externalIssueLabelStatus}`}function FQ(e){let t=[];return e.commitScope==="broad-sweep"&&t.push("Broad-sweep history is weaker than focused co-edits; confirm this is a real coordination contract."),e.recency==="stale"&&t.push("The pair has no co-change in the recent history window; confirm the coupling still holds."),t}function _Q(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}var ag=3;function AQ(e,t,n,r,i,o){o.checksRun.push("doc-reference");let s=Hn.referenceTargets(e,t,r);if(s.size===0)return;let a=new Set(i.map(l=>l.from)),c=[];for(let l of Xw(e,s))n.has(l.doc)||Hl(e,l.doc)||c.push(LQ(e,l,a));for(let l of MQ(c))pn(o,l)}function LQ(e,t,n){let r=t.citedClaims.length>0?t.citedClaims:Hn.citationContexts(e,t.doc,t.cited),i=Hn.classifyCitation(r),o=Hn.hasLineAnchoredCitation(t.citations),s=t.cited.some(d=>n.has(d)||!Yl(`${e.config.projectRoot}/${d}`)),a=!(o||s),c=t.cited[0]??"",l=je("doc-reference",t.doc,t.cited.join("|")),u=je("doc-reference",t.doc,c);return{id:u,legacySuppressionIds:l===u?void 0:[l],check:"doc-reference",severity:"warning",evidence:"change-graph",actionTier:i.actionTier,groupKey:`doc-reference:${c}`,rootCauseKey:c,confidence:1,file:t.doc,relatedFiles:t.cited,citationKind:i.citationKind,citationKindReasons:i.reasons,citedClaims:r,...a?{advisory:!0}:{},message:`${t.doc} cites ${t.cited.join(", ")} as ${Hn.citationKindLabel(i.citationKind)} \u2014 changed in this diff, doc untouched`,why:[`${t.cited.join(", ")} changed in this diff.`,`${t.doc} cites the changed file(s) but was not updated in the same diff.`,...i.reasons.map(d=>`Citation kind evidence: ${d}`),a?"Advisory: bare file-mention citation (no line anchor, cited file still present under the same path) \u2014 21.2 calibration found this citation shape low-precision; verify at your leisure.":o?"Blocking: citation includes a line anchor that may now point at the wrong lines.":"Blocking: the cited file was deleted or renamed in this diff \u2014 the citation almost certainly needs an update."],remediation:Hn.citationRemediation(i.citationKind,t.doc)}}function MQ(e){let t=new Map;for(let r of e){let i=r.rootCauseKey??"",o=t.get(i);o?o.push(r):t.set(i,[r])}let n=[];for(let[r,i]of t)i.length<=ag?n.push(...i):n.push(NQ(r,i));return n}function NQ(e,t){let n=[...t].sort((u,d)=>(u.file??"").localeCompare(d.file??"")),r=n.slice(0,ag).map(u=>({doc:u.file??"",citedClaims:u.citedClaims??[]})),i=n.length-r.length,o=n.every(u=>u.advisory===!0),s=n.reduce((u,d)=>YE(u,d.severity),"info"),a=n.reduce((u,d)=>XE(u,d.actionTier),void 0),c=n.map(u=>u.file??"").filter(u=>u.length>0),l=[...new Set(n.flatMap(u=>[u.id,...u.legacySuppressionIds??[]]))];return{id:je("doc-reference","hub-cluster",e),memberFindingIds:l,check:"doc-reference",severity:s,evidence:"change-graph",actionTier:a,groupKey:`doc-reference:${e}`,rootCauseKey:e,confidence:1,file:r[0]?.doc,relatedFiles:[e],citationCount:n.length,citationExemplars:r,suppressedCount:i,...o?{advisory:!0}:{},message:`${e} is cited by ${n.length} doc(s) changed in this diff, doc(s) untouched \u2014 showing ${r.length} example(s), ${i} more damped`,why:[`${e} changed in this diff.`,`${n.length} doc(s) cite it but were not updated in the same diff: ${c.join(", ")}.`,...r.map(u=>`Example \u2014 ${u.doc}: ${u.citedClaims[0]??"(no captured citation text)"}`),`${i} additional doc(s) also cite this file, past the per-hub-file cascade cap (${ag}) \u2014 not silently dropped: counted in citationCount/suppressedCount and individually addressable via memberFindingIds.`,o?"Advisory: every citation in this cluster is a bare file-mention (no line anchor, cited file still present).":"Blocking: at least one citation in this cluster is line-anchored or cites a deleted/renamed file."],remediation:`Review the ${r.length} example doc(s) above; ${n.length} total doc(s) cite ${e} the same way \u2014 see citationExemplars and memberFindingIds in --json for the complete list.`}}function OQ(e,t,n){n.checksRun.push("unused-params");for(let r of rg(e,{files:t,limit:50})){let i=je("unused-params",r.symbol,r.file,r.unusedTrailing.join("|")),o=je("unused-params",r.symbol,r.file);pn(n,{id:o,legacySuppressionIds:i===o?void 0:[i],check:"unused-params",severity:"warning",evidence:"heuristic",confidence:.85,file:r.file,startLine:r.startLine,endLine:r.endLine,symbol:r.symbol,message:`${r.shortName} (${r.file}) has trailing unused parameter(s): ${r.unusedTrailing.join(", ")}`,why:[`${r.shortName} is in a changed file.`,`The trailing parameter(s) ${r.unusedTrailing.join(", ")} are not referenced in the function body.`],remediation:"Drop the unused trailing parameters and their call-site arguments."})}}function BQ(e,t,n,r){r.checksRun.push("new-dead");let i=new F(e),o=Si(e.config.projectRoot),s=o.length>1;for(let a of t){if(n(a)||a.fanIn>0||i.fileKind(a.file)==="test"||Ue(e,a.file)||Re(e,a.symbol,a.file)||HQ(a.symbol))continue;let c=je("new-dead",a.symbol,a.file),l=s&&jQ(o,a.file)&&$Q(e,a.symbol);pn(r,{id:c,check:"new-dead",severity:"warning",evidence:l?"heuristic":"graph-fact",confidence:l?.4:.9,file:a.file,symbol:a.symbol,message:l?`${a.shortName} (${a.file}) unconfirmed (cross-package ambiguous-name resolution gap): zero indexed consumers found, but this name is ambiguous project-wide and lives in a workspace package \u2014 verify manually before treating as dead`:`${a.shortName} (${a.file}) was changed but has zero indexed consumers`,why:l?[`${a.shortName} is a changed production symbol in a workspace package.`,"The index, semantic, and source-fallback layers all report zero consumers for this symbol.","Its leaf name is ambiguous project-wide (a same-named definition exists elsewhere), and cross-package consumers reached only through a re-exporting barrel are a known unresolvable shape for this tool \u2014 see docs/plans/2026-07-02-followups.md item 2."]:[`${a.shortName} is a changed production symbol.`,"The index reports zero consumers for this symbol.","The symbol is not in a detected entry surface or configured live root."],remediation:l?"Verify with a direct code search before deleting; this tool cannot confidently resolve this symbol.":"Wire it up, or remove it before it becomes permanent dead code."})}}function jQ(e,t){return e.some(n=>t===n.relativeDir||t.startsWith(`${n.relativeDir}/`))}function $Q(e,t){let n=T(t);return n?(kn(e).get(n)?.length??0)>1:!1}function HQ(e){if(be(e)!=="type")return!1;let t=T(e);return t.startsWith("_Assert")||t.startsWith("Assert")}function GQ(e,t,n,r){let i=new Map(n.renamedFiles.map(s=>[s.to,s.from])),o=r??uo({projectRoot:e,base:t,preloadPaths:Ws(n)});return s=>{let a=i.get(s.file)??s.file,c=T(s.symbol);if(!c)return!1;let l=o(a);if(l.state==="unavailable")throw new Error(`Base content unavailable for ${a}: ${l.reason}`);return l.state==="present"&&qQ(l.content,c)}}function qQ(e,t){return new RegExp(`\\b${H(t)}\\b`).test(e)}function UQ(e,t){if(!Yl(po(e))){t.skipped.push({check:"baseline",reason:"no .scipquery-baseline.json \u2014 run health --write-baseline to enable"});return}t.checksRun.push("baseline");let n=Zp(e);for(let r of n.newFindings.filter(i=>!i.startsWith(Wt))){let i=Hp(r),o=je("baseline",r);pn(t,{id:o,groupKey:`baseline:${i.sourceAnalyzer}:${i.rootCauseKey}`,check:"baseline",severity:"error",evidence:"baseline",actionTier:i.actionTier,confidence:1,file:i.file,relatedFiles:i.relatedFiles.length>0?i.relatedFiles:void 0,sourceAnalyzer:i.sourceAnalyzer,rootCauseKey:i.rootCauseKey,message:`new ${i.label} vs committed baseline: ${r}`,why:["A committed health baseline exists.","The current health result contains a finding not present in that baseline.",`Underlying analyzer: ${i.sourceAnalyzer}.`,`Inherited action tier: ${i.actionTier}.`,`Root cause key: ${i.rootCauseKey}.`,...i.why],remediation:i.remediation})}}function VQ(e,t){if(!vI(e.config.architecture)){t.skipped.push({check:"architecture",reason:"no closed architecture dependency rows, requireCompletePolicy rule, or requireAcyclic rule configured"});return}if(!Yl(po(e))){t.skipped.push({check:"architecture",reason:"no .scipquery-baseline.json \u2014 run health --write-baseline to enable"});return}t.checksRun.push("architecture");let n=ME(e);for(let r of n.newFindings){let i=Hp(r),o=je("architecture",r);pn(t,{id:o,groupKey:`architecture:${i.rootCauseKey}`,check:"architecture",severity:"error",evidence:"baseline",actionTier:"direct",confidence:1,sourceAnalyzer:"architecture",rootCauseKey:i.rootCauseKey,message:`new ${i.label} vs committed baseline: ${r}`,why:["The project declares an enforceable architecture rule.","The current boundary graph contains a violation not present in the committed baseline.",...i.why],remediation:i.remediation})}}function je(e,...t){return`SQ${KE("sha256").update([e,...t].join("\0")).digest("hex").slice(0,12).toUpperCase()}`}import{dirname as zQ,isAbsolute as WQ,relative as KQ,resolve as JQ}from"path";var YQ=new Set(ln());function XQ(e,t){return`tests/generated/twin-ab/${ZE(e)}-vs-${ZE(t)}.test.ts`}function ZE(e){return(e.split(/[/#]/).pop()||e).replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"symbol"}function QQ(e,t,n,r){let{refA:i,refB:o,outFile:s}=typeof t=="string"?{refA:t,refB:n,outFile:r}:t;if(typeof i!="string"||typeof o!="string"||typeof s!="string")throw new TypeError("twinAb requires refA, refB, and outFile.");if(!WQ(s))throw new TypeError("twinAb outFile must be an absolute path.");let a=eD(e,i);if(!a.ok)return a;let c=eD(e,o);if(!c.ok)return c;let l=a.symbol.paramCount===null||c.symbol.paramCount===null?null:a.symbol.paramCount===c.symbol.paramCount,u=e4(a.symbol,c.symbol,e.config.projectRoot,s,l);return{ok:!0,a:a.symbol,b:c.symbol,signatureCompatible:l,testSource:u}}function eD(e,t){let r=Or(e,t).match;if(!r)return{ok:!1,reason:`${t} does not resolve to an indexed symbol.`};let o=e.get("SELECT kind FROM global_symbols WHERE id = ?",r.symbolId)?.kind??null;if(!(o!==null?YQ.has(o):ae(r.symbol)))return{ok:!1,reason:`${t} resolves to ${E(r.symbol)}${o!==null?` with SCIP kind ${Fs(o)}`:""} \u2014 twin-ab compares call outputs, so both referents must be functions or methods.`};if(!ea(e,r))return{ok:!1,reason:`${t} (${E(r.symbol)} at ${r.relativePath}:${r.startLine+1}) is not exported \u2014 twin-ab needs an importable named binding for both twins.`};let a=e.get("SELECT documentation FROM global_symbols WHERE id = ?",r.symbolId),c=En(Dn(a?.documentation??null));return{ok:!0,symbol:{ref:t,symbol:r.symbol,shortName:T(r.symbol)||E(r.symbol),file:r.relativePath,startLine:r.startLine,signature:c,paramCount:c?ZQ(c):null}}}function ZQ(e){let t=e.indexOf("(");if(t===-1)return null;let n=0,r=-1;for(let a=t;a<e.length;a+=1){let c=e[a];if(c==="(")n+=1;else if(c===")"&&(n-=1,n===0)){r=a;break}}if(r===-1)return null;let i=e.slice(t+1,r).trim();if(!i)return 0;let o=1,s=0;for(let a of i)a==="("||a==="["||a==="{"?s+=1:a===")"||a==="]"||a==="}"?s=Math.max(0,s-1):a===","&&s===0&&(o+=1);return o}function tD(e,t,n){let r=zQ(t),i=JQ(e,n),s=KQ(r,i).replace(/\\/g,"/").replace(/\.tsx?$/,".js");return s.startsWith(".")?s:`./${s}`}function e4(e,t,n,r,i){let o=tD(n,r,e.file),s=tD(n,r,t.file),a=i===null?"Signature comparison: unknown (one or both signatures unavailable in the index) \u2014 check by hand.":i?"Signature comparison: param counts match.":"Signature comparison: param counts DIFFER \u2014 twins may not be directly comparable; check by hand.";return`/**
|
|
806
|
+
* Generated by 'scip-query twin-ab'. scip-audit integrity scenario.
|
|
807
|
+
* ("cross-examine same-concept twins"): where one concept is computed in
|
|
808
|
+
* more than one place, feed both the same input and require the same
|
|
809
|
+
* answer. Disagreement between twins means at least one is wrong \u2014
|
|
810
|
+
* determine which before consolidating.
|
|
811
|
+
*
|
|
812
|
+
* Twin A: ${e.shortName} (${e.file}:${e.startLine+1})
|
|
813
|
+
* ${e.signature??"(signature unavailable)"}
|
|
814
|
+
* Twin B: ${t.shortName} (${t.file}:${t.startLine+1})
|
|
815
|
+
* ${t.signature??"(signature unavailable)"}
|
|
816
|
+
* ${a}
|
|
817
|
+
*
|
|
818
|
+
* Fill in the TODO input table below with inputs both twins should agree
|
|
819
|
+
* on, then run this file with vitest.
|
|
820
|
+
*/
|
|
821
|
+
import { describe, expect, it } from 'vitest';
|
|
822
|
+
import { ${e.shortName} as twinA } from '${o}';
|
|
823
|
+
import { ${t.shortName} as twinB } from '${s}';
|
|
824
|
+
|
|
825
|
+
// TODO: fill in shared inputs both twins should agree on \u2014 one arg array per call.
|
|
826
|
+
const inputs: any[][] = [
|
|
827
|
+
// [/* arg1, arg2, ... */],
|
|
828
|
+
];
|
|
829
|
+
|
|
830
|
+
// Cast to a variadic signature so the input table can hold any arg shape \u2014
|
|
831
|
+
// the real twins have fixed, non-rest parameter lists, and TS rejects
|
|
832
|
+
// spreading a generic args array into those (TS2556) even when the array
|
|
833
|
+
// itself is 'any'; casting the callee's signature, not the args, satisfies
|
|
834
|
+
// the checker without weakening the twins' real exported types elsewhere.
|
|
835
|
+
const callA = twinA as (...callArgs: any[]) => any;
|
|
836
|
+
const callB = twinB as (...callArgs: any[]) => any;
|
|
837
|
+
|
|
838
|
+
describe.skipIf(inputs.length === 0)('twin-ab: ${e.shortName} vs ${t.shortName}', () => {
|
|
839
|
+
it.each(inputs)('agrees on input %#', (...args) => {
|
|
840
|
+
expect(callA(...args)).toEqual(callB(...args));
|
|
841
|
+
});
|
|
842
|
+
});
|
|
843
|
+
`}var nD={caller:3,"entry-surface":2,rooted:1},t4=/not\s*yet\s*implement|not\s*implement|unimplement|\bnyi\b|\btodo\b|\bstub\b|not\s*supported|coming\s*soon/i,n4=/^throw\s+new\s+[\w.]*Error\s*\(([\s\S]*)\)\s*;?$/,r4=/^return(\s+(null|undefined|false|0|''|""|``|\[\]|\{\}))?\s*;?$/,i4=/\/\/\s*TODO\b|\/\*\s*TODO\b/i,o4=/(?:=>|\))\s*(?::\s*[^{;=]+)?\s*\{\s*\}\s*;?\s*$/;function s4(e,t={}){let{scope:n,limit:r=30,scanLimit:i,semantic:o=!0}=t,s=new F(e),a=fe(s.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),c=[];for(let f of a){let p=c4(e,f);p&&c.push(p)}if(c.length===0)return[];let l=m4(e,c,a),u=c.filter(f=>!l.has(f.def.symbol));if(u.length===0)return[];let d=Bn(e,s).forDefinitions(u.map(f=>f.def),{semantic:o}),m=[];for(let f of u){let g=d.get(f.def.symbolId)?.realConsumers.length??0,y=a4(e,f.def,g);y&&m.push({symbol:f.def.symbol,shortName:E(f.def.symbol),file:f.def.relativePath,startLine:f.def.startLine,endLine:f.def.endLine,loc:j(f.def),stubKind:f.stubKind,reachability:y,callerFanIn:g,stubText:f.stubText})}return m.sort((f,p)=>nD[p.reachability]-nD[f.reachability]||p.callerFanIn-f.callerFanIn||f.file.localeCompare(p.file)||f.startLine-p.startLine),r?m.slice(0,r):m}function a4(e,t,n){return n>0?"caller":Re(e,t.symbol,t.relativePath)?"rooted":Ue(e,t.relativePath)?"entry-surface":null}function c4(e,t){let n=Gn(e,t);if(!n)return null;let r=fn(n),i=r.trim();if(i==="")return!d4(n)||!ea(e,t)?null:{def:t,stubKind:"empty-body",stubText:"(empty body)"};let o=Fo(r),s=Tt(r),a=l4(o,s);if(a.length!==1)return null;let c=a[0];return u4(c)?{def:t,stubKind:"throw-stub",stubText:c.trim()}:i4.test(r)&&r4.test(c.trim())?{def:t,stubKind:"todo-return-default",stubText:i}:null}function l4(e,t){let n=[],r=0,i="";for(let o=0;o<t.length;o+=1){let s=t[o];if(s==="("||s==="["||s==="{"?r+=1:(s===")"||s==="]"||s==="}")&&(r=Math.max(0,r-1)),s===";"&&r===0){n.push(i),i="";continue}i+=e[o]??""}return i.trim()&&n.push(i),n.map(o=>o.trim()).filter(o=>o.length>0)}function u4(e){let t=n4.exec(e.trim());return t?t4.test(t[1]??""):!1}function d4(e){return o4.test(e.trimEnd())}function m4(e,t,n){let r=new Set,i=new Set(t.map(a=>a.def.parentTypeName).filter(a=>a!==null));if(i.size===0)return r;let o=p4(e,i),s=new Map;for(let a of n){if(!a.parentTypeName)continue;let c=s.get(a.leaf)??new Set;c.add(a.parentTypeName),s.set(a.leaf,c)}for(let a of t){let c=a.def.parentTypeName;if(!c)continue;let l=o.get(c);if(!l||l.size===0)continue;let u=s.get(a.def.leaf)??new Set;[...l].every(m=>u.has(m))&&r.add(a.def.symbol)}return r}var f4=/\bclass\s+([A-Za-z_$][\w$]*)\s+extends\s+([A-Za-z_$][\w$]*)/g;function p4(e,t){let n=new Map;for(let r of L(e,{includeIgnored:!1})){let i=k(e,r);if(i)for(let o of i.matchAll(f4)){let s=o[1],a=o[2];if(!s||!a||!t.has(a))continue;let c=n.get(a)??new Set;c.add(s),n.set(a,c)}}return n}var g4=/^(?:validate|verify|check|assert)(?:[A-Z].*)?$/,h4=/^(?:is|has)(?:[A-Z].*)?$/,y4=/[{,]\s*(?:ok|success|valid|isValid)\s*:\s*false\b/,cg=/\breturn\b/g,b4=/\bfunction\b|=>|\)\s*(?::\s*[^{;=]+)?\s*\{/,S4=/\.(?:addIssue|push)\s*\(/;function x4(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new F(e),s=fe(o.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),a=[];for(let c of s){let l=C4(e,c);l&&a.push({symbol:c.symbol,shortName:E(c.symbol),file:c.relativePath,startLine:c.startLine,endLine:c.endLine,loc:j(c),...l})}return a.sort((c,l)=>c.file.localeCompare(l.file)||c.startLine-l.startLine||c.loc-l.loc),r?a.slice(0,r):a}function R4(e){return g4.test(e)?"imperative":h4.test(e)?"predicate":null}function C4(e,t){let n=R4(t.leaf);if(!n||to(e,t))return null;let r=Gn(e,t);if(!r||!b4.test(r))return null;let i=Y(e,t.relativePath)?.callables.find(s=>s.startLine===t.startLine&&s.endLine===t.endLine);if(n==="predicate"&&i?.paramCount===0)return null;if(pE(r)){let s=w4(e,t);return!s||oD(s.body,iD(s.snippet))||rD(s.body)?null:{nameKind:n,resolvedVia:"one-hop-delegate",delegateTarget:s.shortName}}let o=fn(r);return oD(o,iD(r))||rD(o)?null:{nameKind:n,resolvedVia:"direct"}}var v4=new Set(["if","for","while","switch","catch","function"]);function rD(e){let t=Fo(e);for(let n of t.matchAll(/\b([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/g))if(!v4.has(n[1]))return!0;return!1}function iD(e){let t=e.indexOf("=>");return t===-1?!1:!/^\s*\{/.test(e.slice(t+2))}function oD(e,t){let n=Fo(e);if(/\bthrow\b/.test(n)||/\.reject\s*\(/.test(n)||y4.test(n)||S4.test(n))return!0;let r=I4(n);if(t&&r.length===0){let i=n.trim();return i!==""&&i!=="true"}for(let i of r)if(i!==""&&i!=="true")return!0;return!1}function I4(e){let t=[];cg.lastIndex=0;let n;for(;n=cg.exec(e);){let r=n.index+n[0].length,i=0,o=e.length;for(let s=r;s<e.length;s+=1){let a=e[s];if(a==="("||a==="["||a==="{")i+=1;else if(a===")"||a==="]"||a==="}"){if(i===0){o=s;break}i-=1}else if(a===";"&&i===0){o=s;break}}t.push(e.slice(r,o).trim()),cg.lastIndex=o}return t}function w4(e,t){let n=Bt(e,t,{callableOnly:!0,limit:3,semanticEvidence:q}),r=[...new Set(n.map(c=>c.symbol))].filter(c=>c!==t.symbol);if(r.length!==1)return null;let o=Or(e,r[0]).match;if(!o)return null;let s=ie(e,o.relativePath).find(c=>c.symbolId===o.symbolId);if(!s)return null;let a=Gn(e,s);return a?{body:fn(a),snippet:a,shortName:E(s.symbol)}:null}var E4=60;function D4(e,t={}){let{scope:n,limit:r=30,scanLimit:i,rotDays:o=E4}=t,s=fe(ct(e,{extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs"]}).filter(u=>U(u)==="test").filter(u=>!n||u.includes(n)).filter(u=>!e.isIgnored(u)).sort(),i),a=[],c=[],l=[];for(let u of s){let d=k(e,u);if(!d)continue;let m=Ly(d),f=T4(d);for(let g of L4(m,f))f.add(g);let p=P4(m);for(let g of p){if(g.skip){c.push(H4(e,u,g,o));continue}if(g.kind==="describe")continue;let y=aD(d,g.argsStart),h=m.slice(g.argsStart,g.callEnd),S=d.slice(g.argsStart,g.callEnd);cD(h,f)||a.push({file:u,startLine:ia(d,g.callStart),endLine:ia(d,g.callEnd),title:y,severity:/\bawait\b/.test(h)?"low":"high"});let b=B4(h,S);b&&l.push({file:u,startLine:ia(d,g.callStart),endLine:ia(d,g.callEnd),title:y,echoedValue:b})}}return{assertionFree:r?a.slice(0,r):a,skipped:r?c.slice(0,r):c,mockEcho:r?l.slice(0,r):l}}var lg=/(?<!\.)\b(?:x(it|test|describe)|(it|test|describe)(?:\.\s*(skip|only|todo|each\s*\([^)]*\)))?)\s*\(/g;function P4(e){let t=[];lg.lastIndex=0;let n;for(;n=lg.exec(e);){let r=n[1],i=r??n[2];if(!i)continue;let o=n[3]?.split(/\s*\(/)[0],s=n.index,a=n.index+n[0].length-1,c=oa(e,a);lg.lastIndex=a+1,o!=="each"&&t.push({kind:i,skip:r!==void 0||o==="skip"||o==="todo",skipKind:o==="todo"?"todo":"skip",callStart:s,argsStart:a+1,callEnd:c+1})}return t}function oa(e,t){let n=0;for(let r=t;r<e.length;r+=1){let i=e[r];if(i==="(")n+=1;else if(i===")"&&(n-=1,n===0))return r}return e.length-1}function ia(e,t){let n=0;for(let r=0;r<t&&r<e.length;r+=1)e[r]===`
|
|
844
|
+
`&&(n+=1);return n}function aD(e,t){let n=e.slice(t,t+400),r=/^\s*(['"`])((?:\\.|(?!\1)[\s\S])*)\1/.exec(n);return r?r[2]:"(anonymous)"}var k4=new Set(["vitest","chai","jest","@jest/globals","assert","node:assert","node:assert/strict","assert/strict","uvu/assert","expect","chai-as-promised"]),sD=/import\s+(?:\*\s+as\s+(\w+)|\{([^}]*)\}|(\w+))\s+from\s+['"]([^'"]+)['"]/g;function T4(e){let t=new Set(["expect","assert"]);sD.lastIndex=0;let n;for(;n=sD.exec(e);){let[,r,i,o,s]=n;if(!(!s||!k4.has(s))&&(r&&t.add(r),o&&t.add(o),i))for(let a of i.split(",")){let c=a.trim().replace(/^type\s+/,"");if(!c)continue;let l=/^(\w+)\s+as\s+(\w+)$/.exec(c);t.add(l?l[2]:c)}}return t}function cD(e,t){if(/\.should\b/.test(e)||/\bawait\s+(?:[\w$.]+\.)?findBy[A-Z]\w*\s*\(/.test(e)||/\bawait\s+\w*waitFor(?:Text|Value|Condition|Result|Event)\s*\(/.test(e)||/\bthrow\b/.test(e))return!0;for(let n of t){let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\b${r}\\s*(?:<[^<>]*>)?\\s*[.(]`).test(e))return!0}return!1}var F4=/\bfunction\s+(\w+)\s*\(/g,_4=/\b(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/g,A4=60;function L4(e,t){let n=new Set;for(let r of[F4,_4]){r.lastIndex=0;let i;for(;i=r.exec(e);){let o=i[1],s=i.index+i[0].length-1,a=oa(e,s),c=e.indexOf("{",a+1);if(c===-1||c-a>A4)continue;let l=M4(e,c),u=e.slice(c+1,l);cD(u,t)&&n.add(o)}}return n}function M4(e,t){let n=0;for(let r=t;r<e.length;r+=1){let i=e[r];if(i==="{")n+=1;else if(i==="}"&&(n-=1,n===0))return r}return e.length-1}var N4=/\bmock(?:ReturnValue|ResolvedValue)(?:Once)?\s*\(/g,ug=/\bexpect\s*\(/g,O4=/^\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(/,lD=/^(?:-?\d+(?:\.\d+)?|(['"`]).+\1)$/;function B4(e,t){let n=j4(e,t,N4);if(n.length===0)return null;let r=$4(e,t);for(let i of r)if(n.includes(i))return i;return null}function j4(e,t,n){let r=[];n.lastIndex=0;let i;for(;i=n.exec(e);){let o=i.index+i[0].length-1,s=oa(e,o),a=t.slice(o+1,s).trim();lD.test(a)&&r.push(a),n.lastIndex=s+1}return r}function $4(e,t){let n=[];ug.lastIndex=0;let r;for(;r=ug.exec(e);){let i=r.index+r[0].length-1,o=oa(e,i),s=e.slice(o+1),a=O4.exec(s);if(ug.lastIndex=o+1,!a)continue;let c=o+1+a[0].length-1,l=oa(e,c),u=t.slice(c+1,l).trim();lD.test(u)&&n.push(u)}return n}function H4(e,t,n,r){let i=k(e,t),o=aD(i,n.argsStart),s=ia(i,n.callStart),a=G4(e.config.projectRoot,t,s),c=a===null?"unknown":a>=r?"rot":"workflow";return{file:t,startLine:s,title:o,skipKind:n.skipKind,blockKind:n.kind,ageDays:a,rot:c}}function G4(e,t,n){let r=n+1;try{let i=mn(e,["blame","-L",`${r},${r}`,"--porcelain","--",t]),o=/^author-time (\d+)$/m.exec(i);if(!o)return null;let s=Number(o[1]);return Number.isFinite(s)?Math.max(0,Math.round((Date.now()/1e3-s)/86400)):null}catch{return null}}var q4=.7,uD=.62,dD=.45;function U4(e,t={}){let{windowCommits:n=100,limit:r=30,scope:i,scanLimit:o}=t,s=ft(e,{historyMode:t.historyMode}).fileAddRecords();if(!s)return{available:!1,windowCommits:n,findings:[]};if(r<=0)return{available:!0,windowCommits:n,findings:[]};let a=Z4(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let l=V4(e,{limit:r,minSimilarity:t.minSimilarity,scanLimit:o,scope:i,semantic:t.semantic,focusFiles:Number.isFinite(r)?void 0:a}).map(d=>e6(d,s,n)).filter(d=>d!==null);l.sort((d,m)=>(d.kind===m.kind?0:d.kind==="echo"?-1:1)||m.similarity-d.similarity||d.echoFile.localeCompare(m.echoFile)||d.echoSymbol.localeCompare(m.echoSymbol)||d.domain.localeCompare(m.domain));let u=l.slice(0,r).map(t6);return{available:!0,windowCommits:n,findings:u,rootCauseGroups:n6(u)}}function V4(e,t){let n=i6(t.limit),r=[...z4(e,{scope:t.scope,minSimilarity:t.minSimilarity??q4,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],i=$a(e,{scope:t.scope});return i.react&&r.push(...W4(e,{scope:t.scope,minSimilarity:t.minSimilarity??uD,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...K4(e,{scope:t.scope,minSimilarity:t.minSimilarity??dD,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i.vue&&r.push(...X4(e,{scope:t.scope,minSimilarity:t.minSimilarity??uD,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...Q4(e,{scope:t.scope,minSimilarity:t.minSimilarity??dD,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r}function z4(e,t){return Bs(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles}).filter(n=>!$e(n.symbolA)&&!$e(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 W4(e,t){return Ql(e,t,{query:js,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 Ql(e,t,n){return n.query(e,t).filter(r=>r.fileA!==r.fileB).filter(r=>n.acceptPair?.(r)??!0).map(r=>({domain:n.domain,basis:n.basis,symbolA:n.symbolA(r),fileA:r.fileA,symbolB:n.symbolB(r),fileB:r.fileB,similarity:r.similarity,sharedEvidence:o6(...n.evidenceBuckets(r)),sharedCallees:[]}))}function K4(e,t){return Ql(e,t,{query:$s,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,acceptPair:Y4,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 J4=new Set(["useCallback","useEffect","useLayoutEffect","useMemo","useMutation","useQueries","useQuery","useQueryClient","useReducer","useRef","useState"]);function Y4(e){return e.sharedHooks.some(t=>!J4.has(t))||e.sharedState.length>0||e.sharedHandlers.length>0||e.sharedHandlerVerbs.length>=2}function X4(e,t){return Ql(e,t,{query:Hs,domain:"vue-component",basis:"vue-template",symbolA:n=>Xl(n.fileA),symbolB:n=>Xl(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function Q4(e,t){return Ql(e,t,{query:Gs,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>Xl(n.fileA),symbolB:n=>Xl(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 Z4(e,t){let n=new Set;for(let[r,i]of e)i.commitsAgo<=t&&n.add(r);return n}function e6(e,t,n){let r=t.get(e.fileA)?.commitsAgo??null,i=t.get(e.fileB)?.commitsAgo??null,o=r!==null&&r<=n,s=i!==null&&i<=n;if(!o&&!s)return null;if(o&&s){let a=(r??0)<=(i??0);return{kind:"twin",domain:e.domain,basis:e.basis,echoSymbol:a?e.symbolA:e.symbolB,echoFile:a?e.fileA:e.fileB,echoAgeCommits:(a?r:i)??0,establishedSymbol:a?e.symbolB:e.symbolA,establishedFile:a?e.fileB:e.fileA,establishedAgeCommits:a?i:r,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}return{kind:"echo",domain:e.domain,basis:e.basis,echoSymbol:o?e.symbolA:e.symbolB,echoFile:o?e.fileA:e.fileB,echoAgeCommits:(o?r:i)??0,establishedSymbol:o?e.symbolB:e.symbolA,establishedFile:o?e.fileB:e.fileA,establishedAgeCommits:o?i:r,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}function t6(e){let t=mD(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function mD(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 n6(e){let t=new Map;for(let[n,r]of e.entries()){let i=r.rootCauseKey??mD(r),o=r.groupKey??`recent-duplicate:${i}`,s=t.get(o);s||(s={groupKey:o,rootCauseKey:i,kind:r.kind,domain:r.domain,basis:r.basis,count:0,maxSimilarity:r.similarity,findingIndexes:[],echoFiles:new Set,establishedFile:r.kind==="echo"?r.establishedFile:void 0,establishedSymbol:r.kind==="echo"?r.establishedSymbol:void 0,relatedFiles:new Set,sharedEvidence:new Set,recommendation:r6(r)},t.set(o,s)),s.count+=1,s.maxSimilarity=Math.max(s.maxSimilarity,r.similarity),s.findingIndexes.push(n),s.echoFiles.add(r.echoFile),s.relatedFiles.add(r.echoFile),s.relatedFiles.add(r.establishedFile);for(let a of r.sharedEvidence)s.sharedEvidence.add(a)}return[...t.values()].map(n=>({...n,echoFiles:[...n.echoFiles].sort(),relatedFiles:[...n.relatedFiles].sort(),sharedEvidence:[...n.sharedEvidence].sort().slice(0,16)})).sort((n,r)=>r.count-n.count||r.maxSimilarity-n.maxSimilarity||n.groupKey.localeCompare(r.groupKey))}function r6(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 i6(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function o6(...e){let t=[],n=new Set;for(let[r,i]of e)for(let o of i){let s=`${r}:${o}`;n.has(s)||(n.add(s),t.push(s))}return t}function Xl(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var s6=z("suppression-inventory",{clearGroups:["whole-project"]});function Zl(e){return s6.get(e,()=>a6(e))}function a6(e){let t={dead:0,stale:0,wrapper:0,passthrough:0,drift:0,extract:0,similar:0,twin:0,uncategorized:0},n=new Map,r=0;for(let i of ct(e)){let o=k(e,i);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=vo(s);if(a===null)continue;r+=1,n.set(i,(n.get(i)??0)+1);let c=c6(a);t[c]+=1}}return{total:r,byCategory:t,byFile:n}}function c6(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"?"dead":t}function dg(e,t,n={}){let r=G(e,t);if(!r)return null;let i=new F(e),o=l6(e,r),s=r.endLine-r.startLine+1,c=i.calleeMap([r],{additive:!0,semantic:n.semantic}).get(r.symbolId)??[],l=new Set(c.map(u=>u.symbol));return{symbol:r.symbol,shortName:E(r.symbol),relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,loc:s,branches:o.branches,estimateBasis:o.estimateBasis,cyclomaticEstimate:o.branches+1,calleeCount:l.size,fanIn:d6(e,r.symbolId),fanOut:m6(c,r.relativePath)}}function l6(e,t){let n=ne(e,t.relativePath);if(n){let r=hD(n.rootNode,t.startLine,t.endLine);if(r)return{branches:f6(r),estimateBasis:"ast"}}return{branches:bD(gD(e,t.relativePath,t.startLine,t.endLine),pD(e,t.relativePath)),estimateBasis:"regex-fallback"}}function fD(e,t){let n=new Map,r=new Map;for(let i of t){let o=r.get(i.relativePath)??[];o.push(i),r.set(i.relativePath,o)}for(let[i,o]of r){let s=ne(e,i),a=s===null?[]:o.filter(l=>s.rootNode.startPosition.row<=l.startLine&&s.rootNode.endPosition.row>=l.endLine),c=new Set(a.map(l=>l.symbolId));if(s&&a.length>0){for(let l of a)n.set(l.symbolId,{branches:0,estimateBasis:"ast"});p6(s.rootNode,a,n)}for(let l of o)c.has(l.symbolId)||n.set(l.symbolId,u6(e,l))}return n}function u6(e,t){return{branches:bD(gD(e,t.relativePath,t.startLine,t.endLine),pD(e,t.relativePath)),estimateBasis:"regex-fallback"}}function pD(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function gD(e,t,n,r){try{return de(e.config.projectRoot,t,{inputKind:"indexed source file"}).split(`
|
|
845
|
+
`).slice(n,r+1).join(`
|
|
846
|
+
`)}catch(i){if(!we(i))throw i;return""}}function d6(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
|
|
847
|
+
FROM mentions m
|
|
848
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
849
|
+
JOIN (
|
|
850
|
+
SELECT m2.symbol_id, c2.document_id
|
|
851
|
+
FROM mentions m2
|
|
852
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
853
|
+
WHERE m2.role = 1
|
|
854
|
+
GROUP BY m2.symbol_id
|
|
855
|
+
) sym_def ON sym_def.symbol_id = m.symbol_id
|
|
856
|
+
WHERE m.symbol_id = ?
|
|
857
|
+
AND m.role != 1
|
|
858
|
+
AND sym_def.document_id != c.document_id`,t)?.c??0}function m6(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function f6(e){let t=0;return mg(e,n=>{t+=yD(n)}),t}function p6(e,t,n){let r=[...t].sort((i,o)=>i.startLine-o.startLine||o.endLine-i.endLine);mg(e,i=>{let o=yD(i);if(o===0)return;let s=i.startPosition.row,a=i.endPosition.row;for(let c of r){if(c.startLine>s)break;if(c.endLine<a)continue;let l=n.get(c.symbolId);l&&(l.branches+=o)}})}function mg(e,t){t(e);for(let n of e.namedChildren)mg(n,t)}function hD(e,t,n){if(e.startPosition.row>t||e.endPosition.row<n)return null;for(let r of e.namedChildren){let i=hD(r,t,n);if(i)return i}return e}var g6=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 yD(e){return g6.has(e.type)?1:e.type==="binary_expression"&&e.parent?.type!=="binary_expression"&&(e.text.includes("&&")||e.text.includes("||"))?h6(e.text):0}function h6(e){return(e.match(/&&|\|\|/g)??[]).length}function bD(e,t){let n=Tt(e),r=0,i=[/\bif\b/g,/\belse\s+if\b/g,/\belse\b/g,/\bfor\b/g,/\bwhile\b/g,/\bswitch\b/g,/\bcase\b/g,/\bcatch\b/g,/\?\s*[^?]/g,/&&/g,/\|\|/g];for(let o of i){let s=n.match(o);s&&(r+=s.length)}if(t==="python"){let o=[/\belif\b/g,/\bexcept\b/g,/\bfinally\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="rust"){let o=[/\bmatch\b/g,/=>/g,/\bloop\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="ruby"){let o=[/\belsif\b/g,/\bunless\b/g,/\brescue\b/g,/\bwhen\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="go"){let o=[/\bselect\b/g,/\bdefer\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}return r}function fg(e,t,n={}){let r=G(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],o=nn(e,r,{semantic:n.semantic,semanticEvidence:q}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?E(c.enclosingSymbol):"(top-level)"})),{producers:s,consumers:a}=y6(e,r,o,{semantic:n.semantic!==!1});return{symbol:r.symbol,shortName:E(r.symbol),relativePath:r.relativePath,definitionSites:i.filter(c=>!e.isIgnored(c.file)),usageSites:o,producers:s.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:E(c.symbol),file:c.file})),consumers:a.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:c.symbol===c.file?"(top-level)":E(c.symbol),file:c.file}))}}function y6(e,t,n,r){let i=eo(Bt(e,t,{limit:30,semantic:r.semantic,semanticEvidence:q}).map(a=>({symbol:a.symbol,file:a.file}))),o=eo(Nn(e,t,{limit:30,semantic:r.semantic,semanticEvidence:q})),s=o.length>0?o:eo(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:i,consumers:s}}function eu(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=G(e,t);return o?r==="backward"?b6(e,o,i,{semantic:n.semantic!==!1}):S6(e,o,{semantic:n.semantic!==!1}):null}function b6(e,t,n,r){let i=[],o=new Set([t.symbol]),s=[t];for(let a=1;a<=n&&s.length!==0;a++){let c=[];for(let l of s){let u=Bt(e,l,{semantic:r.semantic,semanticEvidence:q});for(let d of u){if(o.has(d.symbol))continue;o.add(d.symbol),i.push({symbol:d.symbol,shortName:E(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=No(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&c.push(m)}}s=c}return{symbol:t.symbol,shortName:E(t.symbol),direction:"backward",connectedSymbols:i}}function S6(e,t,n){let r=new Set,i=[],o=new F(e);for(let s of nn(e,t,{semantic:n.semantic,semanticEvidence:q})){if(i.length>=30)break;let a=s.enclosingSymbol??tn(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=No(e,a);!c||e.isIgnored(c.relativePath)||r.has(c.symbol)||(r.add(c.symbol),i.push({symbol:c.symbol,shortName:E(c.symbol),file:c.relativePath,relationship:`references target at ${s.file}:${s.line+1}`}))}return i.sort((s,a)=>s.file.localeCompare(a.file)),{symbol:t.symbol,shortName:E(t.symbol),direction:"forward",connectedSymbols:i}}function x6(e,t,n={}){let r=n.impactDepth??3,i=n.sliceDepth??3,o=n.semantic,s=!C6(t),a=s?Xe("trace",t,()=>Kf(e,t,{semantic:o}),C=>({definitions:C.definitions.length,references:C.referencedBy.length})):{definitions:[],referencedBy:[]},c=s?Xe("call-graph",t,()=>ip(e,t,{semantic:o}),C=>({callers:C?.callers.length??0,callees:C?.callees.length??0})):null,l=s?Xe("complexity",t,()=>dg(e,t,{semantic:o}),C=>({callees:C?.calleeCount??0})):null,u=s?Xe("dataflow",t,()=>fg(e,t,{semantic:o}),C=>({references:C?.usageSites.length??0,producers:C?.producers.length??0,consumers:C?.consumers.length??0})):null,d=s?Xe("backward-slice",t,()=>eu(e,t,{direction:"backward",maxDepth:i,semantic:o}),C=>({maxDepth:i,connectedSymbols:C?.connectedSymbols.length??0})):null,m=s?Xe("forward-slice",t,()=>eu(e,t,{direction:"forward",maxDepth:i,semantic:o}),C=>({maxDepth:i,connectedSymbols:C?.connectedSymbols.length??0})):null,f=s?Xe("affected",t,()=>xp(e,t,{maxDepth:r,scope:n.scope}),C=>({maxDepth:r,affectedSymbols:C.length})):[],p=Xe("change-surface",t,()=>Rp(e,t,{semantic:o}),C=>({symbols:C?.symbols.length??0,externalConsumers:C?.totalExternalConsumers??0})),g=Xe("system",t,()=>Xf(e,t),C=>({files:C.files.length,symbols:C.symbols.length})),y=g.files.length===1,h=Xe("deps",t,()=>y?g.dependsOn.map(C=>({relativePath:C})):Jf(e,t),C=>({files:C.length,reusedSystem:y})),S=Xe("rdeps",t,()=>y?g.dependedOnBy.map(C=>({relativePath:C})):Yf(e,t),C=>({files:C.length,reusedSystem:y})),b=Xe("surface",t,()=>Qf(e,t),C=>({consumers:C.length})),R={symbol:a.definitions.length>0||a.referencedBy.length>0||c!==null||l!==null||u!==null||d!==null||m!==null||f.length>0,file:p!==null||h.length>0||S.length>0,module:g.files.length>0||g.symbols.length>0||b.length>0},x=[];!R.symbol&&!R.file&&!R.module&&x.push("No symbol, file, or module matched target.");let v=p?.file??a.definitions[0]?.relativePath??null;return{target:t,matched:R,history:Xe("history",v??t,()=>R6(e,v,n.gitHead)),trace:a,callGraph:c,complexity:l,dataflow:u,backwardSlice:d,forwardSlice:m,affected:f,changeSurface:p,deps:h,rdeps:S,system:g,surface:b,warnings:x}}function Xe(e,t,n,r=()=>({})){let i;return D(`plan-context.${e}`,()=>(i=n(),i),()=>({target:t,...r(i)}))}function R6(e,t,n){let r={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return r;let i=ft(e,n?{head:n}:{}),o=Xe("history.churn",t,()=>i.fileChurn(),c=>({files:c?.size??0}));if(!o)return r;let s=Xe("history.co-change",t,()=>Vs(e,t,{limit:5,...n?{head:n}:{}}),c=>({commits:c.commitsAnalyzed,partners:c.findings.length})),a=Xe("history.suppressions",t,()=>Zl(e).byFile.get(t)??0,c=>({suppressions:c}));return{available:!0,file:t,churn:o.get(t)??{changes:0,fixChanges:0,lastChangedAt:0},coChangePartners:s.findings.map(c=>({file:c.fileA===t?c.fileB:c.fileA,together:c.together,confidence:c.confidence,subjectContext:c.subjectContext})),suppressionsInFile:a}}function C6(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}var v6=new Set(ln());function pg(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:o}=t??{},s=new F(e);return $t({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:r,requireFunctionLikeSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,filterCandidate:I6,profile:{name:"complexity-hotspots"},prepare:a=>{let c=E6(e,a),l=t?.semantic!==!1,u=l?mt(e):null;u?.materializeReferences(a,{prefetchCallees:!0});let d=s.crossFileCallerMap(a,{semantic:!1});return{callerMap:u?On(d,u.callerMap(a)):d,calleeMap:s.calleeMap(a,{semantic:l}),languageByFile:c,clojureCallableIds:D6(e,a,c),branchEstimates:fD(e,a)}},evaluate:(a,c)=>w6(a,c,r),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:i})}function I6(e){return e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&v6.has(e.kind):!0}function w6(e,t,n){if(t.languageByFile.get(e.relativePath)==="clojure"&&!t.clojureCallableIds.has(e.symbolId))return null;let r=e.endLine-e.startLine+1;if(r<n)return null;let i=t.callerMap.get(e.symbolId)?.size??0,o=t.calleeMap.get(e.symbolId)??[],s=new Set,a=new Set;for(let m of o){let f=`${m.symbol}|${m.file}`;s.add(f),m.file!==e.relativePath&&a.add(f)}let c=a.size,l=s.size,u=t.branchEstimates.get(e.symbolId)??{branches:0,estimateBasis:"regex-fallback"},d=u.branches+1;return{symbol:e.symbol,shortName:E(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:r,fanIn:i,fanOut:c,calleeCount:l,branches:u.branches,estimateBasis:u.estimateBasis,score:Math.round(r/50*(i/5)*Math.max(c/5,1)*Math.max(d/5,1)*100)/100}}function E6(e,t){let n=[...new Set(t.map(o=>o.relativePath))];if(n.length===0)return new Map;let r=n.map(()=>"?").join(", "),i=e.all(`SELECT relative_path, language
|
|
859
|
+
FROM documents
|
|
860
|
+
WHERE relative_path IN (${r})`,...n);return new Map(i.map(o=>[o.relative_path,o.language?.toLowerCase()??null]))}function D6(e,t,n){let r=new Set,i=new Map;for(let o of t){if(n.get(o.relativePath)!=="clojure")continue;let s=i.get(o.relativePath);s||(s=new Set((Y(e,o.relativePath)?.callables??[]).map(a=>`${a.name}:${a.startLine}`)),i.set(o.relativePath,s)),s.has(`${o.leaf}:${o.startLine}`)&&r.add(o.symbolId)}return r}import{createHash as P6,randomUUID as k6}from"crypto";function Ht(e,t){return`${e}\0${t}`}function pwe(e,t,n,r,i,o={}){let s=new Map(e.map(l=>[Ht(l.check,l.findingId),l])),a=[],c=(l,u)=>{let d=n.get(l.findingId),m=u==="resolved"?o.verifiedAgainstByFinding?.get(Ht(l.check,l.findingId)):void 0,f=u==="suppressed"?o.suppressionPolicyVersionByFinding?.get(Ht(l.check,l.findingId)):void 0;a.push({ts:i,check:l.check,findingId:l.findingId,event:u,commit:r,...o.comparisonBaseCommit?{comparisonBaseCommit:o.comparisonBaseCommit}:{},...m?{verifiedAgainstCommit:m}:{},...d?{symbol:d}:{},...o.gateRunId?{gateRunId:o.gateRunId}:{},...o.observer?{observer:o.observer}:{},...o.observation?{observation:o.observation}:{},...f!==void 0?{suppressionPolicyVersion:f}:{}})};for(let l of t){let u=s.get(Ht(l.check,l.findingId));if(!u){c(l,"caught"),l.outcome==="suppressed"&&c(l,"suppressed");continue}u.outcome!==l.outcome&&(l.outcome==="resolved"?c(l,"resolved"):l.outcome==="suppressed"?c(l,"suppressed"):l.outcome==="still-open"&&c(l,"reopened"))}return a}function SD(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(n?.event==="caught"||n?.event==="reopened")return n}}function T6(e,t,n,r,i=new Set){let o=new Map(e.map(c=>[Ht(c.check,c.findingId),c])),s=new Set(t.map(c=>Ht(c.check,c.findingId))),a=new Set(n);for(let c of t){let l=Ht(c.check,c.findingId),u=o.get(l),d=c.suppressed?"suppressed":"still-open";u?o.set(l,{...u,lastSeen:r,timesShown:u.timesShown+1,outcome:d}):o.set(l,{check:c.check,findingId:c.findingId,firstSeen:r,lastSeen:r,timesShown:1,outcome:d})}for(let c of e){if(!a.has(c.check))continue;let l=Ht(c.check,c.findingId);s.has(l)||i.has(l)||c.outcome!=="resolved"&&o.set(l,{...c,outcome:"resolved"})}return[...o.values()]}function gg(e,t){let n=new Map;for(let i of e){let o=n.get(i.check)??[];o.push(i),n.set(i.check,o)}let r=[];for(let[i,o]of n){let s=o.filter(d=>d.outcome==="resolved").length,a=o.filter(d=>d.outcome==="suppressed").length,c=o.filter(d=>d.outcome==="still-open").length,l=o.length,u=o.filter(d=>d.outcome==="still-open").sort((d,m)=>d.firstSeen-m.firstSeen)[0];r.push({check:i,seen:l,resolved:s,suppressed:a,stillOpen:c,resolutionRate:l>0?s/l:0,suppressionRate:l>0?a/l:0,oldestOpenAgeDays:u?Math.floor((t-u.firstSeen)/RD):null})}return r.sort((i,o)=>i.check.localeCompare(o.check))}var RD=864e5,F6=50,_6=.1,A6=10;function L6(e,t,n){return e.filter(r=>r.check===t).sort((r,i)=>i.firstSeen-r.firstSeen).slice(0,n)}function Swe(e,t,n){if(t.length===0)return null;let r=new Map(e.map(s=>[Ht(s.check,s.findingId),s])),i=t.map(s=>r.get(Ht(s.check,s.findingId))).filter(s=>s!==void 0&&s.timesShown>1);if(i.length===0)return null;let o=Math.max(...i.map(s=>Math.floor((n-s.firstSeen)/RD)));return`${t.length} finding(s), ${i.length} shown before and unresolved (oldest: ${o} day(s))`}function xwe(e,t){let n=[];for(let r of[...new Set(t)].sort()){let i=L6(e,r,F6);i.length<A6||i.filter(a=>a.outcome==="resolved").length/i.length>=_6||n.push(`(the ${r} check's findings are rarely acted on in this repo \u2014 consider suppressing with reasons or tuning its config)`)}return n}function hg(e){return oh(e).map(tu)}function Rwe(e,t,n,r=Date.now(),i=new Set,o=k6(),s){let a=M6(t),c=[...new Set(n)].sort(),l=new Set([...i].sort()),u=P6("sha256").update(JSON.stringify({checksRun:c,observed:a,observedAt:r,retainedKeys:[...l]})).digest("hex"),d=sh(e,{observationId:o,fingerprint:u,observedAt:r},m=>T6(m.map(tu),a,c,r,l),s===void 0?{}:{busyTimeoutMs:s});return{observationId:o,status:d.status,previous:d.previous.map(tu),current:d.current.map(tu)}}function M6(e){let t=new Map;for(let n of e){let r=Ht(n.check,n.findingId),i=t.get(r);t.set(r,{check:n.check,findingId:n.findingId,suppressed:n.suppressed||(i?.suppressed??!1)})}return[...t.values()].sort((n,r)=>xD(n.check,r.check)||xD(n.findingId,r.findingId))}function xD(e,t){return e<t?-1:e>t?1:0}function tu(e){return{check:e.check,findingId:e.findingId,firstSeen:e.firstSeen,lastSeen:e.lastSeen,timesShown:e.timesShown,outcome:e.outcome}}function qn(e){return e.scoreCount??e.count}function ID(e){let t=j6(e),{breakdown:n,pressure:r}=$6(e),i=vD(n,"risk"),o=vD(n,"hygiene");return{score:Math.min(i,o),riskScore:i,hygieneScore:o,scoreBreakdown:n,overview:{documents:e.statsResult.documents,symbols:e.statsResult.symbols,indexSizeBytes:e.statsResult.indexSizeBytes},findings:{deadSymbols:e.dead.count,deadLoc:e.dead.loc,isolatedSymbols:e.isolated.count,isolatedLoc:e.isolated.loc,cycles:e.realCycleCount,similarPairs:e.similarCount,duplicateBodyGroups:e.duplicateBodies.count,duplicateBodyLoc:e.duplicateBodies.loc,twinDriftGroups:e.twinDrift.count,twinDriftLoc:e.twinDrift.loc,reactComponentDuplicatePairs:e.reactComponentDuplicates.count,reactHookCandidatePairs:e.reactHookCandidates.count,reactHookCandidateScoreCount:qn(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:qn(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:qn(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:N6(e),validation:B6(e),suppressions:e.suppressions,actions:t,pressure:r,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0,detectorPrecision:[]}}function N6(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:O6(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 O6(e){let t=e.gitEvidence?.fileStats;return t?e.complexity.top.map(n=>{let r=n.file?t[n.file]?.changes??0:0;return{...n,changes:r,weighted:gn(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function B6(e){let t=e.gitEvidence?.fileStats;if(!t)return null;let n={dead:e.dead.files??[],isolated:e.isolated.files??[],twinDrift:e.twinDrift.files??[],wrappers:e.wrappers.files??[],passthroughs:e.passthroughs.files??[],stale:e.stale.files??[],reactComponents:e.reactComponentDuplicates.files??[],reactHooks:e.reactHookCandidates.files??[],reactLargeComponents:e.reactLargeComponentPressure.files??[],vueComponents:e.vueComponentDuplicates.files??[],vueComposables:e.vueComposableCandidates.files??[],vueLargeViews:e.vueLargeViewPressure.files??[]},r=new Set(Object.values(n).flat()),i=0,o=0,s=0;for(let[u,d]of Object.entries(t))r.has(u)?i+=d.fixChanges:(o+=d.fixChanges,s+=1);let a=r.size>0?gn(i/r.size):0,c=s>0?gn(o/s):0,l={};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=gn(f/m.size);l[u]={flaggedFiles:m.size,fixDensity:p,lift:c>0?gn(p/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?gn(a/c):null,byCategory:l,validationBasis:{method:"subject-regex",commitsScanned:e.gitEvidence?.commitsScanned??0}}}function gn(e){return Math.round(e*100)/100}function wD(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function nu(e,t="existing shared infrastructure discount"){let n=qn(e);return Math.abs(n-e.count)<.01?"":` (${wD(n)} score-weighted after ${t})`}function sa(e,t){let n=qn(e),r=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?r:`${r} (${wD(n)} score-weighted)`}function j6(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${nu(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${nu(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${nu(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 i=[];e.stale.unused>0&&i.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&i.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",evidence:"heuristic",description:`${i.join(", ")} \u2014 review public, runtime-registration, and ownership evidence before removing, moving, or inlining`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let i=[];e.drift.unusedImports>0&&i.push(`${e.drift.unusedImports} unused imports`),e.drift.architectureViolations>0&&i.push(`${e.drift.architectureViolations} declared architecture violations`),t.push({category:"Structural drift",evidence:"heuristic",description:`${i.join(", ")} \u2014 repair direct dependency-rule breaks; inspect boundary signals with \`drift --architecture\``,effort:e.drift.architectureViolations>0?"medium":"low",impact:e.drift.architectureViolations>0?"medium":"low",count:e.drift.count,locRecoverable:0})}if(e.coverageContracts.count>0&&t.push({category:"Coverage contract drift",evidence:"graph-fact",description:`${e.coverageContracts.count} configured coverage contract(s) drifted from their ground-truth source (enumeration rot) \u2014 run \`scip-query diff-gate\` or \`scip-query health --json\` for the missing/extra keys`,effort:"low",impact:"medium",count:e.coverageContracts.count,locRecoverable:0}),e.gitEvidence&&e.gitEvidence.hiddenCoupling.pairCount>0){let i=e.gitEvidence.hiddenCoupling.top[0];t.push({category:"Hidden coupling",evidence:"change-graph",description:`${e.gitEvidence.hiddenCoupling.pairCount} file pair(s) co-change without a structural link`+nu({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:e.gitEvidence.hiddenCoupling.scoreCount},"broad/stale-history discount")+(i?` (e.g. ${i.fileA} \u2194 ${i.fileB})`:"")+" \u2014 inspect whether a shared concept, generated artifact, or coordinated contract explains the history",effort:"medium",impact:"high",count:e.gitEvidence.hiddenCoupling.pairCount,locRecoverable:0})}let n={high:3,medium:2,low:1},r={low:3,medium:2,high:1};return t.sort((i,o)=>{let s=n[i.impact]*r[i.effort];return n[o.impact]*r[o.effort]-s}),t}var CD={"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 vD(e,t){let n=e.filter(r=>r.kind===t).reduce((r,i)=>r+i.points,0);return Math.max(0,Math.min(100,100-n))}function $6(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=[],i=[],o=(C,w,I)=>{w>0&&r.push({axis:C,points:w,detail:I,kind:CD[C]??"hygiene"})},s=(C,w,I,P,_,se,ee)=>{let A=Math.max(P,1);if(I<=A)return;let ge=I/A,pe=Math.min(_,Math.ceil(Math.log2(ge)*se));if(pe<=0)return;let Cr=CD[C]??"hygiene";i.push({axis:C,category:w,kind:Cr,count:I,threshold:gn(A),ratio:gn(ge),extraPenalty:pe}),o(C,pe,`${I} ${ee} exceed pressure threshold ${gn(A)} (${gn(ge)}x)`)},a=e.dead.count/n;o("dead-code",Math.min(20,Math.round(a*200)),`${e.dead.count} dead symbols (${e.dead.loc} LOC deletable)`);let c=e.isolated.count/n;o("isolated",Math.min(10,Math.round(c*200)),`${e.isolated.count} isolated symbols (${e.isolated.loc} LOC deletable)`),o("cycles",Math.min(15,e.realCycleCount*5),`${e.realCycleCount} real dependency cycle(s)`);let l=e.similarCount/n*1e3;o("similar",Math.min(10,Math.round(l)),`${e.similarCount} similar function pair(s)`);let u=e.duplicateBodies.count/n*1e3;o("duplicate-bodies",Math.min(10,Math.round(u*2)),`${e.duplicateBodies.count} exact duplicate small-body group(s) (${e.duplicateBodies.loc} duplicate LOC)`);let d=e.twinDrift.count/n*1e3;o("twin-drift",Math.min(10,Math.round(d*2)),`${e.twinDrift.count} drifted twin implementation group(s) (same or near-same name, diverged or identical bodies)`);let m=e.reactComponentDuplicates.count/t*1e3;o("react-component-duplicates",Math.min(10,Math.round(m)),`${e.reactComponentDuplicates.count} duplicated React component pair(s)`);let f=qn(e.reactHookCandidates),p=f/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(p)),sa(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 y=e.vueComponentDuplicates.count/t*1e3;o("vue-component-duplicates",Math.min(10,Math.round(y)),`${e.vueComponentDuplicates.count} duplicated Vue component pair(s)`);let h=qn(e.vueComposableCandidates),S=h/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(S)),sa(e.vueComposableCandidates,"duplicated Vue behavior pair(s)"));let b=e.vueLargeViewPressure.count/t*1e3;o("vue-large-view-pressure",Math.min(5,Math.round(b/2)),`${e.vueLargeViewPressure.count} large Vue view pressure file(s)`);let R=qn(e.wrappers);o("wrappers",Math.min(3,R),sa(e.wrappers,"wrapper candidate(s)"));let x=qn(e.passthroughs);o("passthroughs",Math.min(3,x),sa(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 v=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(v*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 C=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(C/10)),sa({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:C},"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 C=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",C,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",h,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",R,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",x,50,4,2,"passthrough candidate(s)"),s("stale-abstractions-pressure","Single-consumer stale abstraction signals",e.stale.singleUse,Math.max(50,n*.02),4,2,"single-consumer stale abstraction signal(s)"),s("drift-pressure","Structural drift signals",e.drift.signal,Math.max(10,t*.1),4,2,"signal drift finding(s)"),{breakdown:r,pressure:i}}import{getHeapStatistics as H6}from"v8";var G6=64*1024*1024;function yg(){let e=globalThis.gc;if(!e)return;let t=H6();t.heap_size_limit-t.used_heap_size<G6||e()}var q6=50,U6=25e3,V6=2500,ED=2500,DD=50,z6=10,ru=["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"],W6={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:X6(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:Q6(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:Z6(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:e3(e,t,n)}),"duplicate-bodies":(e,t,n)=>({phase:"duplicate-bodies",duplicateBodies:n3(e,t,n)}),"twin-drift":(e,t,n)=>({phase:"twin-drift",twinDrift:r3(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:i3(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:o3(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:s3(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:a3(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:c3(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:l3(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:t3(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:u3(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:d3(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:m3(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:h3(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:y3(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:f3(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:p3(e,n)}),"coverage-contracts":(e,t,n)=>({phase:"coverage-contracts",coverageContracts:g3(e,n)})};function bg(e,t,n={}){return K6(e,[t],n)[0]}function K6(e,t,n={}){return J6(e,n.full!==!1,(r,i)=>{let o={...i,releaseCachesBetweenPhases:!1};return t.map(s=>W6[s](e,n.scope,o,r))})}function J6(e,t,n){let r=Zr(e),i=b3(r,t);try{return n(r,i)}finally{tp(e,{semanticProvider:!0}),yg()}}function Sg(e){return ID(Y6(e))}function Y6(e){let t=Pe(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,dead:Pe(e,"dead").dead,isolated:Pe(e,"isolated").isolated,realCycleCount:Pe(e,"cycles").realCycleCount,similarCount:Pe(e,"similar").similarCount,duplicateBodies:Pe(e,"duplicate-bodies").duplicateBodies,twinDrift:Pe(e,"twin-drift").twinDrift,reactComponentDuplicates:Pe(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:Pe(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:Pe(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:Pe(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:Pe(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:Pe(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:Pe(e,"extract-candidates").extractCount,wrappers:Pe(e,"wrapper-candidates").wrappers,passthroughs:Pe(e,"passthrough-candidates").passthroughs,stale:Pe(e,"stale-abstractions").stale,drift:Pe(e,"drift").drift,complexity:Pe(e,"complexity-hotspots").complexity,gitEvidence:PD(e,"git-evidence")?.gitEvidence??null,suppressions:PD(e,"suppressions")?.suppressions??null,coverageContracts:Pe(e,"coverage-contracts").coverageContracts}}function PD(e,t){return e.find(n=>n.phase===t)}function Pe(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function X6(e,t,n){return ve(e,n,"dead",()=>{let r=ei(e,{scope:t,...Ce.dead,scanLimit:n.candidateScanLimit,semantic:n.semantic});return iu(R3(e,r.symbols))})}function Q6(e,t,n){return ve(e,n,"isolated",()=>{let r=Os(e,{scope:t,...Ce.isolated,scanLimit:n.candidateScanLimit,semantic:n.semantic});return iu(C3(e,r))})}function Z6(e,t,n){return ve(e,n,"cycles",()=>Ms(e,{scope:t}).filter(i=>i.kind==="real").length)}function e3(e,t,n){let r=ve(e,n,"similar",()=>up(e,{scope:t,...Ce.similar,scanLimit:n.candidateScanLimit,semantic:n.semantic}));return Math.min(r,n.candidateResultLimit)}function t3(e,t,n){return ve(e,n,"extract-candidates",()=>qs(e,{scope:t,...Ce.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}).length)}function n3(e,t,n){return ve(e,n,"duplicate-bodies",()=>{let r=Js(e,{scope:t,...Ce.duplicateBodies,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),i=new Set,o=0;for(let s of r)for(let a of s.functions.slice(1))i.add(a.file),o+=a.loc;return{count:r.length,loc:o,files:[...i]}})}function r3(e,t,n){return ve(e,n,"twin-drift",()=>{let r=fo(e,{scope:t,...Ce.twinDrift,scanLimit:n.candidateScanLimit}).filter(s=>s.relationship==="divergent"||s.relationship==="identical"),i=new Set,o=0;for(let s of r)for(let a of s.members)i.add(a.file),o+=a.loc;return{count:r.length,loc:o,files:[...i].sort()}})}function i3(e,t,n){return ve(e,n,"react-component-duplicates",()=>{let r=js(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return xg(r)})}function o3(e,t,n){return ve(e,n,"react-hook-candidates",()=>{let r=$s(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return FD(r,I3)})}function s3(e,t,n){return ve(e,n,"react-large-component-pressure",()=>{let r=dp(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return v3(r)})}function a3(e,t,n){return ve(e,n,"vue-component-duplicates",()=>{let r=Hs(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return xg(r)})}function c3(e,t,n){return ve(e,n,"vue-composable-candidates",()=>{let r=Gs(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return FD(r,w3)})}function l3(e,t,n){return ve(e,n,"vue-large-view-pressure",()=>{let r=mp(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return iu(r)})}function u3(e,t,n){return ve(e,n,"wrapper-candidates",()=>{let r=na(e,{scope:t,...Ce.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return TD(r,E3)})}function d3(e,t,n){return ve(e,n,"passthrough-candidates",()=>{let r=Zs(e,{scope:t,...Ce.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return TD(r,D3)})}function m3(e,t,n){return ve(e,n,"stale-abstractions",()=>{let r=ta(e,{scope:t,...Ce.stale,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}),i=r.filter(o=>o.consumers===0).length;return{count:r.length,loc:r.reduce((o,s)=>o+s.loc,0),files:[...new Set(r.map(o=>o.file))],unused:i,singleUse:r.length-i}})}function f3(e,t){return ve(e,t,"git-evidence",()=>{let n=ft(e,{historyMode:t.gitHistoryMode}),r=n.fileChurn();if(!r)return null;let i=n.commitHistory(),o=Vs(e,void 0,{limit:t.candidateResultLimit,historyMode:t.gitHistoryMode}),s={};for(let[a,c]of r)s[a]={changes:c.changes,fixChanges:c.fixChanges};return{amplification:n.changeAmplification(),hiddenCoupling:{pairCount:o.findings.length,scoreCount:Rg(o.findings.reduce((a,c)=>a+kD(c),0)),top:o.findings.slice(0,5).map(a=>({fileA:a.fileA,fileB:a.fileB,together:a.together,confidence:a.confidence,focusedTogether:a.focusedTogether,broadTogether:a.broadTogether,broadCommitRatio:a.broadCommitRatio,lastTogetherAt:a.lastTogetherAt,recentTogether:a.recentTogether,commitScope:a.commitScope,recency:a.recency,scoreWeight:kD(a),subjectContext:a.subjectContext}))},fileStats:s,commitsScanned:i?.commits.length??0}})}function p3(e,t){return ve(e,t,"suppressions",()=>{let n=Zl(e);return{total:n.total,byCategory:{...n.byCategory}}})}function g3(e,t){return ve(e,t,"coverage-contracts",()=>{let n=e.config.coverageContracts??[],i=xE(e,n).filter(o=>o.status!=="ok");return{count:i.length,loc:0,files:[...new Set(i.map(o=>o.file))].sort()}})}function h3(e,t,n){return ve(e,n,"drift",()=>{let r=Qs(e,{scope:t,...Ce.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY,semantic:n.semantic}),i=r.results.filter(a=>a.kind!=="pattern-deviation"),o=i.filter(a=>a.actionTier==="direct").length,s=i.length-o;return{count:i.length,unusedImports:r.unusedImports,architectureViolations:r.architectureViolations,layerViolations:r.layerViolations,direct:o,signal:s}})}function y3(e,t,n){return ve(e,n,"complexity-hotspots",()=>{let r=pg(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return{top:r.slice(0,5).map(i=>({symbol:i.shortName,score:i.score,file:i.file})),extremeCount:r.filter(i=>i.score>q6).length}})}function b3(e,t){let n=e.symbols>=U6||e.documents>=V6,r=t?Number.POSITIVE_INFINITY:DD,i=t?Number.POSITIVE_INFINITY:z6;return!n||t?{candidateScanLimit:void 0,candidateResultLimit:r,complexityResultLimit:i,semantic:!0,gitHistoryMode:t?"full":"bounded",releaseCachesBetweenPhases:!0,warnings:t&&n?["Large index detected; running health without candidate scan or result caps because full mode is enabled."]:[]}:{candidateScanLimit:ED,candidateResultLimit:r,complexityResultLimit:i,semantic:!1,gitHistoryMode:"bounded",releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${ED} symbols and reported their top ${DD} findings. Enable full mode for unbounded candidate counts.`]}}function S3(e,t){t.releaseCachesBetweenPhases&&(tp(e),yg())}function ve(e,t,n,r){x3(n);try{return r()}finally{S3(e,t)}}function x3(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function R3(e,t){return t.filter(n=>!Ue(e,n.relativePath)&&!Re(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function C3(e,t){return t.filter(n=>!Ue(e,n.relativePath)&&!Re(e,n.symbol,n.relativePath))}function iu(e){let t=new Set;for(let n of e){let r=n.relativePath??n.file;r&&t.add(r)}return{count:e.length,loc:e.reduce((n,r)=>n+r.loc,0),files:[...t]}}function TD(e,t){return{...iu(e),scoreCount:Rg(e.reduce((r,i)=>r+t(i),0))}}function v3(e){let t=new Map;for(let n of e)t.set(n.file,Math.max(t.get(n.file)??0,n.loc));return{count:t.size,loc:[...t.values()].reduce((n,r)=>n+r,0),files:[...t.keys()]}}function xg(e){let t=new Map;for(let n of e)t.set(n.fileA,Math.max(t.get(n.fileA)??0,n.locA)),t.set(n.fileB,Math.max(t.get(n.fileB)??0,n.locB));return{count:e.length,loc:[...t.values()].reduce((n,r)=>n+r,0),files:[...t.keys()]}}function FD(e,t){return{...xg(e),scoreCount:Rg(e.reduce((r,i)=>r+t(i),0))}}function I3(e){let t=e.sharedHooks.length>0,n=_D({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:AD(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function w3(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=_D({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:AD(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function _D(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!MD.has(LD(t))).length+Math.min(e.functions.length,3)}function AD(e,t,n){let r=[...e,...t,...n].map(LD);return r.length>0&&r.every(i=>MD.has(i))}function LD(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function E3(e){return e.actionTier==="signal"?.25:1}function D3(e){return e.actionTier==="signal"?.25:1}function kD(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 Rg(e){return Math.round(e*100)/100}var MD=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"]);var Cg=864e5;function rEe(e,t={}){let r=[...t.check?e.filter(u=>u.check===t.check):[...e]].sort((u,d)=>u.ts-d.ts),i=new Map;for(let u of r){let d=`${u.check}\0${u.findingId}`,m=i.get(d);m||(m={check:u.check,findingId:u.findingId,caughtAt:u.ts,events:[]},i.set(d,m)),m.events.push(u)}let o=[...i.values()].filter(u=>t.sinceMs===void 0||u.caughtAt>=t.sinceMs),s=T3(r),a=new Map;for(let u of o){let d=a.get(u.check)??[];d.push(u),a.set(u.check,d)}let c=[];for(let[u,d]of a){let m=0,f=0,p=0,g=0,y=0,h=0,S=[];for(let v of d){p+=v.events.filter(I=>I.event==="reopened").length;let C=v.events[v.events.length-1],w=`${v.check}\0${v.findingId}`;if(C.event==="resolved"&&s.has(w))g+=1;else if(C.event==="resolved"){let I=SD(v.events.slice(0,-1)),P=I?.comparisonBaseCommit??I?.commit,_=C.comparisonBaseCommit??C.commit;P&&(_===P||C.verifiedAgainstCommit===P)?(m+=1,S.push((C.ts-v.caughtAt)/Cg)):y+=1}else C.event==="suppressed"?f+=1:h+=1}let b=m+f,R=vg(d.flatMap(v=>v.events),t.protectedGateRunIds),x=b>0?m/b:null;c.push({check:u,caught:d.length,fixed:m,suppressed:f,reopened:p,moved:g,unverified:y,open:h,authority:R,resolutionVsSuppressionRate:x,precision:R==="protected-external-evaluation"?x:null,medianDaysToFix:S.length>0?F3(S):null})}let l=o.flatMap(u=>u.events);return{totalEvents:r.length,windowStart:t.sinceMs??null,authority:vg(l,t.protectedGateRunIds),provenance:P3(l,t.protectedGateRunIds),anomalies:k3(o,c,t.protectedGateRunIds),checks:c.sort((u,d)=>u.check.localeCompare(d.check))}}function vg(e,t){if(e.length===0)return"no-data";let n=e.filter(r=>Ig(r,t)).length;return n===e.length?"protected-external-evaluation":n>0?"mixed-authority-telemetry":"local-writable-telemetry"}function P3(e,t){let n=new Set(e.flatMap(o=>o.gateRunId?[o.gateRunId]:[])),r=e.filter(o=>o.observer?.authority==="protected-external"),i=r.filter(o=>Ig(o,t));return{localAgentEvents:e.filter(o=>o.observer?.kind==="local-agent").length,localHumanEvents:e.filter(o=>o.observer?.kind==="local-human").length,protectedCiEvents:e.filter(o=>o.observer?.kind==="protected-ci").length,legacyUnknownEvents:e.filter(o=>o.observer===void 0).length,repositoryWritableEvents:e.filter(o=>o.observer?.authority==="repository-writable").length,protectedExternalEvents:r.length,attestedProtectedEvents:i.length,unattestedProtectedClaims:r.length-i.length,distinctGateRuns:n.size,missingGateRunIdEvents:e.filter(o=>o.gateRunId===void 0).length}}function k3(e,t,n){let r=e.flatMap(l=>l.events),i=[],o=l=>l.slice(0,5).map(u=>({check:u.check,findingId:u.findingId,...u.gateRunId?{gateRunId:u.gateRunId}:{}})),s=r.filter(l=>l.observer===void 0);s.length>0&&i.push({code:"legacy-provenance-missing",message:`${s.length} event(s) predate observer provenance and remain repository-writable telemetry.`,samples:o(s)});let a=r.filter(l=>l.gateRunId===void 0);a.length>0&&i.push({code:"gate-run-identity-missing",message:`${a.length} event(s) lack an originating gate-run identity.`,samples:o(a)});let c=r.filter(l=>l.observer?.authority==="protected-external"&&!Ig(l,n));c.length>0&&i.push({code:"unattested-protected-claim",message:`${c.length} event(s) claim protected authority without a separately supplied gate-run attestation; they remain writable telemetry.`,samples:o(c)}),vg(r,n)==="mixed-authority-telemetry"&&i.push({code:"mixed-observer-authority",message:"Protected external observations and repository-writable observations are mixed; no precision claim is valid.",samples:o(r)});for(let l of t){if(!Yc(l.suppressed,l.caught))continue;let u=r.filter(d=>d.check===l.check&&d.event==="suppressed");i.push({code:"automatic-suppression-rate",message:`${l.check} suppressed ${l.suppressed} of ${l.caught} finding lifecycle(s), above the automatic calibration threshold.`,samples:o(u)})}return i}function Ig(e,t){return e.observer?.kind==="protected-ci"&&e.observer.authority==="protected-external"&&e.gateRunId!==void 0&&t?.has(e.gateRunId)===!0}function T3(e){let t=new Map;for(let i of e){if(i.event!=="caught"||!i.commit||!i.symbol)continue;let o=t.get(i.commit)??[];o.push(i),t.set(i.commit,o)}let n=new Map;for(let i of e)i.event==="caught"&&i.symbol&&n.set(`${i.check}\0${i.findingId}`,i.symbol);let r=new Set;for(let i of e){if(i.event!=="resolved"||!i.commit)continue;let o=`${i.check}\0${i.findingId}`,s=i.symbol??n.get(o);if(!s)continue;(t.get(i.commit)??[]).some(c=>c.check===i.check&&c.symbol===s&&c.findingId!==i.findingId)&&r.add(o)}return r}function iEe(e,t){let n=/^(\d+)([dw])$/.exec(e.trim());if(n){let i=Number(n[1]),o=n[2]==="w"?7*Cg:Cg;return t-i*o}let r=Date.parse(e);return Number.isNaN(r)?null:r}function F3(e){let t=[...e].sort((r,i)=>r-i),n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function _3(e,t,n,r={}){let i=lp(e,t,n,r);return i?{symbolA:i.symbolA,symbolB:i.symbolB,similarity:i.similarity,sharedCallees:i.sharedEvidence,uniqueToA:i.uniqueToA,uniqueToB:i.uniqueToB,consolidationStrategy:i.consolidationStrategy}:null}function A3(e,t={}){let{scope:n,limit:r}=t,i=new F(e),o=G3([...L3(e,n),...O3(e,i,n)]);return q3(o),r?o.slice(0,r):o}function L3(e,t){let n=[];for(let r of M3(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||qf(e,r.barrel_path)||k(e,r.barrel_path)&&Ja(e,r.barrel_path).length===0)continue;let i=N3(e,r),o=i?.barrel_consumers??0,s=i?.direct_consumers??0;o!==0||s!==0||n.push({barrelFile:r.barrel_path,symbol:r.symbol,shortName:E(r.symbol),originalFile:r.original_path,barrelConsumers:o,directConsumers:s,...OD(e,r.barrel_path)})}return n}function M3(e,t){let n=t?"AND barrel_d.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`WITH barrel_refs AS MATERIALIZED (
|
|
861
|
+
SELECT DISTINCT
|
|
862
|
+
barrel_d.id AS barrel_doc_id,
|
|
863
|
+
barrel_d.relative_path AS barrel_path,
|
|
864
|
+
m.symbol_id
|
|
865
|
+
FROM documents barrel_d
|
|
866
|
+
JOIN chunks c ON c.document_id = barrel_d.id
|
|
867
|
+
JOIN mentions m ON m.chunk_id = c.id
|
|
868
|
+
WHERE m.role != 1
|
|
869
|
+
AND (barrel_d.relative_path LIKE '%/index.ts'
|
|
870
|
+
OR barrel_d.relative_path LIKE '%/index.js'
|
|
871
|
+
OR barrel_d.relative_path = 'index.ts'
|
|
872
|
+
OR barrel_d.relative_path = 'index.js')
|
|
873
|
+
${e.pathExclusionsFor("barrel_d")}
|
|
874
|
+
${n}
|
|
875
|
+
),
|
|
876
|
+
sym_def AS MATERIALIZED (
|
|
877
|
+
SELECT m2.symbol_id, c2.document_id
|
|
878
|
+
FROM barrel_refs br
|
|
879
|
+
-- Keep the bounded barrel-symbol set on the outer side. An ordinary
|
|
880
|
+
-- JOIN lets SQLite scan every definition mention before applying the
|
|
881
|
+
-- barrel-symbol bloom filter on large indexes.
|
|
882
|
+
CROSS JOIN mentions m2 ON m2.symbol_id = br.symbol_id
|
|
883
|
+
AND m2.role = 1
|
|
884
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
885
|
+
GROUP BY m2.symbol_id
|
|
886
|
+
)
|
|
887
|
+
SELECT DISTINCT
|
|
888
|
+
br.barrel_doc_id,
|
|
889
|
+
br.barrel_path,
|
|
890
|
+
gs.id AS symbol_id,
|
|
891
|
+
gs.symbol AS symbol,
|
|
892
|
+
orig_d.id AS original_doc_id,
|
|
893
|
+
orig_d.relative_path AS original_path
|
|
894
|
+
FROM barrel_refs br
|
|
895
|
+
JOIN global_symbols gs ON br.symbol_id = gs.id
|
|
896
|
+
JOIN sym_def ON sym_def.symbol_id = gs.id
|
|
897
|
+
JOIN documents orig_d ON sym_def.document_id = orig_d.id
|
|
898
|
+
WHERE orig_d.id != br.barrel_doc_id
|
|
899
|
+
${e.pathExclusionsFor("orig_d")}
|
|
900
|
+
${e.symbolNoiseFor("gs")}
|
|
901
|
+
-- Only function-level symbols (ending with ().), not module-level
|
|
902
|
+
AND gs.symbol LIKE '%().'
|
|
903
|
+
ORDER BY br.barrel_path, gs.symbol`,...r)}function N3(e,t){return e.get(`SELECT
|
|
904
|
+
SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
|
|
905
|
+
SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
|
|
906
|
+
FROM (
|
|
907
|
+
SELECT
|
|
908
|
+
consumer_d.id AS consumer_doc_id,
|
|
909
|
+
MAX(CASE WHEN EXISTS (
|
|
910
|
+
SELECT 1
|
|
911
|
+
FROM mentions barrel_m
|
|
912
|
+
JOIN chunks barrel_c ON barrel_m.chunk_id = barrel_c.id
|
|
913
|
+
WHERE barrel_c.document_id = consumer_d.id
|
|
914
|
+
AND barrel_m.role != 1
|
|
915
|
+
AND barrel_m.symbol_id IN (
|
|
916
|
+
SELECT m2.symbol_id
|
|
917
|
+
FROM mentions m2
|
|
918
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
919
|
+
WHERE c2.document_id = ?
|
|
920
|
+
AND m2.role != 1
|
|
921
|
+
)
|
|
922
|
+
) THEN 1 ELSE 0 END) AS uses_barrel
|
|
923
|
+
FROM mentions ref_m
|
|
924
|
+
JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
|
|
925
|
+
JOIN documents consumer_d ON ref_c.document_id = consumer_d.id
|
|
926
|
+
WHERE ref_m.symbol_id = ?
|
|
927
|
+
AND ref_m.role != 1
|
|
928
|
+
AND consumer_d.id != ?
|
|
929
|
+
AND consumer_d.id != ?
|
|
930
|
+
${e.pathExclusionsFor("consumer_d")}
|
|
931
|
+
GROUP BY consumer_d.id
|
|
932
|
+
)`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function O3(e,t,n){let r=[],i=H3(e);for(let o of B3(e,n))BD(i,o,o)>0||r.push(...j3(e,t,o,i));return r}function B3(e,t){return L(e,{scope:t,includeIgnored:!1}).filter(n=>Ja(e,n).length>0||wn(e,n).length>0)}function j3(e,t,n,r){let i=Ja(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>ND(e,t,n,s.sourcePath,r,[$3(s.specifier)])),o=wn(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>ND(e,t,n,s.sourcePath,r,s.kind==="named"&&s.names.length>0?s.names:[s.kind==="star"?`* from ${s.sourcePath}`:`* namespace from ${s.sourcePath}`]));return[...i,...o]}function ND(e,t,n,r,i,o){let s=t.definitionsForFile(r);return o.map(a=>{let c=s.find(l=>l.leaf===a);return{barrelFile:n,symbol:c?.symbol??`source-reexport:${n}:${a}`,shortName:c?E(c.symbol):a,originalFile:r,barrelConsumers:0,directConsumers:BD(i,r,n),...OD(e,n)}})}function $3(e){return e.split("::").at(-1)?.split("/").at(-1)?.replace(/\.[^.]+$/,"")??e}function OD(e,t){return Mn(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 H3(e){let t=new Map;for(let n of L(e,{includeIgnored:!1}))for(let r of oe(e,n)){if(!r.sourcePath)continue;let i=t.get(r.sourcePath)??new Set;i.add(n),t.set(r.sourcePath,i)}return t}function BD(e,t,n){let r=e.get(t);return r?r.size-(r.has(n)?1:0):0}function G3(e){let t=new Set,n=[];for(let r of e){let i=`${r.barrelFile}|${r.symbol}|${r.originalFile}`;t.has(i)||(t.add(i),n.push(r))}return n}function q3(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function U3(e,t={}){let{samples:n=50,scope:r,maxDisagreements:i=5}=t,o=new F(e),s=V3(o.productionCallableDefinitions({scope:r,minLoc:2,requireFunctionLikeSymbol:!0}),n),a=z3(e,s);if(s.length===0||!a)return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let c={references:jD(),callees:jD()},l=[],u=0,d=a==="semantic"?$c(e,s):new Map,m=a==="source"?J3(e,o,s):null;for(let f of s){let p=ou(f,a==="semantic"?jc(e,f).map(R=>R.file):[...m?.referencesBySymbolId.get(f.symbolId)??[]]),g=ou(f,a==="semantic"?(d.get(f.symbolId)??[]).map(R=>R.file):[...m?.calleesBySymbolId.get(f.symbolId)??[]]);u+=1;let y=ou(f,nn(e,f,{semanticEvidence:q}).map(R=>R.file)),h=ou(f,(o.calleeMap([f],{semantic:!1}).get(f.symbolId)??[]).map(R=>R.file)),S=wg(a,"references"),b=wg(a,"callees");$D(c.references,f,"references",y,p,S,l),$D(c.callees,f,"callees",h,g,b,l)}return l.sort((f,p)=>p.cheapOnly.length+p.oracleOnly.length-(f.cheapOnly.length+f.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?Dg(u/s.length):0,oracleKind:a,scores:["references","callees"].map(f=>K3(f,c[f],a)),topDisagreements:l.slice(0,i)}}function jD(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0,skippedOraclePartial:0}}function V3(e,t){let n=[...e].sort((o,s)=>o.symbolId-s.symbolId);if(n.length<=t)return n;let r=n.length/t,i=[];for(let o=0;o<t;o++)i.push(n[Math.floor(o*r)]);return i}function z3(e,t){let n=t[0];if(!n)return null;if(Eg(e,n))return"source";try{if(mt(e).capability("semantic-references",n.relativePath).available)return"semantic"}catch{}return t.some(r=>Eg(e,r))?"source":null}function ou(e,t){let n=new Set;for(let r of t)r!==e.relativePath&&n.add(r);return n}function $D(e,t,n,r,i,o,s){if(!o&&i.size===0){e.skippedOraclePartial+=1;return}e.comparedSymbols+=1,e.cheapTotal+=r.size,e.oracleTotal+=i.size;let a=[],c=[];for(let l of r)i.has(l)?e.agreed+=1:a.push(l);for(let l of i)r.has(l)||c.push(l);(a.length>0||c.length>0)&&s.push({symbol:E(t.symbol),question:n,cheapOnly:a,oracleOnly:c})}var W3={references:!0,callees:!1};function K3(e,t,n){let r=t.oracleTotal>0?t.agreed/t.oracleTotal:1,i=t.cheapTotal-t.agreed,o=wg(n,e);return{question:e,comparedSymbols:t.comparedSymbols,precision:o&&t.cheapTotal>0?Dg(t.agreed/t.cheapTotal):null,recall:Dg(r),unverified:i,skippedOraclePartial:t.skippedOraclePartial}}function wg(e,t){return e==="semantic"?W3[t]:!1}function Eg(e,t){return N(t.relativePath)==="clojure"&&Y(e,t.relativePath)!==null}function J3(e,t,n){let r=new Map,i=new Map,o=n.filter(c=>Eg(e,c)),s=new Map;for(let c of o){let l=s.get(c.leaf)??[];l.push(c),s.set(c.leaf,l)}for(let c of t.sourceFiles()){if(N(c)!=="clojure")continue;let l=Y(e,c);if(l)for(let u of l.fileIdentifiers)for(let d of s.get(u)??[])HD(r,d.symbolId,c)}let a=new Map;for(let c of t.scopedDefinitions()){if(N(c.relativePath)!=="clojure")continue;let l=a.get(c.leaf)??[];l.push(c),a.set(c.leaf,l)}for(let c of o){let l=Y(e,c.relativePath);if(l){for(let u of l.callSites)if(!(u.line<c.startLine||u.line>c.endLine))for(let d of a.get(u.calleeLeaf)??[])HD(i,c.symbolId,d.relativePath)}}return{referencesBySymbolId:r,calleesBySymbolId:i}}function HD(e,t,n){let r=e.get(t);if(r){r.add(n);return}e.set(t,new Set([n]))}function Dg(e){return Math.round(e*1e3)/1e3}var Y3=new Set(ln());function X3(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o,maxShapeFrequency:s=12}=t,a=t.semantic!==!1,c=eZ(e,Q3(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:a,maxShapeFrequency:s}),l=nZ(c);return i?l.slice(0,i):l}function Q3(e,t){let n=Oe(e,{scope:t.scope}).filter(r=>Z3(r)&&!e.isIgnored(r.relativePath)).filter(r=>j(r)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((r,i)=>j(i)-j(r)||r.relativePath.localeCompare(i.relativePath)),fe(n,t.scanLimit)}function Z3(e){return!e.isFunctionLike||$e(e.symbol)?!1:e.kind===null||Y3.has(e.kind)}function eZ(e,t,n){let r=[];for(let s of t){let a=iZ(e,s,n);a&&r.push({signature:a,definition:s,fn:tZ(s)})}let i=new Map;for(let s of r)i.set(s.signature,(i.get(s.signature)??0)+1);let o=new Map;for(let s of r){let a=rZ(s.fn.loc),c=(i.get(s.signature)??0)>n.maxShapeFrequency,l=c?zp(e,s.definition):null;if(c&&!l)continue;let u=c?`${s.signature}\0body\0${l}`:`${s.signature}\0band\0${a}`,d=o.get(u)??{signature:s.signature,locBand:a,exactBody:c,functions:[]};d.functions.push(s.fn),o.set(u,d)}return[...o.values()]}function tZ(e){return{symbol:e.symbol,shortName:E(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:j(e)}}function nZ(e){let t=[];for(let n of e)n.functions.length>=2&&t.push(n);return t.sort((n,r)=>{let i=r.functions.length-n.functions.length;if(i!==0)return i;let o=n.functions.reduce((a,c)=>a+c.loc,0);return r.functions.reduce((a,c)=>a+c.loc,0)-o}),t}function rZ(e){return e<=5?"<=5":e<=20?"6-20":">20"}function iZ(e,t,n){if(n.semantic){let o=gR(e,t);if(o)return o}let r=oZ(t.documentation),i=r?cZ(r):null;return i||lZ(sZ(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function oZ(e){return En(Dn(e))}function sZ(e,t,n,r,i){let o=k(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=dZ(s,n,r,i);for(let c of a){let l=Math.min(s.length-1,Math.max(c,c+4)),u="";for(let d=c;d<=l;d+=1){let m=s[d]?.trim();if(m&&(u=u?`${u} ${m}`:m,aZ(u)))return u}if(u&&u.includes("("))return u}return null}function aZ(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||_o(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function cZ(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 lZ(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),r=n.indexOf("(");if(r===-1)return null;let i=n.slice(0,r),s=new RegExp(`\\b${H(t)}\\b`,"i").exec(i);s&&typeof s.index=="number"&&(i=i.slice(0,s.index)),i=i.replace(/\b(public|private|protected|internal|final|static|abstract|sealed|virtual|override|async|suspend|inline|constexpr|consteval|constinit|const|pub|fn|function|def|sub|friend|shared|readonly|new|open|partial|export)\b/gi," ").replace(/\s+/g," ").trim();let a=uZ(n.slice(r)).replace(/\)\s*=\s*[\s\S]*$/,")").replace(/\s+throws\s+[^={]+$/i,"").replace(/\s+where\s+.+$/i,"").replace(/\s+/g," ").trim();if(!a.startsWith("("))return null;let c=`${i?`${i} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return c.length>=3?c:null}function uZ(e){let t=0,n=0,r=0,i=0,o=null,s=!1;for(let a=0;a<e.length;a+=1){let c=e[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c===o&&(o=null);continue}if(c==='"'||c==="'"||c==="`"){o=c;continue}if(c==="(")t+=1;else if(c===")")t=Math.max(0,t-1);else if(c==="[")r+=1;else if(c==="]")r=Math.max(0,r-1);else if(c==="<")i+=1;else if(c===">")i=Math.max(0,i-1);else if(c==="{"){if(t===0&&r===0&&i===0)return e.slice(0,a);n+=1}else if(c==="}")n=Math.max(0,n-1);else if(c==="="&&e[a+1]===">"&&t===0&&n===0&&r===0&&i===0)return e.slice(0,a)}return e}function dZ(e,t,n,r){let i=H(r),o=new RegExp(`\\b${i}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${i}\\b`,"i"),a=[],c=new Set,l=Math.max(0,Math.min(t,e.length-1)),u=Math.max(l,Math.min(e.length-1,Math.max(n,t+4)));for(let d=l;d<=u;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}for(let d=0;d<e.length;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}return a}import{spawnSync as pZ}from"child_process";import{spawn as fZ}from"child_process";import{platform as GD}from"os";import{performance as qD}from"perf_hooks";var Pg={probe:1e4,git:3e4,analysis:18e4,install:3e5,indexer:6e5},ri=class extends Error{constructor(n,r,i,o={}){super(i,o.cause===void 0?void 0:{cause:o.cause});this.kind=n;this.label=r;this.name="BoundedProcessError",this.timedOut=o.timedOut??!1,this.reaped=o.reaped??!1,this.stdout=o.stdout??"",this.stderr=o.stderr??"",this.stdoutTruncated=o.stdoutTruncated??!1,this.stderrTruncated=o.stderrTruncated??!1}kind;label;timedOut;reaped;stdout;stderr;stdoutTruncated;stderrTruncated};function aa(e,t){if(!Number.isFinite(e)||e<=0)throw new TypeError(`${t} must be a positive finite number.`)}function UD(e,t,n,r){let i=Math.max(0,r-n);i>0&&e.push(t.subarray(0,i))}function VD(e,t,n){let r=Buffer.concat([...e,t]);e.length=0,e.push(r.subarray(Math.max(0,r.length-n)))}function zD(e){aa(e.timeoutMs,"timeoutMs"),aa(e.maxStdoutBytes,"maxStdoutBytes"),aa(e.maxStderrBytes,"maxStderrBytes");let t=e.terminationGraceMs??1e3;aa(t,"terminationGraceMs");let n=e.terminationForceMs??t;return aa(n,"terminationForceMs"),new Promise((r,i)=>{let o=qD.now(),s;try{let v=GD()!=="win32";s=fZ(e.command,[...e.args??[]],{cwd:e.cwd,env:e.env,detached:v?!0:e.detached,stdio:["pipe","pipe","pipe"]})}catch(v){i(new ri("spawn",e.label,`${e.label} could not start.`,{cause:v,reaped:!0}));return}let a=[],c=[],l=0,u=0,d=!1,m=!1,f=null,p=!1,g=GD()!=="win32",y=s.pid===void 0?null:jS(s.pid,g),h=()=>{clearTimeout(R),e.signal?.removeEventListener("abort",x)},S=v=>{if(p||!f)return;p=!0,h();let C=Buffer.concat(a).toString("utf8"),w=Buffer.concat(c).toString("utf8"),I=v.reaped||!v.detail?"":` Process-tree cleanup failed: ${v.detail}`;i(new ri(f.kind,e.label,`${f.message}${I}`,{timedOut:f.timedOut,reaped:v.reaped,stdout:C,stderr:w,stdoutTruncated:d,stderrTruncated:m}))},b=v=>{if(!(f||p)){if(f=v,!y){S({reaped:s.pid===void 0,reason:s.pid===void 0?"terminated":"identity-unavailable"});return}hc(y,{gracefulMs:t,forceMs:n}).then(S,C=>{S({reaped:!1,reason:"signal-failed",detail:C instanceof Error?C.message:String(C)})})}},R=setTimeout(()=>{b({kind:"timeout",timedOut:!0,message:`${e.label} timed out after ${e.timeoutMs}ms.`})},e.timeoutMs);R.unref();let x=()=>{b({kind:"aborted",timedOut:!1,message:`${e.label} was cancelled.`})};e.signal?.addEventListener("abort",x,{once:!0}),e.signal?.aborted&&x(),s.stdout.on("data",v=>{let C=Buffer.isBuffer(v)?v:Buffer.from(v);e.outputLimitBehavior==="truncate-tail"?VD(a,C,e.maxStdoutBytes):UD(a,C,l,e.maxStdoutBytes),l+=C.length,l>e.maxStdoutBytes&&(d=!0,e.outputLimitBehavior!=="truncate-tail"&&b({kind:"stdout-limit",timedOut:!1,message:`${e.label} exceeded stdout limit (${e.maxStdoutBytes} bytes).`}))}),s.stderr.on("data",v=>{let C=Buffer.isBuffer(v)?v:Buffer.from(v);e.outputLimitBehavior==="truncate-tail"?VD(c,C,e.maxStderrBytes):UD(c,C,u,e.maxStderrBytes),u+=C.length,u>e.maxStderrBytes&&(m=!0,e.outputLimitBehavior!=="truncate-tail"&&b({kind:"stderr-limit",timedOut:!1,message:`${e.label} exceeded stderr limit (${e.maxStderrBytes} bytes).`}))}),s.on("error",v=>{if(!p&&!f){if(s.pid===void 0){h(),p=!0,i(new ri("spawn",e.label,`${e.label} could not start: ${v.message}`,{cause:v,reaped:!0}));return}b({kind:"spawn",timedOut:!1,message:`${e.label} failed after start: ${v.message}`})}}),s.on("close",(v,C)=>{if(p||f)return;p=!0,h();let w=Buffer.concat(a).toString("utf8"),I=Buffer.concat(c).toString("utf8");r({status:v,signal:C,stdout:w,stderr:I,timedOut:!1,durationMs:qD.now()-o,stdoutTruncated:d,stderrTruncated:m})}),e.input===void 0?s.stdin.end():s.stdin.end(e.input)})}var Tg="scip-query-isolated-analysis",Fg=1;function WD(e){let t=[...e??[]];return t.includes("--json")?t:["--json",...t]}var ii=class extends Error{constructor(n,r,i=!0){super(`${n} timed out after ${r}ms.`);this.label=n;this.timeoutMs=r;this.reaped=i;this.name="IsolatedProcessTimeoutError"}label;timeoutMs;reaped;timedOut=!0};function tPe(e,t){Xi(JSON.stringify({protocol:Tg,schemaVersion:Fg,producer:{name:"scip-query",version:wt},command:e,result:t}))}function nPe(e){let t=e.timeoutMs??Pg.analysis,n=pZ(process.execPath,[...process.execArgv,e.cliPath,e.command,...WD(e.args)],{cwd:process.cwd(),env:e.env??process.env,encoding:"utf8",maxBuffer:e.maxBuffer??10*1024*1024,timeout:t,killSignal:"SIGKILL"});if(n.error&&n.error.code==="ETIMEDOUT")throw new ii(e.label,t);if(n.status!==0){let r=n.stderr.trim();throw new Error(`${e.label} failed${r?`:
|
|
933
|
+
${r}`:""}`)}return JD(n.stdout,e)}function KD(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function su(e){let t=e.timeoutMs??Pg.analysis,n=e.maxBuffer??10*1024*1024;return zD({command:process.execPath,args:[...process.execArgv,e.cliPath,e.command,...WD(e.args)],cwd:process.cwd(),env:e.env??process.env,label:e.label,timeoutMs:t,maxStdoutBytes:n,maxStderrBytes:n}).catch(r=>{throw r instanceof ri&&r.kind==="timeout"?new ii(e.label,t,r.reaped):r}).then(r=>{let i=r.stderr.trim();if(r.status!==0)throw new Error(`${e.label} failed${i?`:
|
|
934
|
+
${i}`:""}`);return JD(r.stdout,e)})}function JD(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(!V(n))throw new Error(`${t.label} returned a non-object isolated-analysis message.`);if(n.protocol!==Tg)throw new Error(`${t.label} returned protocol ${kg(n.protocol)}; expected ${Tg}.`);if(n.schemaVersion!==Fg)throw new Error(`${t.label} returned unsupported isolated-analysis schemaVersion ${kg(n.schemaVersion)}; expected ${Fg}.`);if(!gZ(n.producer))throw new Error(`${t.label} did not identify a scip-query producer version.`);if(n.command!==t.command)throw new Error(`${t.label} returned result for command ${kg(n.command)}; expected ${t.command}.`);if(!Object.hasOwn(n,"result"))throw new Error(`${t.label} omitted the isolated-analysis result.`);return n.result}function gZ(e){return V(e)&&e.name==="scip-query"&&typeof e.version=="string"&&e.version.length>0}function kg(e){return typeof e=="string"?JSON.stringify(e):String(e)}async function _g(e,t,n){let r=new Array(e.length),i=0;async function o(){for(;i<e.length;){let s=i++;r[s]=await n(e[s])}}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),r}function YD(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let o=t.find(a=>a.has(i));if(!o){n.add(i),r.push([i]);continue}let s=e.filter(a=>o.has(a));s.forEach(a=>n.add(a)),r.push(s)}return r}import{spawnSync as hZ}from"child_process";import{existsSync as yZ,mkdirSync as bZ,renameSync as SZ,writeFileSync as xZ}from"fs";import{dirname as XD,join as RZ}from"path";var au=3,CZ="health-report-cache.json";function Ag(e,t,n,r=EZ()){let i=We(e);return i?{version:au,projectFingerprint:i,cliVersion:n,scope:t.scope??null,full:t.full===!0,phaseTimeoutMs:t.phaseTimeoutMs??null,gitHead:r.gitHead(e.config.projectRoot)}:null}function QD(e,t,n=nP()){let r=eP(e),i=tP(t),o=!1;return D("health.report-cache.read",()=>{if(!n.existsSync(r))return null;try{let s=JSON.parse(n.readFile(r));return!vZ(s)||s.keyHash!==i?null:(o=!0,s.report)}catch{return null}},()=>({available:!0,hit:o,keyHash:i}))}function ZD(e,t,n,r=nP()){let i=eP(e),o={version:au,keyHash:tP(t),key:t,writtenAt:r.nowIso(),report:n};r.mkdirSync(XD(i),{recursive:!0});let s=`${i}.${process.pid}.${Date.now()}.tmp`;r.writeFileSync(s,JSON.stringify(o)),r.renameSync(s,i)}function eP(e){return RZ(XD(e.config.dbPath),CZ)}function tP(e){return ke(JSON.stringify(e))}function vZ(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===au&&typeof t.keyHash=="string"&&IZ(t.key)&&typeof t.writtenAt=="string"&&wZ(t.report)}function IZ(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===au&&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 wZ(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.score=="number"&&typeof t.riskScore=="number"&&typeof t.hygieneScore=="number"&&typeof t.overview=="object"&&typeof t.findings=="object"&&Array.isArray(t.scoreBreakdown)&&Array.isArray(t.actions)&&Array.isArray(t.pressure)&&Array.isArray(t.topComplexity)&&Array.isArray(t.detectorPrecision)}function EZ(){return{gitHead(e){let t=hZ("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:3e4,killSignal:"SIGKILL"});return t.status===0?t.stdout.trim():null}}}function nP(){return{existsSync:yZ,mkdirSync:bZ,readFile:e=>O(e,"health report cache"),renameSync:SZ,writeFileSync:xZ,nowIso:()=>new Date().toISOString()}}var oP="__health-phase",PZ="__diff-impact-batch",kZ=10,TZ=4,FZ=8,_Z=25e3,AZ=2500,Lg=2500,LZ=4,MZ=12,rP=3e4,sP=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),aP=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]),NZ=new Set([...aP,"suppressions"]),OZ=new Set(["similar","extract-candidates"]),cu=2,iP=Pr({kind:"health-semantic-prewarm",invalidation:re("health-semantic-prewarm"),serialize:e=>JSON.stringify(e),deserialize:BZ});function BZ(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return n.version!==cu||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:cu,definitions:n.definitions,referenceCacheWrites:n.referenceCacheWrites,referenceIncomplete:n.referenceIncomplete,calleeRows:n.calleeRows,warmedAt:n.warmedAt}}catch{return null}}function cP(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
|
|
935
|
+
`)}function jZ(e){let t=Zr(e);return t.symbols>=_Z||t.documents>=AZ}function lP(e,t,n,r={}){return jZ(e)?n?(r.quiet||console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0}):(r.quiet||console.error(`Large index detected; ${t} will scan the highest-priority ${Lg} candidates with semantic enrichment disabled. Run "scip-query ${t} --full" for the unbounded semantic pass.`),{scanLimit:Lg,semantic:!1,analysisBudget:{scanLimit:Lg,semanticEnrichment:!1,reason:"large index default budget; pass --full for unbounded semantic analysis"}}):{semantic:!0}}function PPe(e){return e?`analysis budget: scanning up to ${e.scanLimit} candidate(s); semantic enrichment=${e.semanticEnrichment}; ${e.reason}`:null}var $Z={env:process.env,projectFingerprint:We,semanticEngineFingerprint:UZ,readMarker:(e,t,n)=>iP.read(e,t,n),writeMarker:(e,t,n,r)=>iP.write(e,t,n,r),candidateDefinitions:(e,t)=>new F(e).scopedDefinitions(t.scope).filter(n=>qe(n.relativePath)!==null),materializeReferences:(e,t,n)=>mt(e).materializeReferences(t,n),materializeCallees:Vm};function HZ(e,t,n=$Z){if(t.full!==!0)return Rr("default-mode");if((n.env??process.env).SCIP_QUERY_HEALTH_SEMANTIC_PREWARM==="0")return Rr("disabled");let r=Rr("error");return D("health.semantic-prewarm",()=>{try{r=GZ(e,t,n)}catch(i){r=Rr("error",{error:i instanceof Error?i.message:String(i)})}return r},()=>VZ(r))}function GZ(e,t,n){let r=n.projectFingerprint(e);if(!r)return Rr("missing-project-fingerprint");let i=qZ(t,n.semanticEngineFingerprint(e)),o=n.readMarker(e,i,r);if(o&&o.referenceIncomplete===0)return Rr("cache-hit");let s=[];if(s=D("health.semantic-prewarm.candidate-definitions",()=>(s=n.candidateDefinitions(e,t),s),()=>({definitions:s.length})),s.length===0)return Rr("no-semantic-definitions");let a=0,c=D("health.semantic-prewarm.references",()=>{let m=n.materializeReferences(e,s,{prefetchCallees:!0});return a=m.cacheHits+m.cacheWrites+m.inMemoryHits,m},()=>({definitions:s.length,rows:a}));if(c.cacheHits+c.cacheWrites+c.inMemoryHits===0&&c.misses+c.unkeyed>0)return Rr("provider-unavailable",{definitions:s.length,referenceMisses:c.misses});let u=0,d=D("health.semantic-prewarm.callees",()=>{let m=n.materializeCallees(e,s);return u=m.size,m},()=>({definitions:s.length,rows:u}));return c.incomplete>0?{status:"partial",reason:"incomplete-references",definitions:s.length,referenceCacheHits:c.cacheHits,referenceCacheWrites:c.cacheWrites,referenceMisses:c.misses,referenceIncomplete:c.incomplete,calleeRows:d.size}:(D("health.semantic-prewarm.marker-write",()=>n.writeMarker(e,i,r,{version:cu,definitions:s.length,referenceCacheWrites:c.cacheWrites,referenceIncomplete:c.incomplete,calleeRows:d.size,warmedAt:Date.now()})),{status:"warmed",reason:"cache-miss",definitions:s.length,referenceCacheHits:c.cacheHits,referenceCacheWrites:c.cacheWrites,referenceMisses:c.misses,referenceIncomplete:c.incomplete,calleeRows:d.size})}function qZ(e,t){return JSON.stringify({version:cu,cliVersion:wt,semanticEngineFingerprint:t,scope:e.scope??null})}function UZ(e){return ke(JSON.stringify({kind:"health-semantic-prewarm-engine",rust:Gr(e.config.projectRoot)}))}function Rr(e,t={}){return{status:"skipped",reason:e,definitions:0,referenceCacheHits:0,referenceCacheWrites:0,referenceMisses:0,referenceIncomplete:0,calleeRows:0,...t}}function VZ(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}}async function kPe(e){let t=XZ(e),n={...e,phaseTimeoutMs:t??null},r=An(m=>{let f=Ag(m,n,wt);if(!f)return null;let p=QD(m,f);return p?(p.detectorPrecision=gg(hg(m),Date.now()),p):null});if(r)return r;let{applicability:i,overview:o}=An(m=>({applicability:zZ(m,e),overview:bg(m,"overview",e)})),s=new Map;s.set("overview",o);let a=ru.filter(m=>m==="overview"?!1:WZ(m,i)?!0:(s.set(m,oi(m)),!1)),c=KZ(a);e.full&&An(m=>HZ(m,e));let l=await _g(c,QZ(c.length),m=>JZ(m,e,t)),u=[];if(l.flat().forEach(m=>{m.healthPhaseMeta&&u.push(`Health phase "${m.phase}" deferred: ${m.healthPhaseMeta.reason}. Run health --full for exhaustive analysis.`),s.set(m.phase,m)}),u.length>0){let m=s.get("overview");s.set("overview",{...m,warnings:[...m.warnings,...u]})}let d=Sg(ru.map(m=>s.get(m)));return d.detectorPrecision=An(m=>gg(hg(m),Date.now())),An(m=>{let f=Ag(m,n,wt);f&&ZD(m,f,d)}),d}function zZ(e,t){return $a(e,{scope:t.scope})}function WZ(e,t){return sP.has(e)?t.react:aP.has(e)?t.vue:!0}function KZ(e){return YD(e,[sP,NZ,OZ])}function oi(e){switch(e){case"react-component-duplicates":return{phase:e,reactComponentDuplicates:{count:0,loc:0,files:[]}};case"react-hook-candidates":return{phase:e,reactHookCandidates:{count:0,loc:0,files:[]}};case"react-large-component-pressure":return{phase:e,reactLargeComponentPressure:{count:0,loc:0,files:[]}};case"vue-component-duplicates":return{phase:e,vueComponentDuplicates:{count:0,loc:0,files:[]}};case"vue-composable-candidates":return{phase:e,vueComposableCandidates:{count:0,loc:0,files:[]}};case"vue-large-view-pressure":return{phase:e,vueLargeViewPressure:{count:0,loc:0,files:[]}};default:throw new Error(`Health phase "${e}" cannot be synthesized.`)}}function JZ(e,t,n){if(e.length===1)return YZ(e[0],t,n).then(s=>[s]);let r=e.join(","),i=process.argv[1]??Ng(import.meta.url),o=[r];return t.scope&&o.push("--scope",t.scope),t.full&&o.push("--full"),su({cliPath:i,command:oP,args:o,label:`Health phases "${r}"`,timeoutMs:n}).catch(s=>{if(t.full||!(s instanceof ii))throw s;return e.map(a=>uP(a,s.timeoutMs,`timed out after ${s.timeoutMs}ms`))})}function YZ(e,t,n){let r=process.argv[1]??Ng(import.meta.url),i=[e];return t.scope&&i.push("--scope",t.scope),t.full&&i.push("--full"),su({cliPath:r,command:oP,args:i,label:`Health phase "${e}"`,timeoutMs:n}).catch(o=>{if(t.full||!(o instanceof ii))throw o;return uP(e,o.timeoutMs,`timed out after ${o.timeoutMs}ms`)})}function XZ(e,t=process.env){if(e.full)return;let n=t.SCIP_QUERY_HEALTH_PHASE_TIMEOUT_MS;if(!n)return rP;let r=parseInt(n,10);return!Number.isFinite(r)||r<0?rP:r===0?void 0:r}function uP(e,t,n){let r={healthPhaseMeta:{status:"deferred",reason:n,timeoutMs:t}};switch(e){case"overview":throw new Error("Overview health phase cannot be deferred.");case"dead":return{phase:e,dead:{count:0,loc:0,files:[]},...r};case"isolated":return{phase:e,isolated:{count:0,loc:0,files:[]},...r};case"cycles":return{phase:e,realCycleCount:0,...r};case"similar":return{phase:e,similarCount:0,...r};case"duplicate-bodies":return{phase:e,duplicateBodies:{count:0,loc:0,files:[]},...r};case"twin-drift":return{phase:e,twinDrift:{count:0,loc:0,files:[]},...r};case"react-component-duplicates":return{...oi(e),...r};case"react-hook-candidates":return{...oi(e),...r};case"react-large-component-pressure":return{...oi(e),...r};case"vue-component-duplicates":return{...oi(e),...r};case"vue-composable-candidates":return{...oi(e),...r};case"vue-large-view-pressure":return{...oi(e),...r};case"extract-candidates":return{phase:e,extractCount:0,...r};case"wrapper-candidates":return{phase:e,wrappers:{count:0,loc:0,files:[]},...r};case"passthrough-candidates":return{phase:e,passthroughs:{count:0,loc:0,files:[]},...r};case"stale-abstractions":return{phase:e,stale:{count:0,loc:0,files:[],unused:0,singleUse:0},...r};case"drift":return{phase:e,drift:{count:0,unusedImports:0,architectureViolations:0,layerViolations:0,direct:0,signal:0},...r};case"complexity-hotspots":return{phase:e,complexity:{top:[],extremeCount:0},...r};case"git-evidence":return{phase:e,gitEvidence:null,...r};case"suppressions":return{phase:e,suppressions:{total:0,byCategory:{}},...r};case"coverage-contracts":return{phase:e,coverageContracts:{count:0,loc:0,files:[]},...r}}}var QZ=dP({envKey:"SCIP_QUERY_HEALTH_CONCURRENCY",defaultMinimum:LZ,defaultMaximum:MZ});function TPe(e){if(console.log(`
|
|
936
|
+
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)
|
|
937
|
+
`),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${fv(e.overview.indexSizeBytes)}
|
|
938
|
+
`),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: ${Mg(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: ${Mg(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: ${Mg(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(`
|
|
939
|
+
Prioritized Actions (highest impact + lowest effort first):`);for(let n=0;n<e.actions.length;n++){let r=e.actions[n],i=r.locRecoverable>0?` (~${r.locRecoverable} LOC involved)`:"";console.log(` ${n+1}. [${r.effort} effort / ${r.impact} impact] ${r.description}${i}`)}}if(e.topComplexity.length>0){console.log(`
|
|
940
|
+
Top Complexity Hotspots:`);for(let n of e.topComplexity)console.log(` ${n.score.toFixed(1).padStart(6)} ${n.symbol}`)}if(t9(e),e9(e),e.scoreBreakdown.length>0){console.log(`
|
|
941
|
+
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?`
|
|
942
|
+
No findings from completed analyses. Review warnings before interpreting this result as clean.`:`
|
|
943
|
+
No issues found. Codebase is clean.`)}function Mg(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${ZZ(t)} score-weighted)`}function ZZ(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function e9(e){if(e.pressure.length!==0){console.log(`
|
|
944
|
+
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 t9(e){let t=e.axes;if(console.log(`
|
|
945
|
+
Axes:`),console.log(` Zero-reference candidates: ${t.deletable.loc} LOC across ${t.deletable.symbols} symbols`),t.changeAmplification){let r=t.changeAmplification;console.log(` Change amplification: ${r.medianFilesPerCommit} files/commit median, ${r.p90FilesPerCommit} p90 (${r.commitsAnalyzed} commits)`)}if(t.hiddenCoupling&&t.hiddenCoupling.pairCount>0){console.log(` Hidden coupling: ${t.hiddenCoupling.pairCount} co-changing pair(s) without a dependency edge`);for(let r of t.hiddenCoupling.top.slice(0,3))console.log(` ${r.fileA} <-> ${r.fileB} (${r.together}x together, ${Math.round(r.confidence*100)}%)`)}if(t.churnWeightedComplexity&&t.churnWeightedComplexity.length>0){let r=t.churnWeightedComplexity[0];r.weighted>0&&console.log(` Churn x complexity: hottest is ${r.symbol} (${r.changes} changes, weighted ${r.weighted})`)}let n=t.evidenceQuality;if(console.log(` Evidence quality: ${n.graphFindings} graph-fact finding(s), ${n.heuristicFindings} heuristic finding(s), ${n.userSuppressed} user-suppressed`),e.validation&&e.validation.flaggedFiles>0){let r=e.validation,i=r.ratio===null?"n/a":`${r.ratio}x`;console.log(` Validation: flagged files fix-density ${r.flaggedFixDensity} vs baseline ${r.baselineFixDensity} (${i})`),console.log(` fix-commit signal: subject-keyword heuristic over ${r.validationBasis.commitsScanned} commits`)}}async function FPe(e){let t=An(i=>{let o=xr(i,{base:e.base});return o.note?{kind:"complete",result:lo(i,{base:e.base})}:o.changedFiles.length===0?{kind:"complete",result:lo(i,{base:e.base})}:{kind:"batched",plan:o}});if(t.kind==="complete")return t.result;let n=KD(t.plan.changedFiles,kZ),r=await _g(n,n9(n.length),i=>o9(i,e));return Nl(t.plan.changedFiles,r)}var n9=dP({envKey:"SCIP_QUERY_DIFF_IMPACT_CONCURRENCY",defaultMinimum:TZ,defaultMaximum:FZ});function dP(e){return(t,n=process.env,r=DZ)=>r9(t,n,r,e)}function r9(e,t,n,r){let i=t[r.envKey],o=i9(n,r),s=i?parseInt(i,10):o;return!Number.isFinite(s)||s<1?Math.min(o,e):Math.min(s,e)}function i9(e,t){let n=e(),r=Number.isFinite(n)?Math.max(t.defaultMinimum,n-1):0;return Math.min(t.defaultMaximum,Math.max(t.defaultMinimum,r))}function o9(e,t){let n=process.argv[1]??Ng(import.meta.url),r=[];return t.base&&r.push("--base",t.base),su({cliPath:n,command:PZ,args:r,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch"})}function _Pe(e){console.log(`Changed files: ${e.summary.totalChangedFiles}`),console.log(`Changed symbols: ${e.summary.totalChangedSymbols}`),console.log(`Affected consumer files: ${e.summary.totalAffectedFiles}`),e.summary.note&&console.log(`Note: ${e.summary.note}`);for(let n of e.evidenceTiers.filter(r=>r.state==="failed"))console.log(`WARNING: ${n.tier} evidence failed for ${n.attemptedSymbols} candidate symbol(s): ${n.reason}`);let t=e.attributionNotes.filter(n=>n.method==="unattributed");if(t.length>0){let n=[...new Set(t.map(r=>r.file))];for(let r of n){let i=t.filter(o=>o.file===r).length;console.log(`note: ${i} changed line-range(s) in ${r} belong to no indexed symbol`)}}console.log(""),e.changedSymbols.length>0&&(console.log("Changed symbols:"),cn.list(e.changedSymbols,n=>` ${n.file} ${n.shortName} (fan-in: ${n.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
|
|
946
|
+
Affected consumer files:`),cn.list(e.affectedConsumers,n=>` ${n.file} (${n.consumedSymbols} symbol(s))`))}var s9="scip-query-result";var a9=1,c9=1;function mP(e){let t=e.resultSchemaVersion??c9;if(!l9(t))throw new Error("CLI result schema version must be a positive safe integer.");let{producerVersion:n,...r}=e;return{kind:s9,schemaVersion:a9,producer:{name:"scip-query",version:n},resultSchemaVersion:t,...r}}function fP(e,t){return JSON.stringify(e,null,t?0:2)}function l9(e){return Number.isSafeInteger(e)&&Number(e)>0}var pP=Symbol("option-value-source"),gP=new Map,hP=new Map;function $Pe(e){gP=new Map(e)}function HPe(e){hP=new Map(e)}function ca(e){return(...t)=>{let{args:n,opts:r}=x9(t);An(i=>e({db:i,args:n,opts:r}))}}function lu(e,t){return ca(n=>{let r=lP(n.db,e,si(n.opts,"full"),{quiet:si(n.opts,"json")});t({...n,budget:r})})}function GPe(e){return ca(t=>ho(t,e,{kind:"list"}))}function qPe(e){return ca(t=>ho(t,e,{kind:"table",headers:e.headers,dashWidths:e.dashWidths}))}function UPe(e){return ca(t=>ho(t,e,{kind:"grouped",key:e.key}))}function u9(e){return ca(t=>Og(t,e))}function VPe(e){return u9({commandName:e.commandName,query:e.query,emptyMessage:e.emptyMessage,heuristicLabel:e.heuristicLabel,before:e.before,render:(t,n)=>cn.sectionedReport(e.sections(t,n)),toJson:e.toJson,coverage:e.coverage,agentResult:e.agentResult,after:e.after})}function d9(e,t){return lu(e,n=>Og(n,{...t,commandName:t.commandName??e}))}function zPe(e,t){return d9(e,{commandName:t.commandName??e,query:t.query,emptyMessage:t.emptyMessage,heuristicLabel:t.heuristicLabel,before:t.before,render:(n,r)=>cn.sectionedReport(t.sections(n,r)),toJson:t.toJson,coverage:t.coverage,agentResult:t.agentResult,after:t.after})}function WPe(e,t){return lu(e,n=>ho(n,{...t,commandName:e},{kind:"list"}))}function KPe(e,t){return lu(e,n=>ho(n,{...t,commandName:e},{kind:"table",headers:t.headers,dashWidths:t.dashWidths}))}function JPe(e,t){return lu(e,n=>ho(n,{...t,commandName:e},{kind:"grouped",key:t.key}))}function YPe(e,t){return String(e[t])}function XPe(e,t){let n=e[t];return typeof n=="string"?n:void 0}function QPe(e,t){let n=e[t];return typeof n=="string"?n:void 0}function yP(e,t){let n=e[t];return typeof n=="number"?n:void 0}function si(e,t){return!!e[t]}function ZPe(e,t){let n=e[t];return Array.isArray(n)&&n.every(r=>typeof r=="string")?n:[]}function eke(e,t,n){return yP(e,t)??n}function tke(e,t,n){let r=yP(e,t),i=r!==void 0&&m9(e,t)!=="default";if(si(e,"full")){if(i)throw new Error("--full cannot be combined with --limit. Use --full for all findings, or --limit N for a capped report.");return Number.MAX_SAFE_INTEGER}return r??n}function m9(e,t){return e[pP]?.(t)}function ho(e,t,n){Og(e,{commandName:t.commandName,query:t.query,emptyMessage:(r,i)=>r.length===0&&t.emptyMessage?t.emptyMessage(i):void 0,heuristicLabel:t.heuristicLabel,render:(r,i)=>{n.kind==="list"?cn.list(r,o=>t.format(o,i)):n.kind==="table"?cn.table(n.headers,r.map(o=>t.format(o,i)),n.dashWidths):cn.groupedByFile(r,o=>t.format(o,i),n.key?o=>n.key(o,i):void 0)},toJson:t.toJson,coverage:t.coverage,agentResult:t.agentResult,before:t.before,after:t.after})}function Og(e,t){let n=t.query(e);if(si(e.opts,"json")){if(!t.commandName)throw new Error("JSON output requires a command name so its result contract can be identified.");p9(t.commandName,e.args,e.opts,t.toJson?t.toJson(n,e):n,{analysisBudget:f9(e),coverage:t.coverage?.(n,e),agentResult:t.agentResult?.(n,e)});return}let r=t.emptyMessage?.(n,e);if(r){cn.empty(r);return}t.heuristicLabel&&cP(t.heuristicLabel),t.before?.(n,e),t.render(n,e),t.after?.(n,e)}function f9(e){return e.budget?.analysisBudget}function p9(e,t,n,r,i={}){let o=gP.get(e),s=hP.get(e),a=b9(r),c=i.coverage??h9(s,r,i.analysisBudget),l=c&&a&&!c.resolution?{...c,resolution:a}:c;if(l&&g9(l),si(n,"resultOnly")){let d=Object.hasOwn(i,"resultOnly")?i.resultOnly:r;Xi(JSON.stringify(d,null,si(n,"compact")?0:2));return}let u=mP({producerVersion:wt,command:e,...o?{evidence:o}:{},...i.analysisBudget?{analysisBudget:i.analysisBudget}:{},args:S9(t),options:n,result:r,...l?{coverage:l}:{},...i.agentResult!==void 0?{agentResult:i.agentResult}:{},...i.resultSchemaVersion===void 0?{}:{resultSchemaVersion:i.resultSchemaVersion}});Xi(fP(u,si(n,"compact")))}function g9(e){if(!Number.isSafeInteger(e.returned)||e.returned<0)throw new Error("Invocation coverage returned count must be a non-negative safe integer.");if(e.complete!==!0&&e.complete!==!1&&e.complete!==null)throw new Error("Invocation coverage complete must be true, false, or null.");if(e.complete===!0){if(!e.totalKnown)throw new Error("Complete invocation coverage must know its total.");if(!Number.isSafeInteger(e.total)||e.total!==e.returned)throw new Error("Complete invocation coverage total must equal returned.");if(e.omitted!==0)throw new Error("Complete invocation coverage cannot omit results.");if(e.omittedIdentities!==void 0)throw new Error("Complete invocation coverage cannot name omitted identities.");if(e.continuation!==void 0)throw new Error("Complete invocation coverage cannot provide a continuation.")}else if(e.totalKnown){if(e.complete!==!1)throw new Error("Known incomplete invocation coverage must set complete to false.");if(!Number.isSafeInteger(e.total)||e.total<e.returned)throw new Error("Known invocation coverage total must be a safe integer at least as large as returned.");let t=e.total-e.returned;if(e.omitted!==t)throw new Error("Known invocation coverage omitted count must equal total minus returned.");if(t===0)throw new Error("Known incomplete invocation coverage must omit at least one result.");if(e.omittedIdentities&&e.omittedIdentities.length!==t)throw new Error("Omitted identity count must equal the disclosed omitted count.")}else{if(e.total!==void 0||e.omitted!==void 0)throw new Error("Unknown invocation coverage cannot claim a total or omitted count.");if(e.omittedIdentities!==void 0)throw new Error("Unknown invocation coverage cannot claim omitted identities.")}if(e.continuation&&(e.continuation.cursor.length===0||e.continuation.indexGeneration.length===0))throw new Error("Invocation coverage continuation requires a cursor and index generation.");if(e.resolution){if(!Number.isSafeInteger(e.resolution.totalCandidates)||e.resolution.totalCandidates<0)throw new Error("Invocation resolution candidate count must be a non-negative safe integer.");if(e.resolution.state==="exact"&&e.resolution.totalCandidates!==1)throw new Error("Exact invocation resolution must name exactly one candidate.");if(e.resolution.state==="missing"&&e.resolution.totalCandidates!==0)throw new Error("Missing invocation resolution cannot name candidates.");if(e.resolution.state==="ambiguous"&&e.resolution.totalCandidates<2)throw new Error("Ambiguous invocation resolution must name at least two candidates.")}}function h9(e,t,n){if(!e)return;let r=y9(e,t);return e.coverage==="complete"?{complete:!0,totalKnown:!0,returned:r,total:r,omitted:0}:e.coverage==="sampled"?{complete:!1,totalKnown:!1,returned:r}:e.coverage==="bounded"&&n?{complete:!1,totalKnown:!1,returned:r}:{complete:null,totalKnown:!1,returned:r}}function y9(e,t){let n=e.resultUnits??{kind:"report"};if(n.kind==="rows")return Array.isArray(t)?t.length:0;if(n.kind==="field"){if(!t||typeof t!="object")return 0;let r=t[n.field];return Array.isArray(r)?r.length:r==null?0:1}return t==null?0:1}function b9(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(t.matched===!1)return{state:"missing",totalCandidates:0};if(t.matched!==!0||!Number.isSafeInteger(t.totalMatches))return;let n=t.totalMatches;return n<=0?{state:"missing",totalCandidates:0}:n===1?{state:"exact",totalCandidates:n}:{state:"ambiguous",totalCandidates:n}}function S9(e){return e.filter(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean")}function x9(e){if(e.length===0)return{args:[],opts:{}};let t=e[e.length-1];return{args:e.slice(0,-1),opts:R9(t)}}function R9(e){if(!e||typeof e!="object")return{};let t=e;if(typeof t.opts=="function"){let n=t.opts();return!n||typeof n!="object"?{}:(typeof t.getOptionValueSource=="function"&&Object.defineProperty(n,pP,{value:r=>t.getOptionValueSource(r),enumerable:!1}),n)}return e}function rke(e){return Buffer.from(JSON.stringify(e),"utf8").toString("base64url")}export{hs as a,fu as b,qg as c,C9 as d,V as e,la as f,yo as g,gu as h,vr as i,Jt as j,T9 as k,zg as l,xP as m,F9 as n,We as o,G9 as p,L as q,fi as r,ht as s,Ie as t,He as u,Me as v,Th as w,Qt as x,Se as y,J as z,O as A,Dk as B,Pk as C,Ou as D,xi as E,en as F,et as G,W as H,gh as I,hh as J,yh as K,YP as L,D as M,J9 as N,zn as O,jk as P,de as Q,$u as R,Co as S,H as T,Tt as U,c8 as V,l8 as W,ne as X,JF as Y,Y7 as Z,xy as _,ct as $,cne as aa,le as ba,E as ca,T as da,ae as ea,ie as fa,Oe as ga,G as ha,Or as ia,Sb as ja,OM as ka,BM as la,Td as ma,Fs as na,ln as oa,Hv as pa,Xfe as qa,Vre as ra,jb as sa,zre as ta,$b as ua,qb as va,IN as wa,Md as xa,rie as ya,DN as za,PN as Aa,iie as Ba,oie as Ca,zb as Da,dc as Ea,Rt as Fa,Ct as Ga,Ke as Ha,tt as Ia,Ae as Ja,jr as Ka,Ti as La,dt as Ma,ce as Na,Be as Oa,nr as Pa,vt as Qa,ir as Ra,mc as Sa,Li as Ta,Hr as Ua,fc as Va,bse as Wa,Use as Xa,Vse as Ya,HO as Za,ax as _a,cm as $a,rt as ab,t8 as bb,ui as cb,uk as db,Rh as eb,n8 as fb,fa as gb,Yt as hb,ji as ib,$i as jb,rn as kb,Cx as lb,cB as mb,Dc as nb,Nx as ob,kc as pb,Gi as qb,Hi as rb,MB as sb,Tm as tb,or as ub,tce as vb,Nc as wb,gle as xb,Zr as yb,Hq as zb,zq as Ab,zle as Bb,Kf as Cb,Jf as Db,Yf as Eb,Xf as Fb,Qf as Gb,ei as Hb,YU as Ib,ZU as Jb,eV as Kb,tV as Lb,nue as Mb,pV as Nb,yV as Ob,bV as Pb,SV as Qb,RV as Rb,CV as Sb,vV as Tb,bI as Ub,ti as Vb,UV as Wb,Os as Xb,WV as Yb,KV as Zb,tz as _b,oz as $b,ip as ac,El as bc,lp as cc,Bs as dc,Jz as ec,js as fc,$s as gc,dp as hc,Hs as ic,Gs as jc,mp as kc,HW as lc,qs as mc,WK as nc,xp as oc,Rp as pc,k2 as qc,Vs as rc,xr as sc,Hw as tc,kY as uc,Js as vc,JY as wc,Qs as xc,Zs as yc,ta as zc,na as Ac,UX as Bc,Zp as Cc,tg as Dc,rg as Ec,BR as Fc,Xc as Gc,og as Hc,NCe as Ic,OE as Jc,BE as Kc,Kl as Lc,oQ as Mc,sQ as Nc,aQ as Oc,cQ as Pc,VCe as Qc,uQ as Rc,dQ as Sc,mQ as Tc,JE as Uc,fQ as Vc,XQ as Wc,QQ as Xc,s4 as Yc,x4 as Zc,D4 as _c,U4 as $c,dg as ad,fg as bd,eu as cd,x6 as dd,pg as ed,Ht as fd,pwe as gd,SD as hd,Swe as id,xwe as jd,hg as kd,Rwe as ld,ru as md,bg as nd,K6 as od,rEe as pd,iEe as qd,_3 as rd,due as sd,A3 as td,U3 as ud,X3 as vd,wt as wd,DR as xd,Vc as yd,Ym as zd,PR as Ad,zm as Bd,Wm as Cd,Iue as Dd,wue as Ed,Eue as Fd,zc as Gd,Wc as Hd,MR as Id,tl as Jd,ZR as Kd,ude as Ld,dde as Md,mde as Nd,fde as Od,pde as Pd,bs as Qd,mC as Rd,K1 as Sd,Tde as Td,Fde as Ud,xs as Vd,SC as Wd,Jde as Xd,Yde as Yd,Xde as Zd,Qde as _d,sme as $d,ame as ae,cme as be,lme as ce,Rme as de,Pme as ee,kme as fe,ul as ge,nv as he,rv as ie,Qr as je,iv as ke,kf as le,tfe as me,Tf as ne,Lf as oe,dv as pe,mfe as qe,ffe as re,mv as se,pfe as te,gfe as ue,hfe as ve,An as we,yfe as xe,fv as ye,bfe as ze,Pg as Ae,ri as Be,zD as Ce,pv as De,Ot as Ee,Xi as Fe,xfe as Ge,ii as He,tPe as Ie,nPe as Je,yv as Ke,gG as Le,vfe as Me,Ife as Ne,cn as Oe,oP as Pe,PZ as Qe,cP as Re,lP as Se,PPe as Te,kPe as Ue,TPe as Ve,FPe as We,_Pe as Xe,$Pe as Ye,HPe as Ze,ca as _e,lu as $e,GPe as af,qPe as bf,UPe as cf,u9 as df,VPe as ef,d9 as ff,zPe as gf,WPe as hf,KPe as if,JPe as jf,YPe as kf,XPe as lf,QPe as mf,yP as nf,si as of,ZPe as pf,eke as qf,tke as rf,m9 as sf,p9 as tf,x9 as uf,R9 as vf,rke as wf};
|
|
947
|
+
//# sourceMappingURL=chunk-JFGGXWQF.js.map
|