scip-query 0.23.0 → 0.26.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 +491 -2
- package/README.md +111 -122
- package/dist/augment-vue-worker.js +1 -1
- package/dist/by-kind-PRVFAGTQ.js +2 -0
- package/dist/call-graph-DVPAQV2F.js +2 -0
- package/dist/call-graph-evidence-CUtj8V2I.d.ts +19 -0
- package/dist/chunk-2FSBGL5P.js +2 -0
- package/dist/chunk-2HLAFUCY.js +2 -0
- package/dist/chunk-2IWUT6CJ.js +3 -0
- package/dist/chunk-2KNN7GTQ.js +2 -0
- package/dist/chunk-2LHXRE2B.js +8 -0
- package/dist/{chunk-EG2CPZMJ.js → chunk-2YXE77TJ.js} +2 -2
- package/dist/chunk-36SGVCGX.js +2 -0
- package/dist/chunk-3ABBFPTP.js +2 -0
- package/dist/chunk-3IVFU4FD.js +3 -0
- package/dist/chunk-3JIQS44J.js +7 -0
- package/dist/chunk-3ZRB6DNK.js +7 -0
- package/dist/{chunk-6YTSKJJ3.js → chunk-42EOW5VI.js} +1 -1
- package/dist/{chunk-6I6L7Z62.js → chunk-4BHGBMNO.js} +2 -2
- package/dist/chunk-4BP3UBDG.js +2 -0
- package/dist/chunk-4D6RO7G4.js +2 -0
- package/dist/chunk-4FEWQ6RH.js +2 -0
- package/dist/chunk-4IGEOBG7.js +2 -0
- package/dist/chunk-4QZXBUKC.js +2 -0
- package/dist/chunk-4WBDEVX2.js +4 -0
- package/dist/chunk-4WCUBZU3.js +8 -0
- package/dist/chunk-4WTUBQ36.js +40 -0
- package/dist/chunk-4XQ4O6IM.js +3 -0
- package/dist/chunk-55UQAMZO.js +4 -0
- package/dist/chunk-5D2LVK7O.js +125 -0
- package/dist/chunk-5IYJ56TT.js +2 -0
- package/dist/chunk-5PLMJC7Q.js +2 -0
- package/dist/chunk-5TNQJUR2.js +5 -0
- package/dist/chunk-62BDNPMI.js +2 -0
- package/dist/chunk-64DZ5TXR.js +7 -0
- package/dist/chunk-65245JCM.js +2 -0
- package/dist/chunk-6FFVZZL4.js +2 -0
- package/dist/chunk-6KO5JHAR.js +2 -0
- package/dist/chunk-6LRXOOSX.js +2 -0
- package/dist/chunk-6LSEIIF7.js +2 -0
- package/dist/chunk-6YMNWD3H.js +6 -0
- package/dist/chunk-72AD6ZRR.js +5 -0
- package/dist/chunk-73AAKPUC.js +4 -0
- package/dist/chunk-76CZ77DF.js +2 -0
- package/dist/chunk-7VPEEAAG.js +2 -0
- package/dist/chunk-7WTPQ4NX.js +14 -0
- package/dist/chunk-7Y5T6XDP.js +2 -0
- package/dist/chunk-A2IIGFMJ.js +5 -0
- package/dist/chunk-AB5KCTEV.js +2 -0
- package/dist/chunk-AC566WBP.js +6 -0
- package/dist/chunk-AGWFSTXC.js +3 -0
- package/dist/chunk-AOSIYPTA.js +2 -0
- package/dist/chunk-AUVEWPIF.js +2 -0
- package/dist/chunk-B56T42J3.js +25 -0
- package/dist/chunk-BIQEF5NE.js +2 -0
- package/dist/chunk-BL6XJKTA.js +3 -0
- package/dist/chunk-BMKOQJRI.js +2 -0
- package/dist/chunk-BOZ4EXBB.js +3 -0
- package/dist/chunk-BUTWYEPH.js +2 -0
- package/dist/chunk-BZB4QPIP.js +2 -0
- package/dist/{chunk-ILTDAWEF.js → chunk-CE357GEE.js} +4 -4
- package/dist/chunk-CFN45HFP.js +2 -0
- package/dist/chunk-CFYMZFXT.js +368 -0
- package/dist/chunk-CN5EH7O3.js +2 -0
- package/dist/chunk-D254DNNQ.js +4 -0
- package/dist/chunk-D3FDISIC.js +2 -0
- package/dist/chunk-D3NX5XIE.js +3 -0
- package/dist/chunk-DA7RPPDF.js +3 -0
- package/dist/chunk-DDMC3FON.js +3 -0
- package/dist/chunk-DIO3FUSG.js +2 -0
- package/dist/chunk-DJ2NNSUK.js +3 -0
- package/dist/chunk-DKYQIM3C.js +18 -0
- package/dist/{chunk-JTQVMR42.js → chunk-DOOEL2IV.js} +2 -2
- package/dist/chunk-DVFP6PZI.js +2 -0
- package/dist/chunk-E3FDPXZK.js +2 -0
- package/dist/chunk-E7YNJLCB.js +2 -0
- package/dist/chunk-EFGW5JPH.js +2 -0
- package/dist/chunk-EJVTR244.js +13 -0
- package/dist/chunk-EOV7RTRZ.js +2 -0
- package/dist/chunk-ETOIKRHO.js +2 -0
- package/dist/chunk-EYK3ZAO2.js +3 -0
- package/dist/chunk-F2V2LPET.js +52 -0
- package/dist/chunk-F4LUHJTF.js +2 -0
- package/dist/chunk-F4PUT6IT.js +2 -0
- package/dist/chunk-F56GCXXS.js +5 -0
- package/dist/chunk-FC2EVQRM.js +2 -0
- package/dist/chunk-FL7NBMHP.js +3 -0
- package/dist/chunk-FMRN2TRL.js +3 -0
- package/dist/chunk-FVULPZDF.js +20 -0
- package/dist/chunk-GCKCF5FL.js +43 -0
- package/dist/chunk-GH2PYF46.js +2 -0
- package/dist/chunk-GHJAGXIP.js +2 -0
- package/dist/{chunk-WIWY3CRX.js → chunk-GMVSHUKZ.js} +2 -2
- package/dist/chunk-GS6KDO4R.js +2 -0
- package/dist/chunk-GUUBXNN7.js +2 -0
- package/dist/chunk-GVWX5T43.js +80 -0
- package/dist/chunk-GZKFETP5.js +2 -0
- package/dist/chunk-H4EQHO6J.js +9 -0
- package/dist/chunk-H73WY2RM.js +2 -0
- package/dist/chunk-H75GSPRV.js +60 -0
- package/dist/chunk-HDR3AHSV.js +61 -0
- package/dist/chunk-HQBSL74Y.js +2 -0
- package/dist/chunk-HRRFKWPZ.js +2 -0
- package/dist/chunk-HXENDJC6.js +2 -0
- package/dist/chunk-IIBAZNSW.js +21 -0
- package/dist/chunk-INLMWEUU.js +12 -0
- package/dist/chunk-IWQPAF4F.js +2 -0
- package/dist/chunk-IZJ6YUKP.js +35 -0
- package/dist/chunk-J2TMAIN5.js +60 -0
- package/dist/chunk-J5FJMODQ.js +142 -0
- package/dist/chunk-J7HZPIO3.js +2 -0
- package/dist/chunk-JEVRKFRL.js +2 -0
- package/dist/chunk-JFXSGAEB.js +30 -0
- package/dist/chunk-JVRTHGFS.js +3 -0
- package/dist/chunk-JYWEX7RR.js +360 -0
- package/dist/chunk-K3YL22N6.js +2 -0
- package/dist/chunk-K4CN7GXK.js +12 -0
- package/dist/chunk-K5TBVXU4.js +30 -0
- package/dist/chunk-KDDIE2DP.js +9 -0
- package/dist/chunk-KHWRRPV4.js +2 -0
- package/dist/chunk-KI6NBKDY.js +14 -0
- package/dist/chunk-KU3QRSTH.js +2 -0
- package/dist/chunk-KZBJWZJB.js +2 -0
- package/dist/chunk-L7GFM3NP.js +3 -0
- package/dist/chunk-LMO6PK3V.js +35 -0
- package/dist/chunk-LN4YXJJU.js +2 -0
- package/dist/chunk-LOVIZBJ4.js +43 -0
- package/dist/chunk-LPCRK4A2.js +11 -0
- package/dist/chunk-MMHZKBFA.js +2 -0
- package/dist/{chunk-M2O5NY6W.js → chunk-MOQQBQRD.js} +2 -2
- package/dist/chunk-N2WN6I3L.js +2 -0
- package/dist/chunk-N3ORQT7L.js +2 -0
- package/dist/chunk-NAZ3RAIW.js +2 -0
- package/dist/chunk-NDUNO5JQ.js +2 -0
- package/dist/chunk-NEIWRNAZ.js +4 -0
- package/dist/chunk-NJJMVD65.js +2 -0
- package/dist/chunk-NLOQOBXI.js +20 -0
- package/dist/chunk-NOLZOVCU.js +2 -0
- package/dist/chunk-NOWINRRN.js +2 -0
- package/dist/chunk-NZAXKGRL.js +16 -0
- package/dist/chunk-O2C4UILI.js +2 -0
- package/dist/chunk-O3RHA6ZT.js +3 -0
- package/dist/chunk-O4UZSPPI.js +3 -0
- package/dist/chunk-OGFV2BUX.js +2 -0
- package/dist/chunk-OZCJXZK6.js +499 -0
- package/dist/chunk-P6ODM7BY.js +2 -0
- package/dist/{chunk-XBGWL66K.js → chunk-PAVGPRHJ.js} +2 -2
- package/dist/chunk-PH52RA7D.js +2 -0
- package/dist/chunk-PKN354TH.js +3 -0
- package/dist/chunk-PWOASWEG.js +11 -0
- package/dist/chunk-QIWXRW72.js +2 -0
- package/dist/chunk-QJRMOK5N.js +2 -0
- package/dist/{chunk-YXPUP5G2.js → chunk-QOIXNWQR.js} +2 -2
- package/dist/chunk-QXEUDXBT.js +3 -0
- package/dist/chunk-QYUVVBMR.js +6 -0
- package/dist/chunk-QZ7KQZRN.js +2 -0
- package/dist/chunk-R6LQBUDH.js +2 -0
- package/dist/chunk-RBS42E55.js +20 -0
- package/dist/chunk-RSJKPCFX.js +26 -0
- package/dist/chunk-S6CZA3MV.js +2 -0
- package/dist/chunk-STMVAHJP.js +2 -0
- package/dist/chunk-SYVPTTVW.js +2 -0
- package/dist/chunk-T3I6NHBH.js +2 -0
- package/dist/chunk-T6DK3ZP7.js +2 -0
- package/dist/chunk-TKD34PHN.js +4 -0
- package/dist/chunk-TNNQFH7W.js +2 -0
- package/dist/chunk-TNV7SSUF.js +2 -0
- package/dist/chunk-TO7ZR3EH.js +8 -0
- package/dist/chunk-TOU3CHK4.js +2 -0
- package/dist/chunk-TRBI4UKT.js +2 -0
- package/dist/chunk-TZCVNCAN.js +4 -0
- package/dist/chunk-U4LZA5LL.js +3 -0
- package/dist/chunk-U5RIG3JP.js +3 -0
- package/dist/chunk-UP5KXN2I.js +2 -0
- package/dist/chunk-UQFR3NDH.js +5 -0
- package/dist/chunk-UXYXF7GV.js +2 -0
- package/dist/chunk-VB3GOKOS.js +2 -0
- package/dist/chunk-VF5JZICY.js +2 -0
- package/dist/chunk-VTY3VK6E.js +2 -0
- package/dist/chunk-VX2O4RIS.js +2 -0
- package/dist/chunk-WKPV2TDZ.js +2 -0
- package/dist/chunk-WOFQ5DTB.js +2 -0
- package/dist/chunk-WS4C6TCK.js +2 -0
- package/dist/chunk-WXU3DGPU.js +2 -0
- package/dist/chunk-X6RMKHJQ.js +81 -0
- package/dist/{chunk-4ILJCCXV.js → chunk-XHMN6ZX7.js} +2 -2
- package/dist/chunk-XHTVFLWW.js +2 -0
- package/dist/chunk-XKIDJCIK.js +2 -0
- package/dist/chunk-XTYTYZPT.js +2 -0
- package/dist/chunk-Y2JHHTTA.js +2 -0
- package/dist/chunk-YGVRMGYN.js +4 -0
- package/dist/chunk-YNQCGEQE.js +2 -0
- package/dist/chunk-YOQVEXVE.js +14 -0
- package/dist/chunk-YRT2WLYY.js +2 -0
- package/dist/chunk-YTAP5Y2G.js +2 -0
- package/dist/chunk-YTYWI7VB.js +2 -0
- package/dist/chunk-YULZRALL.js +2 -0
- package/dist/chunk-Z33WQG4Q.js +2 -0
- package/dist/chunk-ZGTYGDMF.js +16 -0
- package/dist/chunk-ZHMRSZFD.js +43 -0
- package/dist/chunk-ZHSP366W.js +10 -0
- package/dist/chunk-ZIBYCYKK.js +7 -0
- package/dist/{chunk-GAS2LJMP.js → chunk-ZLADLUE6.js} +3 -3
- package/dist/chunk-ZO4YXUT6.js +4 -0
- package/dist/{chunk-HYO3NP5Q.js → chunk-ZR4HBC2H.js} +2 -2
- package/dist/cli-main.js +6 -6
- package/dist/cli.js +1 -1
- package/dist/{code-B17qEMbt.d.ts → code-BNyrCF3_.d.ts} +3 -2
- package/dist/code-IL5WH3NZ.js +2 -0
- package/dist/code-result-json-ANTBEDFP.js +4 -0
- package/dist/command-descriptors-HEEMDHTU.js +222 -0
- package/dist/deps-EOWFC6FD.js +2 -0
- package/dist/direct-navigation-Y5B6OSIQ.js +3 -0
- package/dist/{exploration-topology-BG4v30HZ.d.ts → exploration-topology-CSgEyAz-.d.ts} +3 -1
- package/dist/files-K4AI3JUM.js +2 -0
- package/dist/frontend-profile-roles-D7eCum8P.d.ts +10 -0
- package/dist/{health-CPp2Jf1Z.d.ts → health-BtfmNrfa.d.ts} +58 -74
- package/dist/hierarchy-6W5NDIFI.js +2 -0
- package/dist/imports-WH365QY4.js +2 -0
- package/dist/index.d.ts +13 -1
- package/dist/index.js +1 -1
- package/dist/members-K3PHMF5S.js +2 -0
- package/dist/methods-E7KVMBX4.js +2 -0
- package/dist/output-continuation-command-BJSY67SN.js +3 -0
- package/dist/output-pagination-UZJ5ACIX.js +24 -0
- package/dist/postinstall.js +1 -1
- package/dist/project-reindex-EP24WT4X.js +3 -0
- package/dist/queries/affected.js +1 -1
- package/dist/queries/architecture.d.ts +15 -4
- package/dist/queries/architecture.js +1 -1
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.d.ts +3 -1
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.d.ts +1 -0
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.d.ts +3 -3
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/co-change.d.ts +20 -2
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.d.ts +1 -1
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity.d.ts +6 -3
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/context.d.ts +1 -7
- package/dist/queries/context.js +1 -1
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dead.d.ts +2 -0
- package/dist/queries/dead.js +1 -1
- package/dist/queries/decorative-checkers.js +1 -1
- package/dist/queries/dependence-slice.d.ts +46 -22
- package/dist/queries/dependence-slice.js +1 -1
- package/dist/queries/dependency-depth.d.ts +1 -7
- package/dist/queries/dependency-depth.js +1 -1
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-impact.d.ts +3 -1
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.d.ts +1 -1
- package/dist/queries/drift.js +1 -1
- package/dist/queries/duplicate-bodies.d.ts +29 -2
- package/dist/queries/duplicate-bodies.js +1 -1
- package/dist/queries/entry-map.d.ts +2 -4
- package/dist/queries/entry-map.js +1 -1
- package/dist/queries/evidence.d.ts +121 -61
- package/dist/queries/evidence.js +1 -1
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.js +1 -1
- package/dist/queries/health.d.ts +1 -1
- 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 +1 -1
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.d.ts +1 -0
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.d.ts +3 -3
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +17 -65
- package/dist/queries/index.js +1 -1
- package/dist/queries/locality-candidates.d.ts +4 -4
- 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.js +1 -1
- package/dist/queries/not-implemented.d.ts +2 -6
- package/dist/queries/not-implemented.js +1 -1
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.d.ts +9 -1
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/react-component-duplicates.d.ts +19 -3
- package/dist/queries/react-component-duplicates.js +1 -1
- package/dist/queries/react-hook-candidates.d.ts +22 -3
- package/dist/queries/react-hook-candidates.js +1 -1
- package/dist/queries/react-large-component-pressure.d.ts +17 -3
- package/dist/queries/react-large-component-pressure.js +1 -1
- package/dist/queries/recent-duplicates.js +1 -1
- package/dist/queries/redundant-reexports.d.ts +4 -14
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/refs.d.ts +4 -1
- package/dist/queries/refs.js +1 -1
- package/dist/queries/review.d.ts +188 -0
- package/dist/queries/review.js +2 -0
- package/dist/queries/similar-files.d.ts +7 -10
- package/dist/queries/similar-files.js +1 -1
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.d.ts +19 -1
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice-cohesion.d.ts +205 -0
- package/dist/queries/slice-cohesion.js +2 -0
- package/dist/queries/source-inspection.d.ts +6 -202
- package/dist/queries/source-inspection.js +1 -1
- package/dist/queries/source-search.d.ts +2 -3
- package/dist/queries/source-search.js +1 -1
- package/dist/queries/stats.d.ts +1 -0
- package/dist/queries/stats.js +1 -1
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system.d.ts +4 -2
- package/dist/queries/system.js +1 -1
- package/dist/queries/test-quality.d.ts +1 -1
- package/dist/queries/test-quality.js +1 -1
- package/dist/queries/twin-drift.d.ts +23 -7
- package/dist/queries/twin-drift.js +1 -1
- package/dist/queries/unused-imports.js +1 -1
- package/dist/queries/unused-params.d.ts +3 -15
- package/dist/queries/unused-params.js +1 -1
- package/dist/queries/vue-component-duplicates.js +1 -1
- package/dist/queries/vue-composable-candidates.js +1 -1
- package/dist/queries/vue-large-view-pressure.js +1 -1
- package/dist/query-service-fastpath.js +5 -5
- package/dist/query-service-server.js +4 -4
- package/dist/refs-CCBJG7WK.js +2 -0
- package/dist/refs-pagination-DRNLVU4S.js +2 -0
- package/dist/reindex-worker.js +79 -29
- package/dist/reindex.js +45 -45
- package/dist/repository-cache-worker.js +2 -0
- package/dist/runtime.d.ts +8 -8
- package/dist/runtime.js +3 -4
- package/dist/rust-semantic-session-server.js +1 -1
- package/dist/rust-semantic-session-worker.js +1 -1
- package/dist/rust-semantic-worker.js +1 -1
- package/dist/service-queries-2WAJI7R6.js +6 -0
- package/dist/source-inspection-91U9zdO3.d.ts +341 -0
- package/dist/{source-search-types-Dwz8KeuW.d.ts → source-search-types-DWGYNg8M.d.ts} +15 -2
- package/dist/stats-G7DIV6VU.js +2 -0
- package/dist/surface-IO55UALI.js +2 -0
- package/dist/system-ZBMSHJXU.js +2 -0
- package/dist/{queries/trace.d.ts → trace-BMjw3prn.d.ts} +1 -18
- package/dist/typescript-indexer.js +2 -0
- package/dist/typescript-mailbox-worker.js +1 -1
- package/dist/watch-server.js +3 -3
- package/docs/AGENT_GUIDE.md +19 -128
- package/docs/CLI_JSON_OUTPUT.md +21 -17
- package/docs/COMMAND_REFERENCE.md +34 -49
- package/docs/CURRENT_COMMANDS.md +123 -0
- package/docs/DETECTOR_EVIDENCE_CONTRACTS.md +0 -40
- package/docs/DETECTOR_GUIDE.md +55 -12
- package/docs/PRODUCT_VISION.md +135 -0
- package/docs/PROPERTY_TESTING.md +73 -0
- package/docs/REVIEW.md +76 -0
- package/docs/SKILLS.md +51 -0
- package/docs/WINDOWS_SIDECAR_RELEASE.md +12 -3
- package/docs/accuracy-audit-checklist.md +70 -13
- package/docs/analyzer-inventory.md +2 -2
- package/docs/locality-analyzer-design.md +9 -9
- package/package.json +18 -80
- package/scripts/evidence-product-contract.mjs +7 -3
- package/scripts/record-review-coverage.mjs +118 -0
- package/scripts/scip-windows-provenance.mjs +29 -19
- package/skills/scip-architecture-review/SKILL.md +57 -0
- package/skills/scip-architecture-review/agents/openai.yaml +4 -0
- package/skills/scip-architecture-review/references/design-checks.md +17 -0
- package/skills/scip-explore/SKILL.md +15 -59
- package/skills/scip-explore/agents/openai.yaml +3 -3
- package/skills/scip-explore/references/external-evidence.md +2 -2
- package/skills/scip-explore/references/information-model.md +26 -29
- package/skills/scip-explore/scripts/capture-evidence.mjs +68 -34
- package/skills/scip-integrity-audit/SKILL.md +53 -181
- package/skills/scip-integrity-audit/agents/openai.yaml +3 -3
- package/skills/scip-integrity-audit/references/integrity-probes.md +27 -0
- package/skills/scip-plan/SKILL.md +39 -65
- package/skills/scip-plan/agents/openai.yaml +2 -2
- package/skills/scip-query/SKILL.md +28 -81
- package/skills/scip-query/agents/openai.yaml +2 -2
- package/skills/scip-query/references/command-guide.md +169 -0
- package/skills/scip-setup/SKILL.md +4 -2
- package/skills/scip-setup/agents/openai.yaml +3 -3
- package/dist/by-kind-XI2CSWEY.js +0 -2
- package/dist/call-graph-UONR6JR5.js +0 -2
- package/dist/call-graph-evidence-lZa2dwQA.d.ts +0 -11
- package/dist/chunk-26CT72HM.js +0 -2
- package/dist/chunk-2E7CX53V.js +0 -2
- package/dist/chunk-2GRUZAQF.js +0 -43
- package/dist/chunk-2LDBDR6J.js +0 -29
- package/dist/chunk-2OOY75BW.js +0 -2
- package/dist/chunk-2R3V3PSD.js +0 -4
- package/dist/chunk-2WC2OEDO.js +0 -4
- package/dist/chunk-35NLDRZC.js +0 -2
- package/dist/chunk-3AF4TUFK.js +0 -3
- package/dist/chunk-3D3QG236.js +0 -2
- package/dist/chunk-3FHOF22C.js +0 -21
- package/dist/chunk-3JKSW6LJ.js +0 -2
- package/dist/chunk-3L2ZBPEX.js +0 -133
- package/dist/chunk-3PJABJSU.js +0 -2
- package/dist/chunk-3SVF22I5.js +0 -2
- package/dist/chunk-3WR4E3A3.js +0 -3
- package/dist/chunk-4FTZ4P5G.js +0 -2
- package/dist/chunk-4UX2F3JX.js +0 -2
- package/dist/chunk-4WNW27SX.js +0 -2
- package/dist/chunk-5ENOG4VP.js +0 -61
- package/dist/chunk-64BFSI5I.js +0 -2
- package/dist/chunk-66DVSJQG.js +0 -455
- package/dist/chunk-6HFCYNYE.js +0 -9
- package/dist/chunk-6PQNKL3G.js +0 -3
- package/dist/chunk-6V5CNXL6.js +0 -2
- package/dist/chunk-6VVV4WRR.js +0 -4
- package/dist/chunk-7BWFZPPZ.js +0 -2
- package/dist/chunk-7CYG22FH.js +0 -2
- package/dist/chunk-7F45LJKI.js +0 -2
- package/dist/chunk-7IWV2EG3.js +0 -3
- package/dist/chunk-7KCZELVM.js +0 -2
- package/dist/chunk-AFHTBORT.js +0 -2
- package/dist/chunk-AVRYW5OZ.js +0 -2
- package/dist/chunk-B3X6KU75.js +0 -2
- package/dist/chunk-B5D7QPBE.js +0 -4
- package/dist/chunk-BBCIS4DX.js +0 -16
- package/dist/chunk-BDUVI7TO.js +0 -3
- package/dist/chunk-BE7ZZTMC.js +0 -2
- package/dist/chunk-BHVUJOCQ.js +0 -3
- package/dist/chunk-BJT7LSPK.js +0 -3
- package/dist/chunk-BKVWUP7Y.js +0 -2
- package/dist/chunk-BQGB4HBD.js +0 -2
- package/dist/chunk-BRV7PIFF.js +0 -2
- package/dist/chunk-CEEZJXEF.js +0 -2
- package/dist/chunk-CIYLO6SI.js +0 -7
- package/dist/chunk-CJZXN4NU.js +0 -2
- package/dist/chunk-CNO7TOKL.js +0 -2
- package/dist/chunk-COF23M5F.js +0 -2
- package/dist/chunk-CWFP7GM5.js +0 -2
- package/dist/chunk-D2DHWI3D.js +0 -2
- package/dist/chunk-D4N5SQ2M.js +0 -4
- package/dist/chunk-DBRSYFXR.js +0 -2
- package/dist/chunk-DHUIOLDT.js +0 -2
- package/dist/chunk-DIRJWYBM.js +0 -6
- package/dist/chunk-DIUFNHRJ.js +0 -35
- package/dist/chunk-DRENNWRG.js +0 -2
- package/dist/chunk-DTZCKZEU.js +0 -4
- package/dist/chunk-DULC3QFP.js +0 -5
- package/dist/chunk-DYGHBZ2N.js +0 -16
- package/dist/chunk-E5R6AQ73.js +0 -40
- package/dist/chunk-E73UNJTF.js +0 -38
- package/dist/chunk-EKV5HX33.js +0 -2
- package/dist/chunk-EQHFIL6T.js +0 -3
- package/dist/chunk-ESIQ66Z7.js +0 -2
- package/dist/chunk-EVFUMY4R.js +0 -3
- package/dist/chunk-F7DY272B.js +0 -2
- package/dist/chunk-FBN2FGXG.js +0 -2
- package/dist/chunk-FDLOBR6P.js +0 -4
- package/dist/chunk-FESCRNVV.js +0 -5
- package/dist/chunk-FFRKR4EQ.js +0 -2
- package/dist/chunk-FGA2U4OR.js +0 -8
- package/dist/chunk-FIQRSHVM.js +0 -2
- package/dist/chunk-FPYLNQPT.js +0 -2
- package/dist/chunk-FRUSVINH.js +0 -2
- package/dist/chunk-GSP44ENC.js +0 -2
- package/dist/chunk-GUFSG5TX.js +0 -2
- package/dist/chunk-GYIZ4NXB.js +0 -2
- package/dist/chunk-GZIUDL6G.js +0 -2
- package/dist/chunk-H5EXS3HM.js +0 -2
- package/dist/chunk-HCXEQRFF.js +0 -18
- package/dist/chunk-HEHOQQKH.js +0 -2
- package/dist/chunk-HKGFPJ4T.js +0 -4
- package/dist/chunk-HLZTEXRA.js +0 -2
- package/dist/chunk-HOENASQM.js +0 -3
- package/dist/chunk-HVF5VBG6.js +0 -2
- package/dist/chunk-I55I7XXP.js +0 -2
- package/dist/chunk-IDFEUFKS.js +0 -2
- package/dist/chunk-IHGQTTVW.js +0 -2
- package/dist/chunk-IICPE7B2.js +0 -20
- package/dist/chunk-IL676XCC.js +0 -18
- package/dist/chunk-IW5XQG5G.js +0 -2
- package/dist/chunk-IZDPJ2QI.js +0 -2
- package/dist/chunk-J66VOFW6.js +0 -5
- package/dist/chunk-JFMEXGFE.js +0 -2
- package/dist/chunk-JGKUET5J.js +0 -3
- package/dist/chunk-JS4PGXMV.js +0 -3
- package/dist/chunk-JWTGMPIT.js +0 -80
- package/dist/chunk-JYR66JN5.js +0 -5
- package/dist/chunk-KFOYCQAJ.js +0 -9
- package/dist/chunk-KLFEXGQA.js +0 -2
- package/dist/chunk-KMVGRIO2.js +0 -2
- package/dist/chunk-KYSDI3GE.js +0 -5
- package/dist/chunk-L6PJPETJ.js +0 -29
- package/dist/chunk-LDVT66YM.js +0 -2
- package/dist/chunk-LEECKFCJ.js +0 -2
- package/dist/chunk-LMZ5PRUV.js +0 -2
- package/dist/chunk-LQRQN2XA.js +0 -2
- package/dist/chunk-LXABEJX3.js +0 -2
- package/dist/chunk-MNV5FSBW.js +0 -3
- package/dist/chunk-MPQ4OTBM.js +0 -2
- package/dist/chunk-MTDBHTSF.js +0 -2
- package/dist/chunk-MV3CDXPI.js +0 -38
- package/dist/chunk-MWN53KRN.js +0 -60
- package/dist/chunk-MXNGIEPU.js +0 -3
- package/dist/chunk-N2ZSIIGR.js +0 -117
- package/dist/chunk-N5B2NILC.js +0 -5
- package/dist/chunk-NJITK2GP.js +0 -2
- package/dist/chunk-NOGJXYFO.js +0 -2
- package/dist/chunk-NOYBFVJA.js +0 -554
- package/dist/chunk-NWQXSFFU.js +0 -3
- package/dist/chunk-ODDUPDP7.js +0 -13
- package/dist/chunk-OLIWTZI3.js +0 -3
- package/dist/chunk-OLNV6I6U.js +0 -2
- package/dist/chunk-OR2E3AGZ.js +0 -2
- package/dist/chunk-OSR2GEHQ.js +0 -2
- package/dist/chunk-OSSESPDX.js +0 -3
- package/dist/chunk-OWOOWNJ5.js +0 -7
- package/dist/chunk-P42EIXTA.js +0 -2
- package/dist/chunk-PJFGPYTU.js +0 -2
- package/dist/chunk-PP7KNN7L.js +0 -2
- package/dist/chunk-PU7T5QYQ.js +0 -2
- package/dist/chunk-PWWAJSKV.js +0 -74
- package/dist/chunk-PZL5T7SU.js +0 -73
- package/dist/chunk-QBE3YX64.js +0 -23
- package/dist/chunk-QGVTFRY2.js +0 -7
- package/dist/chunk-QOJONDS7.js +0 -2
- package/dist/chunk-QU5XRYB5.js +0 -4
- package/dist/chunk-QUU5OBVK.js +0 -11
- package/dist/chunk-RBLQNW26.js +0 -20
- package/dist/chunk-RTQ7NEKG.js +0 -81
- package/dist/chunk-SQXRS7BG.js +0 -4
- package/dist/chunk-SSK6LDPC.js +0 -2
- package/dist/chunk-SZHGTCPP.js +0 -7
- package/dist/chunk-T4N4P2K5.js +0 -16
- package/dist/chunk-TA3QKLLU.js +0 -2
- package/dist/chunk-TEBQMNVI.js +0 -43
- package/dist/chunk-TPFHAQ2G.js +0 -2
- package/dist/chunk-TQPCBMWT.js +0 -5
- package/dist/chunk-TQZV7KV4.js +0 -2
- package/dist/chunk-TRNAEQ6P.js +0 -3
- package/dist/chunk-TY7CRN3Z.js +0 -2
- package/dist/chunk-UHFYCMZO.js +0 -35
- package/dist/chunk-UICY4GTQ.js +0 -7
- package/dist/chunk-UVGEWT4Y.js +0 -26
- package/dist/chunk-UXW33INU.js +0 -29
- package/dist/chunk-VMPRET3I.js +0 -5
- package/dist/chunk-VNLGKHS6.js +0 -6
- package/dist/chunk-VQILFTEH.js +0 -2
- package/dist/chunk-VUPHCS7Y.js +0 -57
- package/dist/chunk-VVZSBTSU.js +0 -23
- package/dist/chunk-VZRNID6A.js +0 -2
- package/dist/chunk-W5OXRYGE.js +0 -7
- package/dist/chunk-W6STWDQI.js +0 -57
- package/dist/chunk-W7CXK74K.js +0 -2
- package/dist/chunk-WB3WYIRE.js +0 -4
- package/dist/chunk-WDNVY4E7.js +0 -20
- package/dist/chunk-WK46TNUM.js +0 -3
- package/dist/chunk-WNTFFKAX.js +0 -12
- package/dist/chunk-WOIKCX6A.js +0 -2
- package/dist/chunk-WUN6KBHV.js +0 -2
- package/dist/chunk-WYCTJDVR.js +0 -2
- package/dist/chunk-WYPL7GF7.js +0 -2
- package/dist/chunk-XDAUYDFT.js +0 -2
- package/dist/chunk-XDQMU3BT.js +0 -2
- package/dist/chunk-XFA4SSO3.js +0 -3
- package/dist/chunk-XGZEP6GR.js +0 -8
- package/dist/chunk-XPDPNWTQ.js +0 -368
- package/dist/chunk-XRYABF57.js +0 -8
- package/dist/chunk-YBGKCQIS.js +0 -2
- package/dist/chunk-YEN6CYC7.js +0 -16
- package/dist/chunk-YF5IB2LF.js +0 -2
- package/dist/chunk-YI2AWIHC.js +0 -3
- package/dist/chunk-YPWBKGFU.js +0 -2
- package/dist/chunk-YPWHBBIS.js +0 -2
- package/dist/chunk-YSH6U3L4.js +0 -3
- package/dist/chunk-YU5DZUZI.js +0 -10
- package/dist/chunk-YWO5DDRC.js +0 -16
- package/dist/chunk-Z4CDXYNQ.js +0 -2
- package/dist/chunk-ZF5KHH7C.js +0 -2
- package/dist/chunk-ZOHS7AQV.js +0 -21
- package/dist/chunk-ZTI4SBFV.js +0 -3
- package/dist/code-MI6F2TTU.js +0 -2
- package/dist/code-result-json-FXALY4HE.js +0 -2
- package/dist/command-descriptors-P34VABY5.js +0 -343
- package/dist/dataflow-4KEMJPC6.js +0 -2
- package/dist/dependence-slice-R7FPWD5M.js +0 -2
- package/dist/deps-7EMQUYUT.js +0 -2
- package/dist/direct-navigation-6YO234F2.js +0 -3
- package/dist/entry-map-KOOLR26E.js +0 -2
- package/dist/files-OPIPJIGZ.js +0 -2
- package/dist/graph-evidence-Bjyky2V4.d.ts +0 -126
- package/dist/hierarchy-QPD2CAER.js +0 -2
- package/dist/imports-M6HUXRXC.js +0 -2
- package/dist/members-I5MEFOCT.js +0 -2
- package/dist/methods-5JYGGHXA.js +0 -2
- package/dist/next-anchor-candidates-BwMczMvX.d.ts +0 -90
- package/dist/output-continuation-command-UPQAAKBP.js +0 -3
- package/dist/output-pagination-3OFL2MJV.js +0 -19
- package/dist/project-reindex-UKKQ5PLS.js +0 -3
- package/dist/queries/anchors.d.ts +0 -123
- package/dist/queries/anchors.js +0 -2
- package/dist/queries/complexity-hotspots.d.ts +0 -40
- package/dist/queries/complexity-hotspots.js +0 -2
- package/dist/queries/convergence.d.ts +0 -33
- package/dist/queries/convergence.js +0 -2
- package/dist/queries/dataflow.d.ts +0 -77
- package/dist/queries/dataflow.js +0 -2
- package/dist/queries/deep-chains.d.ts +0 -5
- package/dist/queries/deep-chains.js +0 -2
- package/dist/queries/extract-candidates.d.ts +0 -52
- package/dist/queries/extract-candidates.js +0 -2
- package/dist/queries/isolated.d.ts +0 -24
- package/dist/queries/isolated.js +0 -2
- package/dist/queries/plan-context.d.ts +0 -33
- package/dist/queries/plan-context.js +0 -2
- package/dist/queries/reference-neighborhood.d.ts +0 -4
- package/dist/queries/reference-neighborhood.js +0 -2
- package/dist/queries/reference-reachability.d.ts +0 -48
- package/dist/queries/reference-reachability.js +0 -2
- package/dist/queries/self-audit.d.ts +0 -63
- package/dist/queries/self-audit.js +0 -2
- package/dist/queries/similar-chains.d.ts +0 -48
- package/dist/queries/similar-chains.js +0 -2
- package/dist/queries/slice.d.ts +0 -4
- package/dist/queries/slice.js +0 -2
- package/dist/queries/stale-abstractions.d.ts +0 -72
- package/dist/queries/stale-abstractions.js +0 -2
- package/dist/queries/system-map.d.ts +0 -449
- package/dist/queries/system-map.js +0 -2
- package/dist/queries/trace.js +0 -2
- package/dist/queries/twin-ab.d.ts +0 -66
- package/dist/queries/twin-ab.js +0 -2
- package/dist/queries/value-flow.d.ts +0 -43
- package/dist/queries/value-flow.js +0 -2
- package/dist/queries/wrapper-candidates.d.ts +0 -34
- package/dist/queries/wrapper-candidates.js +0 -2
- package/dist/refs-PSU4JZZW.js +0 -2
- package/dist/refs-pagination-JG6CJMRC.js +0 -2
- package/dist/slice-HYRATV64.js +0 -2
- package/dist/source-snippet-_wrcgmZc.d.ts +0 -15
- package/dist/stats-OOJ74B32.js +0 -2
- package/dist/surface-VTGDYWF5.js +0 -2
- package/dist/symbol-resolution-WD5EU5JE.js +0 -2
- package/dist/system-LRQNFOR2.js +0 -2
- package/dist/trace-F4B6OLL4.js +0 -2
- package/dist/value-flow-VRPZY72V.js +0 -2
- package/skills/concrete-plan/SKILL.md +0 -8
- package/skills/concrete-plan/agents/openai.yaml +0 -4
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{$ as Af,$a as iu,$b as rr,$c as cu,$d as fo,$e as Ra,A as Xl,Aa as Js,Ab as eg,Ac as ea,Ad as Tg,Ae as cn,B as Ql,Ba as jr,Bb as _e,Bc as vt,Bd as Lg,Ca as wt,Cb as Ge,Cc as Xe,Cd as du,Ce as ba,D as Df,Db as tr,Dc as be,Dd as Mg,Df as ho,Ea as Uf,Eb as so,Ec as he,Ed as mu,Ee as Tn,Ef as Zg,F as Ff,Fa as nu,Fb as tg,Fc as ke,Fd as pa,Fe as sr,Ff as yo,Ga as ru,Gb as ng,Gc as ta,Gd as an,Ge as Sa,Hb as se,Hc as na,Hd as fa,Hf as wa,Ia as to,Ib as rg,Ic as ra,Id as $t,If as eh,Jb as Xs,Jc as pg,Jd as ot,Jf as th,Kb as ig,Kc as ia,Kd as Dg,Kf as nh,L as Zl,Lb as ou,Lc as oa,Ld as Fg,Mb as Gr,Mc as Yr,Md as ga,Na as qf,Nb as we,Nc as fg,Nd as En,Ne as Hg,Oa as no,Ob as nr,Oc as D,Pa as zf,Pb as ao,Pc as Pe,Pd as In,Qa as Hr,Qc as gg,Qd as po,Ra as X,Rc as hg,Rd as wn,Re as yu,S as kf,Sa as Gf,Sb as _,Sc as lo,Sd as kg,Se as va,T as eu,Tb as su,Tc as sa,Td as pu,Ua as At,Ub as co,Uc as ir,Ud as Ng,Ue as Ca,Va as bt,Vb as og,Vc as aa,Vd as fu,Ve as xt,Wa as nt,Wb as z,Wc as ca,Wd as Ag,Xb as sg,Xc as sn,Xd as gu,Y as Nf,Yb as ag,Yc as F,Yd as jt,Ye as xa,Za as Kf,Zb as cg,Zc as yg,Zd as ti,Ze as Ug,_ as Zn,_a as Wf,_b as _t,_c as it,_d as Pn,_e as qg,aa as _f,ab as Vf,ad as Bt,ae as ye,af as Ea,bb as q,bd as J,bf as zg,c as Zi,cb as Ur,cc as Kr,cd as la,cf as go,d as wf,db as Jf,dc as Qs,dd as ua,ea as Of,eb as Yf,ec as St,ed as Xr,ef as bu,fc as Wr,fd as Qr,fe as _g,ff as Su,g as Pf,gb as ro,gc as lg,gd as bg,gf as Gg,h as zs,hb as Xf,hd as uo,hf as Kg,hg as Cu,i as ee,ib as Qf,ic as Ot,id as Sg,j as ze,ja as Bf,jb as io,jc as V,jd as vg,jg as xu,kb as fe,kc as ug,kd as Cg,l as Qn,la as Vs,lc as dg,ld as xg,lg as rh,m as Gs,ma as eo,mc as Zs,md as da,mf as Ia,n as rn,na as te,nc as Vr,nd as Zr,ne as Og,o as Ks,oa as xe,oc as Fe,od as ma,oe as ni,pa as Ae,pb as Zf,pd as ei,pe as ha,qa as Br,qb as M,qd as Rg,qe as ya,qg as ih,r as Ws,ra as $f,rb as qr,rd as Eg,re as ri,rg as oh,s as ht,sa as jf,sb as Ys,sd as Ig,se as Ct,t as Ye,tb as rt,td as wg,tf as Wg,ub as er,uc as on,ud as lu,ue as or,uf as Vg,v as Tf,va as Hf,vb as Re,vc as Jr,vd as Pg,vf as Jg,w as Yl,wa as k,wb as H,wc as mg,we as Bg,wf as Yg,wg as sh,x as Lf,xa as $r,xb as oo,xc as L,xe as $g,xf as vu,xg as ah,y as Mf,ya as tu,yb as j,yc as A,yd as uu,ye as hu,yf as Xg,yg as ch,za as yt,zb as zr,zc as au,zd as mo,ze as jg,zf as Qg}from"./chunk-OZCJXZK6.js";var xT=/^[A-Za-z0-9_@%+=:,./-]+$/u;function O(e,t={}){return t.omitSafeQuotes&&xT.test(e)?e:(t.platform??process.platform)==="win32"?`"${e.replaceAll("%","%%").replaceAll('"','\\"')}"`:`'${e.replaceAll("'",`'"'"'`)}'`}import{statSync as RT}from"fs";import{isAbsolute as Pa,join as ET,relative as lh}from"path";function Ht(e,t){let n=Ru(e,t,{allowMultiple:!1})[0]?.relativePath;return n||dh(e,t)}function ar(e,t){return Ru(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function bo(e,t){let n=Ru(e,t,{allowMultiple:!0});return n.length===1?n[0].relativePath:null}function uh(e,t){let n=Ur(e,t,{allowMultiple:!0,requirePathMatch:!0});return n.length===1?n[0].relativePath:null}function dh(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=Pa(n)?lh(e.config.projectRoot,n):n;if(r===".."||r.startsWith("../")||Pa(r))return null;let i=ET(e.config.projectRoot,r);return RT(i,{throwIfNoEntry:!1})?.isFile()?r:null}function Ru(e,t,n){if(n.allowMultiple&&t.trim()){let c=IT(e,t);if(c.length)return c}let r=dh(e,t);if(r)return Ur(e,r,n).filter(c=>c.relativePath===r);let i=t.replace(/\\/g,"/").replace(/^\.\//,""),o=Pa(i)||i.includes("/"),s=Ur(e,t,{...n,requirePathMatch:o});if(s.length||o)return s;let a=Bt(e,t);return!a||e.isIgnored(a.relativePath)?[]:[{relativePath:a.relativePath,score:700}]}function IT(e,t){let r=(Pa(t)?lh(e.config.projectRoot,t):t).replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,""),i=r==="."||r===""?"":`${r}/`;return q(e,{includeIgnored:!1}).filter(s=>s.startsWith(i)).map(s=>({relativePath:s,score:1100}))}function mh(e,t){let n=bo(e,t);if(!n)return[];if(it(e,n)?.freshness.semantic.state==="stale")throw new Error(`Compiler ownership is stale for ${n}. Reindex or read the current file with code.`);let i=sa(e,[n],{sort:!0});if(i.length===0)return[];let o=Math.max(0,oo(H(e,n)).length-1),s=i.map(u=>({symbol:u.symbol,shortName:u.shortName,startLine:u.startLine,endLine:Math.min(u.endLine,o),signature:u.signature,children:[]})),a=new Map;for(let u of s)a.set(u.symbol,u);let c=[],l=new Map;for(let u=0;u<i.length;u++){let d=i[u],m=s[u];if(d.enclosingSymbol&&a.has(d.enclosingSymbol)){let f=a.get(d.enclosingSymbol);f.children.push(m),l.set(m,f);continue}let p=wT(m,s);p?(p.children.push(m),l.set(m,p)):c.push(m)}return PT(n,s,l),c}function wT(e,t){let n=null,r=1/0;for(let i of t)if(i!==e&&i.startLine<=e.startLine&&i.endLine>=e.endLine){if(i.startLine===e.startLine&&i.endLine===e.endLine&&!ra(i.symbol,e.symbol))continue;let s=i.endLine-i.startLine;s<r&&(r=s,n=i)}return n}function PT(e,t,n){let r=new Set;for(let i of t){let o=new Set,s=i;for(;s&&!r.has(s);){if(o.has(s))throw new Error(`Cyclic compiler ownership in ${e}. Reindex before using this outline.`);o.add(s),s=n.get(s)}for(let a of o)r.add(a)}}import{basename as NL,extname as Oh}from"path";function Pt(e,t){let n=j(e,t.relativePath);if(n.length===0)return!1;let r=A(t.symbol);if(!r)return!1;let i=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
|
|
3
|
+
`),o=Ge(r);return new RegExp(`^\\s*export\\s+(?:default\\s+)?(?:(?:async\\s+)?function\\s+${o}\\b|(?:abstract\\s+)?class\\s+${o}\\b|(?:interface|type|enum|namespace|module)\\s+${o}\\b|(?:const|let|var)\\s+${o}\\b)`,"m").test(i)?!0:TT(n,r)}function TT(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${Ge(t)}\\b`);return e.some(r=>n.test(r))}var LT=12,MT=280;function ii(e,t,n,r){let i=DT(e,t,n,r);if(i.size===0)return AT();let o=[],s=new Set,a=(l,u,d,m)=>{if(u===t&&d<=r&&m>=n)return;let p=`${u}:${d}:${m}:${l}`;s.has(p)||(s.add(p),o.push({name:l,relativePath:u,startLine:d,endLine:m}))};for(let l of D(e,t))i.has(l.leaf)&&a(l.leaf,l.relativePath,l.startLine,l.endLine);_T(e,t,i,a),o.sort(fh);let c=o.map(l=>{let u=FT(e,l);return u?{...l,source:u}:null}).filter(l=>l!==null).slice(0,LT);return Eu(c)}function Ta(e,t=[]){return Eu(kT(e.flatMap(n=>n?.inline??[]),t))}function ph(e){return e?e.inline.reduce((t,n)=>t+n.name.length+n.source.length+32,0):0}function DT(e,t,n,r){let i=z(e,t),o=new Set;if(!i)return o;for(let s=n;s<=r;s+=1)for(let a of i.identifiersByLine[s]??[])o.add(a);return o}function FT(e,t){if(t.startLine!==t.endLine)return null;let n=(j(e,t.relativePath)[t.startLine]??"").trim();if(!n||n.length>MT)return null;let r=n.indexOf("=");if(r<0||n[r+1]===">")return null;let i=n.slice(r+1).replace(/(?:\/\/|#).*$/u,"").trim();return OT(i)?n:null}function kT(e,t){let n=new Map;for(let r of e){if(NT(r,t))continue;let i=`${r.relativePath}:${r.startLine}:${r.endLine}:${r.name}`;n.has(i)||n.set(i,{...r})}return[...n.values()].sort(fh)}function NT(e,t){return t.some(n=>n.relativePath===e.relativePath&&n.startLine<=e.startLine&&n.endLine>=e.endLine)}function fh(e,t){return e.relativePath.localeCompare(t.relativePath)||e.startLine-t.startLine||e.name.localeCompare(t.name)}function Eu(e){return{coverage:"indexed-project-literal-values",inline:e}}function AT(){return Eu([])}function _T(e,t,n,r){for(let i of V(e,t)){let o=i.localName;if(!o||!n.has(o)||!i.sourcePath||i.kind==="namespace")continue;let s=i.importedName==="default"?o:i.importedName;for(let a of En(e,i.sourcePath,s,{maxReexportDepth:3}))r(o,a.relativePath,a.startLine,a.endLine)}}function OT(e){if(!e||e.includes("${")||/\b(?:function|class|struct|interface|trait|enum|lambda)\b/u.test(e))return!1;let n=e.replace(/(['"`])(?:\\.|(?!\1).)*\1/gu,"").replace(/\b(?:0[xX][\dA-Fa-f_]+|0[bB][01_]+|0[oO][0-7_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:[eE][+-]?\d+)?)n?\b/gu,""),r=new Set(["true","false","null","undefined","None","True","False"]);return!(n.match(/[A-Za-z_][A-Za-z0-9_]*/gu)??[]).some(o=>!r.has(o))}var BT=12,$T=20,wu=200,Tu=800,jT=.9,HT=64,UT=Gf("behavior-construct-ranges"),yh={if_statement:"branch",conditional_expression:"branch",ternary_expression:"branch",switch_statement:"branch",switch_expression:"branch",switch_case:"branch",case_statement:"branch",match_statement:"branch",match_expression:"branch",match_arm:"branch",for_statement:"loop",for_in_statement:"loop",for_of_statement:"loop",while_statement:"loop",do_statement:"loop",await_expression:"await",return_statement:"return",throw_statement:"throw",raise_statement:"throw",assignment_expression:"mutation",augmented_assignment_expression:"mutation",assignment:"mutation",pair:"shape",field_initializer:"shape",spread_element:"spread",dictionary_splat:"spread",catch_clause:"catch",except_clause:"catch",finally_clause:"finally"},Na=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],bh=[...Na,"lifecycle"],Sh=["loop","await","throw","mutation","spread","catch","finally","lifecycle"],qT=new Set(["onBeforeMount","onBeforeUnmount","onMounted","onUnmounted","useEffect","useInsertionEffect","useLayoutEffect"]);var vh=new Set(["object","object_pattern","dictionary","field_declaration_list","struct_expression","struct_pattern"]);function oi(e,t,n,r,i=[],o={}){let s=_(e,t);if(!s)return null;let a=j(e,t),{callable:c,rangeStart:l,rangeEnd:u,root:d}=GT(e,t,n,r,i,s.rootNode);if(!d)return null;let m=Ih(d,a,l,u,i);if(!m||m.lines.length===0||m.lines.some(h=>h.text.length>Tu))return null;let p=hL(a,l,u),f=yL(m);if(zT(p,f,o.requireSavings))return null;let g=Na.filter(h=>m.lines.some(y=>y.signals.includes(h)));return{...c?{callable:{name:c.name,startLine:c.startLine,endLine:c.endLine}}:{},representation:"outline",constructKind:m.constructKind,signature:m.signature,lines:m.lines,signals:g,testCases:F(t)==="test"?IL(a,l,u):[],coverage:{sourceStatements:m.sourceStatements,representedStatements:m.sourceStatements,copiedStatements:m.copiedStatements,omittedStatements:0},rawCharacters:p,outlineCharacters:f,candidateLines:m.sourceStatements,omittedLines:0}}function zT(e,t,n){return(n??!0)&&t>=e*jT}function GT(e,t,n,r,i,o){let s=Lt(e,t,n,r,i),a=Oa(e,t,s.startLine,s.endLine),c=a?.startLine??n,l=a?.endLine??r,u=(a?wo(o,s.startLine,s.endLine):null)??Gr(o,c,l);return{callable:a,rangeStart:c,rangeEnd:l,root:u}}function Aa(e,t,n,r,i){if(i.length===0)return[];let o=_(e,t);if(!o)return[];let s=j(e,t),a=Lt(e,t,n,r,i),c=Oa(e,t,a.startLine,a.endLine),l=c?.startLine??n,u=c?.endLine??r,d=(c?wo(o.rootNode,a.startLine,a.endLine):null)??Gr(o.rootNode,l,u);if(!d)return[];let m=Ih(d,s,l,u,i);return m?m.lines.filter(p=>p.text.length<=Tu&&p.signals.some(f=>["branch","loop","catch","finally"].includes(f))&&i.some(f=>f>=p.line&&f<=p.endLine)):[]}function Ch(e,t,n,r,i={}){let o=_(e,t);if(!o)return null;let s=nr(o.rootNode,n,r,we,i);if(!s)return null;let a=[],c=Du(s),l=[];return Fu(s,s,u=>{if(vo.has(u.type)||XT.has(u.type)){ZT(a,l,u);return}if(_a.has(u.type)){eL(a,l,u);return}if(Eo.has(u.type)){tL(a,l,u);return}Io.has(u.type)&&rL(a,u)}),{facts:cL(a),terminals:Eh(c),unsupported:l}}function Lt(e,t,n,r,i=[]){let o=i.filter(u=>u>=n&&u<=r),s=UT.get(e,t,H(e,t)??"",()=>new Map),a=`${n}:${r}:${o.join(",")}`,c=s.get(a);if(c)return s.delete(a),s.set(a,c),{startLine:c[0],endLine:c[1]};let l=WT(e,t,n,r,o);if(s.set(a,[l.startLine,l.endLine]),s.size>HT){let u=s.keys().next().value;u!==void 0&&s.delete(u)}return l}function KT(e,t,n,r,i){let o=[],s=r[0],a=s;for(let l of r)s=Math.min(s,l),a=Math.max(a,l);return Th(e,s,a,l=>{lL(l)&&l.startPosition.row>=t&&l.endPosition.row<=n&&r.every(u=>l.startPosition.row<=u&&l.endPosition.row>=u)&&o.push(l),we.has(l.type)&&l.startPosition.row>=t&&l.endPosition.row<=n&&r.every(u=>l.startPosition.row<=u&&l.endPosition.row>=u)&&i.push(l)}),o.sort((l,u)=>l.endPosition.row-l.startPosition.row-(u.endPosition.row-u.startPosition.row)||l.startPosition.row-u.startPosition.row)[0]}function WT(e,t,n,r,i){let o=_(e,t),s=[];if(i.length>0&&o){let u=KT(o.rootNode,n,r,i,s);if(u)return{startLine:u.startPosition.row,endLine:u.endPosition.row}}let a=Oa(e,t,n,r);if(a)return{startLine:a.startLine,endLine:a.endLine};if(i.length===0)return{startLine:n,endLine:r};let c=(z(e,t)?.callables??[]).filter(u=>u.startLine>=n&&u.endLine<=r&&i.every(d=>u.startLine<=d&&u.endLine>=d)).sort((u,d)=>u.endLine-u.startLine-(d.endLine-d.startLine)||u.startLine-d.startLine)[0];if(!o)return hh(c,n,r);let l=s.sort((u,d)=>u.endPosition.row-u.startPosition.row-(d.endPosition.row-d.startPosition.row)||u.startPosition.row-d.startPosition.row)[0];return l?{startLine:l.startPosition.row,endLine:l.endPosition.row}:hh(c,n,r)}function Lu(e,t,n,r,i={}){if(r-n+1<(i.minimumBodyLines??$T))return null;let s=Ph(e,t,n,r,[],!1);if(!s)return null;let a=s.candidates.map(f=>({...f,signals:f.signals.filter(g=>g!=="anchor"&&g!=="signature")})).filter(f=>f.signals.length>0);if(a.length===0)return null;let c=RL(a),l=a.filter(f=>f.text.length<=wu);if(l.length===0)return null;let u=Sh.filter(f=>(c[f]??0)>0);if(!VT(u,c,s.shapes))return null;let d=EL(l,c),m=JT(d,u),p=YT(m,i.maxLines);return p.size>=a.length&&s.shapes.length===0?null:{owner:s.callable?.name??null,startLine:n,endLine:r,lines:[...p.values()].sort((f,g)=>f.line-g.line),shapes:s.shapes,signalCounts:c,candidateLines:a.length,omittedLines:a.length-p.size}}function VT(e,t,n){let r=e.filter(o=>o!=="await"),i=n.reduce((o,s)=>o+s.fields.length,0);return!(r.length===0&&!((t.await??0)>0&&i>0)&&i<3)}function JT(e,t){let n=new Map;for(let r of t){let i=e.find(o=>o.signals.includes(r));i&&n.set(i.line,i)}if(n.size===0){let r=e.find(i=>i.signals.includes("branch"));r&&n.set(r.line,r)}return n}function YT(e,t){let n=Math.min(10,Math.max(1,t??e.size)),r=new Map;for(let i of e.values()){if(r.size>=n)break;r.set(i.line,i)}return r}function ln(e,t,n,r){let i=Ph(e,t,n,r,[],!1);return i?new Map(i.candidates.map(o=>[o.line,o.signals.filter(s=>s!=="lifecycle")])):new Map}var st=new Set(["block","body","compound_statement","declaration_list","statement_block"]),vo=new Set(["if_expression","if_statement","unless","unless_statement"]),XT=new Set(["conditional_expression","ternary_expression"]),_a=new Set(["do_statement","enhanced_for_statement","for_expression","for_in_statement","for_of_statement","for_statement","loop_expression","while_statement"]),Eo=new Set(["match_expression","match_statement","switch_expression","switch_statement"]),xh=new Set(["case_statement","match_arm","switch_case","switch_default"]),Io=new Set(["try_expression","try_statement"]),Ma=new Set(["catch_clause","except_clause","rescue"]),xo=new Set(["ensure","finally_clause"]),Co=new Set(["else","else_clause"]),Rh=new Set(["raise_statement","return_statement","throw_statement"]),QT=new Set(["block_comment","comment","line_comment"]);function ZT(e,t,n){let r=n.childForFieldName("condition")??Nu(n),i=n.childForFieldName("consequence")??n.childForFieldName("body")??n.namedChildren.find(c=>st.has(c.type)),o=n.childForFieldName("alternative")??n.namedChildren.find(c=>Co.has(c.type));if(!r||!i){t.push(ku(n,"conditional-fields-unresolved"));return}let s=qt(r,"predicate",r.text),a=qt(i,gh(i),"consequence");if(Ut(e,s,a,"predicate-consequence",{branchRole:"consequence"}),Da(e,s,i,"consequence"),o){let c=qt(o,gh(o),"alternative");Ut(e,s,c,"predicate-alternative",{branchRole:"alternative"}),Da(e,s,o,"alternative");return}Ut(e,s,Mu(s,"otherwise continue"),"predicate-fallthrough",{branchRole:"fallthrough"})}function eL(e,t,n){let r=n.childForFieldName("body")??n.namedChildren.find(s=>st.has(s.type));if(!r){t.push(ku(n,"loop-body-unresolved"));return}let i=n.childForFieldName("condition"),o=qt(i??n,"predicate",i?.text??Tt(n,r));Ut(e,o,qt(r,"outcome","iteration"),"loop-iteration",{branchRole:"iteration"}),Da(e,o,r,"iteration"),Ut(e,o,Mu(o,"loop exits"),"loop-exit",{branchRole:"exit"})}function tL(e,t,n){let r=n.childForFieldName("body")??n.namedChildren.find(c=>st.has(c.type)),i=n.childForFieldName("value")??n.childForFieldName("condition")??n.childForFieldName("subject")??Nu(n),o=oL(r??n);if(!i||o.length===0){t.push(ku(n,"switch-cases-unresolved"));return}let s=qt(i,"predicate",i.text),a=!1;for(let c of o){let l=nL(e,s,c);a||=l}a||Ut(e,s,Mu(s,"no case matched"),"predicate-fallthrough",{branchRole:"fallthrough"})}function nL(e,t,n){let r=aL(n),i=Tt(n,n.namedChildren.find(o=>Fa(o)));return Ut(e,t,qt(n,"outcome",i||(r?"default":"case")),r?"predicate-default":"predicate-case",{branchRole:r?"default":"case"}),Da(e,t,n,r?"default":"case"),r}function rL(e,t){let n=qt(t,"scope","try");for(let r of sL(t)){let i=xo.has(r.type),o=qt(r,"handler",i?"finally":Tt(r,La(r)));Ut(e,n,o,i?"finally-cleanup":"exception-handler",{branchRole:i?"finally":"catch"}),iL(e,o,r,i?"finally":"catch")}}function iL(e,t,n,r){for(let i of Du(n)){let o=i.label.startsWith("throw")||i.label.startsWith("raise")?"throw":"return";Ut(e,t,i,o==="throw"?"handler-throw":"handler-return",{branchRole:r,terminalKind:o})}}function Da(e,t,n,r){for(let i of Du(n)){let o=i.label.startsWith("throw")||i.label.startsWith("raise")?"throw":"return";Ut(e,t,i,o==="throw"?"predicate-throw":"predicate-return",{branchRole:r,terminalKind:o})}}function Ut(e,t,n,r,i){e.push({controller:t,outcome:n,subtype:r,attributes:i})}function qt(e,t,n){return{kind:t,label:Ro(n).slice(0,Tu),startLine:e.startPosition.row,endLine:e.endPosition.row,startColumn:e.startPosition.column,endColumn:e.endPosition.column,implicit:!1}}function Mu(e,t){return{...e,kind:"outcome",label:t,implicit:!0}}function gh(e){return Rh.has(e.type)?"terminal":"outcome"}function Du(e){let t=[];return Fu(e,e,n=>{Rh.has(n.type)&&t.push(qt(n,"terminal",n.text))}),Eh(t)}function Fu(e,t,n){n(t);for(let r of t.namedChildren)r!==e&&we.has(r.type)||Fu(e,r,n)}function oL(e){let t=[],n=r=>{for(let i of r.namedChildren)Eo.has(i.type)||(xh.has(i.type)?t.push(i):n(i))};return n(e),t}function sL(e){let t=[],n=r=>{for(let i of r.namedChildren)Io.has(i.type)||(Ma.has(i.type)||xo.has(i.type)?t.push(i):we.has(i.type)||n(i))};return n(e),t}function aL(e){let t=Tt(e,e.namedChildren.find(n=>Fa(n))).trim();return e.type==="switch_default"||/^(?:default\b|_\s*=>)/u.test(t)}function ku(e,t){return{startLine:e.startPosition.row,endLine:e.endPosition.row,reason:t}}function cL(e){let t=new Map;for(let n of e)t.set(`${Pu(n.controller)}\0${Pu(n.outcome)}\0${n.subtype}`,n);return[...t.values()]}function Eh(e){let t=new Map;for(let n of e)t.set(Pu(n),n);return[...t.values()]}function Pu(e){return`${e.startLine}:${e.startColumn??""}:${e.endLine}:${e.endColumn??""}:${e.kind}:${e.label}`}function lL(e){return we.has(e.type)||_a.has(e.type)||Eo.has(e.type)||Io.has(e.type)||Ma.has(e.type)||xo.has(e.type)}function Ih(e,t,n,r,i){let s=wo(e,n,r)??e,a=La(s),c=[],l=0,u=0,d=(v,C,R,P,w=!1,T=!0)=>{let G=w?R.trim():Ro(R);if(!G)return;let K=Math.max(n,v.startPosition.row),ue=Math.min(r,v.endPosition.row);c.push({line:K,endLine:Math.max(K,ue),depth:C,signals:Na.filter(ce=>P.includes(ce)||ce==="anchor"&&i.some(Ce=>Ce>=K&&Ce<=ue)),text:G,copied:w}),T&&(l+=1,w&&(u+=1))},m=(v,C)=>{for(let R of v.namedChildren)b(R,C)},p=(v,C)=>{if(vo.has(v.type)){f(v,C,"else if");return}if(Co.has(v.type)){let R=v.namedChildren.find(w=>vo.has(w.type));if(R){f(R,C,"else if");return}d(v,C,"else",["branch"],!1,!1);let P=La(v)??v.namedChildren.find(w=>st.has(w.type));if(P)b(P,C+1);else for(let w of v.namedChildren)b(w,C+1);return}d(v,C,"else",["branch"],!1,!1),b(v,C+1)},f=(v,C,R=v.type.startsWith("unless")?"unless":"if")=>{let P=v.childForFieldName("condition")??Nu(v),w=v.childForFieldName("consequence")??v.childForFieldName("body")??v.namedChildren.find(K=>st.has(K.type)),T=v.childForFieldName("alternative")??v.namedChildren.find(K=>Co.has(K.type)),G=P?P.text:Tt(v,w);d(v,C,`${R} ${fL(G)}`,So(P,["branch"])),w&&b(w,C+1),T&&p(T,C)},g=(v,C)=>{let R=v.childForFieldName("body")??v.namedChildren.find(P=>st.has(P.type));d(v,C,Tt(v,R),So(v,["loop"])),R&&b(R,C+1)},h=(v,C)=>{let R=v.childForFieldName("body")??v.namedChildren.find(P=>st.has(P.type));d(v,C,Tt(v,R),So(v,["branch"])),R&&b(R,C+1)},y=(v,C)=>{let R=v.namedChildren.find(P=>Fa(P));d(v,C,Tt(v,R),["branch"],!1,!1);for(let P of v.namedChildren)(P===R||Fa(P))&&b(P,C+1)},S=(v,C)=>{d(v,C,"try",[],!1);for(let R of v.namedChildren)st.has(R.type)?b(R,C+1):(Ma.has(R.type)||xo.has(R.type))&&b(R,C)},I=(v,C,R)=>{let P=v.childForFieldName("body")??v.namedChildren.find(T=>st.has(T.type)),w=R==="finally"?"finally":Tt(v,P);d(v,C,w,[R],!1,!1),P&&b(P,C+1)},x=(v,C)=>{let R=La(v);d(v,C,Tt(v,R),So(v,["binding"])),R&&b(R,C+1)},E=(v,C)=>vo.has(v.type)?(f(v,C),!0):_a.has(v.type)?(g(v,C),!0):Eo.has(v.type)?(h(v,C),!0):xh.has(v.type)?(y(v,C),!0):Io.has(v.type)?(S(v,C),!0):Ma.has(v.type)?(I(v,C,"catch"),!0):xo.has(v.type)?(I(v,C,"finally"),!0):!1,b=(v,C)=>{if(v.startPosition.row>r||v.endPosition.row<n||QT.has(v.type)||v.type==="empty_statement")return;if(st.has(v.type)){m(v,C);return}if(E(v,C))return;if(Co.has(v.type)){p(v,C);return}if(we.has(v.type)){x(v,C);return}let P=!wh(v)||gL(v);d(v,C,v.text,So(v),P)};return b(a&&a!==s?a:s,0),l===0?null:{constructKind:pL(s),signature:dL(s,a,t,n),lines:c,sourceStatements:l,copiedStatements:u}}function wo(e,t,n){let r=e.namedChildren.filter(i=>i.startPosition.row<=t&&i.endPosition.row>=n);for(let i of r.sort(uL)){let o=wo(i,t,n);if(o)return o}return we.has(e.type)&&e.startPosition.row<=t&&e.endPosition.row>=n?e:null}function uL(e,t){return e.endPosition.row-e.startPosition.row-(t.endPosition.row-t.startPosition.row)||e.startPosition.row-t.startPosition.row}function La(e){return e.childForFieldName("body")??e.childForFieldName("consequence")??e.namedChildren.find(t=>st.has(t.type))??null}function dL(e,t,n,r){let i=Tt(e,t);return i||(n[r]??e.text).trim()}var mL=new Set(["arrow_function","function_expression","lambda"]);function pL(e){return e.type.includes("constructor")?"constructor":e.type.includes("method")||e.type==="method"?Iu(e,new Set(["class_body","class_declaration","class_definition"]))?"class method":"object method":mL.has(e.type)?Iu(e,new Set(["object","pair"]))?"object member":"function value":e.type.includes("function")?Iu(e,we)?"nested function":"module function":"source construct"}function Iu(e,t){let n=e.parent;for(;n;){if(t.has(n.type))return!0;n=n.parent}return!1}function Nu(e){return e.namedChildren.find(t=>!st.has(t.type)&&!Co.has(t.type))??null}function Tt(e,t){if(!t)return Ro(e.text);let n=Math.max(0,t.startIndex-e.startIndex);return Ro(e.text.slice(0,n)).replace(/[:{]\s*$/u,"").trim()}function fL(e){let t=Ro(e);return t.startsWith("(")&&t.endsWith(")")?t.slice(1,-1).trim():t}function Ro(e){return e.trim().replace(/\r?\n[\t ]*/gu," ")}function So(e,t=[]){let n=new Set(t);return e&&Po(e,r=>{let i=yh[r.type];i&&n.add(i),r.type==="call_expression"&&(n.add("call"),Lh(r)&&n.add("shape")),Au.has(r.type)&&n.add("binding")}),Na.filter(r=>n.has(r))}function gL(e){let t=!1;return Po(e,n=>{t||!n.text.includes(`
|
|
4
|
+
`)||/(?:string|template|heredoc|raw_string)/u.test(n.type)&&(t=!0)}),t}function Fa(e){return st.has(e.type)||vo.has(e.type)||_a.has(e.type)||Eo.has(e.type)||Io.has(e.type)||we.has(e.type)||wh(e)}function wh(e){return/(?:statement|declaration|expression|assignment|return|throw|raise|break|continue|yield|with_item)$/u.test(e.type)||Au.has(e.type)}function hL(e,t,n){let r=0;for(let i=t;i<=n;i+=1)r+=(e[i]?.length??0)+10;return r}function yL(e){return e.constructKind.length+e.signature.length+80+e.lines.reduce((t,n)=>t+n.text.length+n.depth*2+10,0)}function Ph(e,t,n,r,i,o){let s=bL(e,t,n,r,o);if(!s)return null;let{callable:a,rangeStart:c,rangeEnd:l,root:u,sourceLines:d}=s,m=new Map,p=new Map,f=new Map,g=(y,S)=>{if(y<c||y>l)return;let I=m.get(y)??new Set;I.add(S),m.set(y,I)};a&&g(a.startLine,"signature");for(let y of i)g(y,"anchor");Po(u,y=>{let S=yh[y.type];S&&g(y.startPosition.row,S),S==="shape"&&vL(p,y,u,c,l),y.type==="call_expression"&&wL(y,g,f),Au.has(y.type)&&g(y.startPosition.row,"binding")}),SL(e,t,c,l,g);let h=[...m.entries()].sort(([y],[S])=>y-S).map(([y,S])=>({line:y,signals:bh.filter(I=>S.has(I)),text:f.get(y)??ka(d[y]??"")})).filter(y=>y.text.length>0||y.signals.includes("anchor"));return{...a?{callable:a}:{},rangeStart:c,rangeEnd:l,sourceLines:d,candidates:h,shapes:[...p.values()].sort((y,S)=>y.startLine-S.startLine)}}function bL(e,t,n,r,i){let o=_(e,t);if(!o)return null;let s=j(e,t),a=Oa(e,t,n,r),c=i?a?.startLine??n:n,l=i?a?.endLine??r:r,d=(a?.startLine===c&&a.endLine===l?wo(o.rootNode,c,l):null)??Gr(o.rootNode,c,l);return d?{callable:a,rangeStart:c,rangeEnd:l,root:d,sourceLines:s}:null}function SL(e,t,n,r,i){let o=z(e,t);for(let s of o?.callSites??[])s.line<n||s.line>r||(i(s.line,"call"),s.calleeLeaf==="catch"&&i(s.line,"catch"))}function vL(e,t,n,r,i){if(t.startPosition.row<r||t.endPosition.row>i)return;let o=t.childForFieldName("key")??t.childForFieldName("name")??t.namedChild(0),s=ka(o?.text??"");!s||s.includes(`
|
|
5
|
+
`)||s.length>60||CL(e,t,n,r,i,s)}function CL(e,t,n,r,i,o){let s=xL(t,n);if(s.startPosition.row<r||s.endPosition.row>i)return;let a=`${s.startPosition.row}:${s.endPosition.row}`,c=e.get(a)??{startLine:s.startPosition.row,endLine:s.endPosition.row,fields:[]};c.fields.some(l=>l.name===o&&l.line===t.startPosition.row)||c.fields.push({name:o,line:t.startPosition.row}),e.set(a,c)}function xL(e,t){let n=e.parent;for(;n&&n!==t.parent;){if(vh.has(n.type))return n;if(n===t)break;n=n.parent}return e.parent??e}function Oa(e,t,n,r){return z(e,t)?.callables.filter(i=>i.startLine<=n&&i.endLine>=r).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine)||i.startLine-o.startLine)[0]}function Po(e,t){t(e);for(let n of e.namedChildren)Po(n,t)}function Th(e,t,n,r){r(e);for(let i of e.namedChildren)i.startPosition.row>t||i.endPosition.row<n||Th(i,t,n,r)}function ka(e){return e.trim().replace(/\s+/gu," ")}function Lh(e){if(e.type!=="call_expression")return!1;let t=e.childForFieldName("arguments")??e.namedChildren.find(r=>r.type==="arguments"||r.type==="argument_list");if(!t)return!1;let n=!1;return Po(t,r=>{vh.has(r.type)&&(n=!0)}),n}function RL(e){let t={};for(let n of bh){let r=e.filter(i=>i.signals.includes(n)).length;r>0&&(t[n]=r)}return t}function EL(e,t){let n=new Map;for(let o of e){let s=o.signals.join(",");n.set(s,(n.get(s)??0)+1)}let r=new Set(Sh),i=o=>{let s=n.get(o.signals.join(","))??1,a=Math.min(...o.signals.map(u=>t[u]??1)),c=o.signals.some(u=>r.has(u))?3:1,l=Math.max(0,o.signals.length-1)*1e3;return c*(1e3/s+1e3/a)+l};return[...e].sort((o,s)=>i(s)-i(o)||s.line-o.line)}var Au=new Set(["lexical_declaration","variable_declarator","const_item","static_item","let_declaration","assignment"]);function IL(e,t,n){let r=[],i=/\b(?:describe|it|test)(?:\.(?:only|skip|todo))?\s*\(\s*(['"`])([^'"`]+)\1/u;for(let o=t;o<=n;o+=1){let s=i.exec(e[o]??"")?.[2];if(!(!s||r.includes(s))&&(r.push(s),r.length>=BT))break}return r}function wL(e,t,n){let i=(e.childForFieldName("function")??e.namedChild(0))?.text.split(".").at(-1);if(Lh(e)){t(e.startPosition.row,"shape");let o=ka(e.text);o.length<=wu&&n.set(e.startPosition.row,o)}if(i&&qT.has(i)){t(e.startPosition.row,"lifecycle");let o=ka(e.text);o.length<=wu&&n.set(e.startPosition.row,o)}}function hh(e,t,n){return e?{startLine:e.startLine,endLine:e.endLine}:{startLine:t,endLine:n}}var PL=new Set(["arrow_function","class_declaration","constructor_declaration","field_definition","function_declaration","function_definition","function_expression","function_item","generator_function_declaration","generator_function","lexical_declaration","method","method_declaration","method_definition","object_method","variable_declaration"]);function si(e,t,n){let r=_(e,t)?.rootNode??null,i=TL(r,n);if(!i)return null;let o=j(e,t);if(o.length===0)return null;let s=Math.max(0,i.startPosition.row),a=i.endPosition.column===0?i.endPosition.row-1:i.endPosition.row;return{type:i.type,startLine:s,endLine:Math.min(o.length-1,Math.max(s,a))}}function To(e,t,n,r,i){let o=Lt(e,t,r,i,[n]),s=LL(e,t,o);if(!s&&(o.startLine>r||o.endLine<i))return o;let a=si(e,t,n);return s&&a?{startLine:a.startLine,endLine:a.endLine}:a&&a.startLine>=r&&a.endLine<=i?{startLine:a.startLine,endLine:a.endLine}:{startLine:r,endLine:i}}function TL(e,t){if(!e||!Fh(e,t))return null;let n=Dh(e,t);for(;n;){if(PL.has(n.type))return n;n=n.parent}return null}function Dh(e,t){let n=e.namedChildren.filter(r=>Fh(r,t)).sort((r,i)=>Mh(r)-Mh(i));return n.length>0?Dh(n[0],t):e}function Fh(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function Mh(e){return e.endIndex-e.startIndex}function LL(e,t,n){return n.startLine===n.endLine&&/(?:=>|\(|\{|\[|,)\s*$/u.test(j(e,t)[n.startLine]??"")}var ML=new Set(["call","call_expression","command","command_call","function_call_expression","invocation_expression","macro_invocation","method_call","method_invocation","new_expression","object_creation_expression"]);function Ba(e,t,n,r){if(!Number.isSafeInteger(n)||n<0)return null;if(!Number.isSafeInteger(r)||r<0)throw new RangeError(`contextLines must be a non-negative safe integer; received ${r}`);let i=j(e,t);if(i.length===0||n>=i.length)return null;let o=Math.max(0,n-r),s=Math.min(i.length-1,n+r);return{relativePath:t,startLine:o,endLine:s,focusLine:n,source:i.slice(o,s+1).join(`
|
|
6
|
+
`)}}function kh(e,t,n,r,i){let o=Ba(e,t,n,r);if(!o)return null;let s=_(e,t)?.rootNode??null;if(!s)return{...o,kind:"bounded-context"};let a=DL(s,n,i);if(a.length!==1)return{...o,kind:a.length===0?"non-call-reference":"bounded-context"};let c=a[0],l=j(e,t),u=Math.max(0,c.startPosition.row),d=c.endPosition.column===0?c.endPosition.row-1:c.endPosition.row,m=Math.min(l.length-1,Math.max(u,d));return{relativePath:t,startLine:u,endLine:m,focusLine:n,source:l.slice(u,m+1).join(`
|
|
7
|
+
`),kind:"complete-call-expression"}}function Nh(e,t,n,r,i){if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`maxLines must be a positive safe integer; received ${i}`);let o=j(e,t);if(o.length===0||n<0||n>=o.length)return null;let s=Math.min(o.length-1,r,n+i-1);return{relativePath:t,startLine:n,endLine:s,focusLine:n,source:o.slice(n,s+1).join(`
|
|
8
|
+
`)}}function Ln(e,t,n,r,i=6){if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`maxLines must be a positive safe integer; received ${r}`);let o=j(e,t);if(o.length===0||n<0||n>=o.length)return null;let s=si(e,t,n);if(!s){let g=Ba(e,t,n,i);return g?{...g,unitType:null,unitStartLine:g.startLine,unitEndLine:g.endLine,omittedLines:0}:null}let a=s.startLine,c=s.endLine,l=c-a+1,u=Math.min(l,r),d=n-a-Math.floor(u/2),m=Math.max(0,Math.min(l-u,d)),p=a+m,f=p+u-1;return{relativePath:t,startLine:p,endLine:f,focusLine:n,source:o.slice(p,f+1).join(`
|
|
9
|
+
`),unitType:s.type,unitStartLine:a,unitEndLine:c,omittedLines:l-u}}function DL(e,t,n){let r=[];return Ah(e,t,n,r),r.filter(i=>!r.some(o=>o!==i&&o.startIndex>=i.startIndex&&o.endIndex<=i.endIndex))}function Ah(e,t,n,r){if(kL(e,t)){ML.has(e.type)&&FL(e)===n&&r.push(e);for(let i of e.namedChildren)Ah(i,t,n,r)}}function FL(e){let t=e.childForFieldName("function")??e.childForFieldName("constructor")??e.childForFieldName("method")??e.childForFieldName("name")??e.namedChild(0);return t?t.text.match(/[\p{L}_$][\p{L}\p{N}_$!?-]*/gu)?.at(-1)??null:null}function kL(e,t){return e.startPosition.row<=t&&e.endPosition.row>=t}function Bh(e,t,n={}){let{context:r=0}=n,i=Jh(t);if(i)return Yh(e,i.filePath,i.startLine,i.endLine,r);let o=Wh(e,t);if(o)return qh(e,o);if(Kh(t))return null;let s=J(e,t);if(s.candidates.length>0)throw new Error(`Ambiguous symbol: ${t}. Use an exact selector or codeBatch.`);return s.match?Lo(e,s.match,r):null}function ase(e,t,n={}){if(t.length===0)throw new RangeError("code requires at least one selector.");if(t.length>24)throw new RangeError(`code accepts at most ${24} selectors per complete packet; received ${t.length}.`);let r=n.context??0,i=n.members??"exported",o=t.map(c=>AL(e,c,r,i,n.localCalls??!1)),s=o.flatMap(c=>c.results),a=s.map(c=>({relativePath:c.relativePath,startLine:c.startLine,endLine:c.endLine}));return{requested:t.length,matched:o.filter(c=>c.status==="matched").length,ambiguous:o.filter(c=>c.status==="ambiguous").length,missing:o.filter(c=>c.status==="missing").length,entries:o,bindingClosure:Ta(s.map(c=>c.bindingClosure),a)}}function AL(e,t,n,r,i){let o=Jh(t);if(o){let l=Yh(e,o.filePath,o.startLine,o.endLine,n);return l?i?OL(e,t,l,n):_h(t,l):$a(e,t,"definition-source-unreadable")}let s=Wh(e,t);if(s)return HL(e,t,s,n,r);if(Kh(t))return $a(e,t,"definition-not-found");let a=J(e,t);if(!a.match)return $a(e,t,"definition-not-found");if(a.total>1)return _L(e,t,a,n);let c=Lo(e,a.match,n);return c?_h(t,c):$a(e,t,it(e,a.match.relativePath)?.freshness.semantic.state==="stale"?"definition-index-stale":"definition-source-unreadable")}function _L(e,t,n,r){let i=JL(e,n),o=i.map(Vh),s=n.total<=4&&i.length===n.total;return{selector:t,status:"ambiguous",kind:"source",totalCandidates:n.total,results:s?i.flatMap(a=>{let c=Lo(e,a,r);return c?[c]:[]}):[],definitions:[],candidates:o,omittedCandidates:Math.max(0,n.total-o.length),suggestions:[]}}function OL(e,t,n,r){let i=D(e,n.relativePath).filter(l=>!$h(l,n.relativePath)),o=BL(e,n,i),s=Uh(o.map(l=>Lo(e,l,r)).filter(l=>l!==null)).filter(l=>!Gh(n,l)),a=new Set(s.map(l=>l.symbol)),c=o.filter(l=>!a.has(l.symbol)&&!(n.startLine<=l.startLine&&n.endLine>=l.endLine)).map(Vh);return{selector:t,status:"matched",kind:"source",totalCandidates:1,results:[n,...s],definitions:[],candidates:[],omittedCandidates:0,suggestions:[],rangeCoverage:{basis:"requested-range-and-same-file-call-closure",referencedDefinitions:o.length,returnedDefinitions:o.length-c.length,returnedBodies:s.length,omittedDefinitions:c.length,omittedLedger:c}}}function BL(e,t,n){if(!ai(t.freshness))return[];if(n.length===0)return[];let r=fo(e,n,{additive:!1,semantic:!1}),i=new Map;for(let s of n){let a=i.get(s.symbol)??[];a.push(s),i.set(s.symbol,a)}let o=$L(t,n,r,i);return Hh(e,[...o.values()],n)}function $L(e,t,n,r){let i=new Map;for(let o of t)if(!(o.endLine<e.startLine||o.startLine>e.endLine)){for(let s of n.get(o.symbolId)??[])if(jL(s,e))for(let a of r.get(s.symbol)??[])i.set(a.symbolId,a)}return i}function jL(e,t){return e.file!==t.relativePath?!1:e.source!=="ast-callsite"&&e.source!=="scip-occurrence"?!0:!(e.chunkId<t.startLine||e.chunkId>t.endLine)}function HL(e,t,n,r,i){let o=n.relativePath,s=ai(n.freshness)?qL(e,o):[],a=ai(n.freshness)?D(e,o).filter(g=>!$h(g,o)):[],c=a.filter(g=>Pt(e,g)),l=c.length>0?c:UL(s,a),u=i==="all"?[]:Hh(e,l,a),d=i==="all"||a.length===0?[qh(e,n)]:Uh(u.map(g=>Lo(e,g,r)).filter(g=>g!==null)),m=GL(s,d),p=KL(o,s,d),f=WL(s);return{selector:t,status:"matched",kind:"file-source",totalCandidates:1,results:d,definitions:[],candidates:[],omittedCandidates:0,suggestions:[],fileCoverage:{members:i,basis:i==="all"||a.length===0?"complete-file-source":c.length>0?"explicit-exports-and-same-file-reference-closure":"top-level-and-same-file-reference-closure",totalDefinitions:f,returnedDefinitions:m,returnedBodies:d.length,omittedDefinitions:Math.max(0,f-m),omittedLedger:p}}}function UL(e,t){let n=new Set(e.map(r=>r.symbol));return t.filter(r=>n.has(r.symbol))}function qL(e,t){return mh(e,t).flatMap(n=>zL(n,t)?n.children:[n])}function $h(e,t){return jh(t).has(e.leaf)}function zL(e,t){return jh(t).has(A(e.symbol))}function jh(e){let t=NL(e);return new Set([t,t.slice(0,Math.max(0,t.length-Oh(t).length))])}function Hh(e,t,n){if(t.length===0)return[];let r=fo(e,n,{additive:!0,semantic:!1}),i=XL(n),o=new Map,s=[...t];for(;s.length>0;){let a=s.shift();if(!o.has(a.symbolId)){o.set(a.symbolId,a);for(let c of r.get(a.symbolId)??[])for(let l of i.get(c.symbol)??[])o.has(l.symbolId)||s.push(l)}}return[...o.values()].sort(VL)}function Uh(e){let t=[...e].sort((r,i)=>r.relativePath.localeCompare(i.relativePath)||r.startLine-i.startLine||i.endLine-r.endLine),n=[];for(let r of t)n.some(i=>Gh(i,r))||n.push(r);return n}function qh(e,t){let n=t.text.split(`
|
|
10
|
+
`);return{symbol:t.relativePath,shortName:t.relativePath,relativePath:t.relativePath,startLine:0,endLine:Math.max(0,n.length-1),language:e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath)?.language??Ou(t.relativePath),source:t.text,freshness:t.freshness,...ai(t.freshness)?{bindingClosure:ii(e,t.relativePath,0,Math.max(0,n.length-1))}:{}}}function GL(e,t){return ja(e).filter(n=>t.some(r=>_u(n,r))).length}function KL(e,t,n){let r=[];return zh(r,e,t,n,0),r}function zh(e,t,n,r,i){for(let o of n){if(r.some(a=>_u(o,a)))continue;let s=ja(o.children).filter(a=>!r.some(c=>_u(a,c))).length;e.push({symbol:o.symbol,shortName:o.shortName,relativePath:t,startLine:o.startLine,endLine:o.endLine,signature:o.signature,depth:i,nestedDefinitions:s}),zh(e,t,o.children,r,i+1)}}function ja(e){return e.flatMap(t=>[t,...ja(t.children)])}function WL(e){return ja(e).length}function _u(e,t){return t.startLine<=e.startLine&&t.endLine>=e.endLine}function Gh(e,t){return e.relativePath===t.relativePath&&e.startLine<=t.startLine&&e.endLine>=t.endLine}function VL(e,t){return e.startLine-t.startLine||t.endLine-e.endLine||e.symbol.localeCompare(t.symbol)}function _h(e,t){return{selector:e,status:"matched",kind:"source",totalCandidates:1,results:[t],definitions:[],candidates:[],omittedCandidates:0,suggestions:[]}}function $a(e,t,n){return{selector:t,status:"missing",kind:"source",totalCandidates:0,results:[],definitions:[],candidates:[],omittedCandidates:0,suggestions:ua(e,t,5),reason:n}}function Kh(e){return/^\S+ \S+ \S+ \S+ /.test(e)?!1:/^(?:\.{1,2}[/\\]|[/\\]|[A-Za-z]:[/\\])/.test(e)?!0:e.includes(":")?!1:/[/\\]/.test(e)?!0:/\.(?:[cm]?[jt]sx?|jsonc?|mdx?|ya?ml|toml|xml|html|css|scss|sql|py|rs|go|java|kt|clj[cs]?|txt|sh)$/i.test(e)}function Wh(e,t){try{return it(e,t)}catch(n){if(n instanceof Pf)return null;throw n}}function JL(e,t){if(!t.match)return[];let n=[t.match];for(let i of t.candidates){let o=D(e,i.relativePath).find(s=>s.symbol===i.symbol&&s.startLine===i.startLine);o&&n.push(o)}let r=new Set;return n.filter(i=>{let o=`${i.relativePath}:${i.startLine}:${i.endLine}:${i.symbol}`;return r.has(o)?!1:(r.add(o),!0)})}function Vh(e){return{symbol:e.symbol,shortName:L(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function Jh(e){let t=e.match(/^(.+):(\d+)-(\d+)$/);if(!t)return null;let n=Number(t[2]),r=Number(t[3]);if(!Number.isSafeInteger(n)||n<1)throw new RangeError(`Source range start line must be a positive integer, got "${t[2]}".`);if(!Number.isSafeInteger(r)||r<n)throw new RangeError(`Source range end line must be an integer at or after ${n}, got "${t[3]}".`);return{filePath:t[1],startLine:n,endLine:r}}function Lo(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=it(e,t.relativePath);if(!i||i.freshness.semantic.state==="stale")return null;let s=i.text.split(`
|
|
11
|
+
`),a=t.endLine<=t.startLine?Ln(e,t.relativePath,t.startLine,Number.MAX_SAFE_INTEGER):null,[c,l]=a?.unitType?[a.unitStartLine,a.unitEndLine]:[t.startLine,t.endLine];if(c<0||c>=s.length||l<c)return null;let u=Math.max(0,c-n),d=Math.min(s.length-1,l+n),m=s.slice(u,d+1).join(`
|
|
12
|
+
`);return{symbol:t.symbol,shortName:L(t.symbol),relativePath:t.relativePath,startLine:u,endLine:d,language:r?.language??Ou(t.relativePath),source:m,freshness:i.freshness,...ai(i.freshness)?{bindingClosure:ii(e,t.relativePath,u,d)}:{}}}function Yh(e,t,n,r,i){let o=it(e,t);if(!o)return null;let s=e.get("SELECT language FROM documents WHERE relative_path = ?",o.relativePath),c=o.text.split(`
|
|
13
|
+
`);if(n>c.length)return null;let l=Math.max(0,n-1-i),u=Math.min(c.length-1,r-1+i),d=c.slice(l,u+1).join(`
|
|
14
|
+
`);return{symbol:`${o.relativePath}:${n}-${r}`,shortName:`${o.relativePath}:${n}-${r}`,relativePath:o.relativePath,startLine:l,endLine:u,language:s?.language??Ou(o.relativePath),source:d,freshness:o.freshness,...ai(o.freshness)?{bindingClosure:ii(e,o.relativePath,l,u)}:{}}}function ai(e){return!!(e&&e.semantic.state!=="stale"&&e.semantic.basis!=="no-compiler-document")}var YL=new Map([[".ts","typescript"],[".tsx","typescript"],[".mts","typescript"],[".cts","typescript"],[".js","javascript"],[".jsx","javascript"],[".mjs","javascript"],[".cjs","javascript"],[".py","python"],[".pyi","python"],[".rs","rust"],[".go","go"],[".java","java"],[".kt","kotlin"],[".kts","kotlin"],[".scala","scala"],[".rb","ruby"],[".php","php"],[".cs","csharp"],[".vb","vb"],[".dart","dart"],[".c","c"],[".h","c"],[".cc","cpp"],[".cpp","cpp"],[".cxx","cpp"],[".hpp","cpp"],[".hh","cpp"],[".hxx","cpp"],[".vue","vue"]]);function Ou(e){return YL.get(Oh(e).toLowerCase())??null}function XL(e){let t=new Map;for(let n of e){let r=t.get(n.symbol)??[];r.push(n),t.set(n.symbol,r)}return t}function Ha(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 Xh(e){let t=new Map,n=ZL(e),r=new Map;return i=>{let o=QL(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=eM(D(e,i.file)),t.set(i.file,a));let c=tM(a,i);return r.set(o,c),c}}function QL(e){return`${e.file}\0${e.symbol}\0${e.line}`}function ZL(e){return new Set(e.all("SELECT relative_path FROM documents").map(t=>t.relative_path))}function eM(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 tM(e,t){if(e.definitions.length===0)return t.symbol;let n=iM(t.symbol),r=nM(e.byLeaf,n),i=rM(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 nM(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 rM(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 iM(e){let t=new Set([e]),r=e.split(/::|\.|#/).filter(Boolean).at(-1);return r&&t.add(r),t}function Qh(e,t){let r=V(e,t).map(i=>sM(t,i));return{usage:r,positions:aM(e,t,r)}}function Zh(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?oM(r.usage,i.sourcePaths):r.usage}}}function oM(e,t){return e.map((n,r)=>{let i=t.get(String(r));return i?{...n,sourcePath:i}:n})}function sM(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 aM(e,t,n){let r=_(e,t);if(!r)return[];let i=cM(r.rootNode),o=new Map;for(let a of i){let c=o.get(Bu(a.importedName,a.localName));c?c.push(a.position):o.set(Bu(a.importedName,a.localName),[a.position])}let s=[];return n.forEach((a,c)=>{let l=o.get(Bu(a.importedName,a.localName??a.importedName))?.shift();l&&s.push({...l,id:String(c),file:t})}),s}function cM(e){let t=[];for(let n of e.descendantsOfType("use_declaration")){let r=n.namedChildren.find(i=>i.type!=="visibility_modifier");r&&t.push(...Ua(r,""))}return t.filter(n=>n.importedName!=="*")}function Ua(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":return[{importedName:e.text,localName:e.text,position:$u(e,e.text)}];case"scoped_identifier":return lM(e);case"scoped_use_list":return uM(e,t);case"use_list":return e.namedChildren.flatMap(n=>Ua(n,t));case"use_as_clause":return dM(e,t);case"use_wildcard":return mM(e);default:return[]}}function lM(e){let t=e.text.split("::").pop()??e.text;return[{importedName:t,localName:t,position:$u(e,t)}]}function uM(e,t){let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=lg(t,n.text);return r.namedChildren.flatMap(o=>Ua(o,i))}function dM(e,t){let n=e.namedChild(0),r=e.namedChild(1);return!n||!r?[]:Ua(n,t).map(i=>({...i,localName:r.text}))}function mM(e){let t=e.namedChild(0),n="*";return[{importedName:n,localName:n,position:$u(t??e,n)}]}function $u(e,t){let n=Math.max(0,e.text.lastIndexOf(t));return{id:"",file:"",line:e.startPosition.row,column:e.startPosition.column+n+pM(t)}}function pM(e){return Math.max(0,Math.min(e.length-1,1))}function Bu(e,t){return`${e}\0${t}`}import{spawnSync as Xu}from"child_process";import{existsSync as Qu}from"fs";import{fileURLToPath as wD}from"url";function Dn(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function qa(e){let t=Og(_g,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 uD,mkdtempSync as xy,rmSync as Gu}from"fs";import{tmpdir as Wu}from"os";import{join as Ku}from"path";import{fileURLToPath as _o,pathToFileURL as dD}from"url";import{SHARE_ENV as mD,Worker as pD}from"worker_threads";function Fn(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 cr(e,t,n){let r=Dn(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 BM}from"child_process";import{createHash as $M,randomUUID as jM}from"crypto";import{existsSync as fy,realpathSync as HM,rmSync as UM}from"fs";import{tmpdir as qM}from"os";import{resolve as li}from"path";import{execFileSync as xM}from"child_process";import{existsSync as fM}from"fs";import{deserializeSCIP as gM,SymbolRole as hM}from"@c4312/scip";import{realpathSync as xse}from"fs";import{basename as Ese,dirname as Ise,join as wse,relative as Pse,sep as Tse}from"path";import{fileURLToPath as Mse,pathToFileURL as Dse}from"url";function za(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 ju=new WeakMap,yM="SCIP_RUST_SCIP_OCCURRENCE_REFERENCE_MODE";function ey(e,t){let n=new Map,r=Ga(),i=t.filter(s=>ry(s,r));if(i.length===0)return n;let o=iy(e);if(!o)return n;for(let s of i){let a=ny(o,s);a!==null&&n.set(s.symbolId,a)}return n}function ty(e,t){if(!ry(t,Ga()))return null;let n=iy(e);return n?ny(n,t):null}function ny(e,t){return e.referencesBySymbol.get(t.symbol)??[]}function ry(e,t="safe"){if(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||ke(e.symbol)||/impl#\[[^\]]+\]\[Default\]default\(\)\.$/.test(e.symbol))return!1;if(t==="all")return!0;let n=vt(e.symbol);if(n==="method")return!0;if(n!=="term")return!1;let r=Jr(e.symbol);return"kind"in r?!1:!bM(r)}function bM(e){for(let t=0;t<e.descriptors.length-1;t+=1)if(e.descriptors[t]?.suffix==="type")return!0;return!1}function iy(e){if(ju.has(e))return ju.get(e)??null;let t=SM(e);return ju.set(e,t),t}function SM(e){if(!e.generation.indexPath||!fM(e.generation.indexPath))return null;try{let t=gM(Ws(e.generation.indexPath,{inputKind:"SCIP occurrence-reference index",maxBytes:Ks})),n=new Map;for(let r of t.documents??[]){let i=r.relativePath;!i||e.isIgnored(i)||CM(r,i,n)}for(let[r,i]of n)n.set(r,za(i));return{referencesBySymbol:n}}catch{return null}}function vM(e,t){if(t.length<3)return null;let n=t[0],r=t[1];return!Number.isInteger(n)||!Number.isInteger(r)?null:{file:e,line:n,column:r}}function Ga(){return process.env[yM]==="all"?"all":"safe"}function CM(e,t,n){for(let r of e.occurrences??[]){if(!r.symbol||(r.symbolRoles&hM.Definition)!==0)continue;let i=vM(t,r.range);if(!i)continue;let o=n.get(r.symbol)??[];o.push(i),n.set(r.symbol,o)}}var oy=new Map;function Hu(e){let n=qa(e).resolvedBinary??null;return{engine:"rust-analyzer",resolvedBinary:n,version:n?RM(e,n):"unavailable"}}function lr(e){return{...Hu(e),scipOccurrenceReferenceMode:Ga()}}function RM(e,t){let n=`${e}\0${t}`,r=oy.get(n);if(r)return r;let i;try{i=xM(t,["--version"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim()}catch{i="unknown"}return oy.set(n,i),i}import{createHash as EM}from"crypto";var IM=new Set(["Cargo.lock","Cargo.toml","rust-project.json","rust-toolchain","rust-toolchain.toml"]);function sy(e){let t=$f(e,{includePath:wM});return EM("sha256").update(JSON.stringify(t)).digest("hex")}function wM(e){let t=e.replaceAll("\\","/"),n=t.split("/").at(-1)??t;return t.endsWith(".rs")||IM.has(n)?!0:t===".cargo/config"||t===".cargo/config.toml"||t.endsWith("/.cargo/config")||t.endsWith("/.cargo/config.toml")}import{createHash as PM}from"crypto";import{resolve as TM}from"path";var ci=3;function qu(e){return PM("sha256").update(or({kind:"scip-query-durable-rust-mailbox",protocolVersion:ci,sessionDir:TM(e)})).digest("hex")}function LM(e,t){return e.mailboxVersion===cn&&e.id===t.requestId&&e.operationKey===t.operationKey&&e.sessionIdentity===t.sessionIdentity&&e.deadlineAtMs===t.deadlineAtMs}function MM(e,t){return typeof e.completedAtMs=="number"&&Number.isFinite(e.completedAtMs)&&!(e.completedAtMs>t.deadlineAtMs)&&!(t.nowMs>t.deadlineAtMs)}function DM(e,t){return e.ok===!1?typeof e.error!="string"||!OM(e.errorCode)?Uu("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"||!FM(e.response,t)?Uu("helper wrote an invalid success response"):{ok:!0,session:e.session,response:e.response}}function ly(e,t){return k(e)?e.protocolVersion!==ci?cy(e.protocolVersion===void 0?"helper wrote a prior uncorrelated response protocol":`helper wrote unsupported response protocol ${String(e.protocolVersion)}`):LM(e,t)?MM(e,t)?DM(e,t.requestKind):{ok:!1,code:"expired-request",error:"helper response arrived after the durable request deadline"}:cy("helper wrote an incompatible response identity"):Uu("helper wrote an invalid response object")}function FM(e,t){return!k(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"?kM(e):NM(e)}function kM(e){return Array.isArray(e.sourcePaths)&&e.sourcePaths.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string"&&(t[1]===null||typeof t[1]=="string"))}function NM(e){return ay(e.references,AM)&&(e.incompleteReferenceSymbolIds===void 0||Array.isArray(e.incompleteReferenceSymbolIds)&&e.incompleteReferenceSymbolIds.every(t=>Number.isSafeInteger(t)))&&(e.callees===void 0||ay(e.callees,_M))&&(e.signatures===void 0||Array.isArray(e.signatures)&&e.signatures.every(t=>Array.isArray(t)&&t.length===2&&Number.isSafeInteger(t[0])&&(t[1]===null||typeof t[1]=="string")))}function ay(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 AM(e){return k(e)&&typeof e.file=="string"&&yt(e.line)&&yt(e.column)}function _M(e){return k(e)&&typeof e.symbol=="string"&&typeof e.file=="string"&&yt(e.line)&&(e.callsiteLine===void 0||yt(e.callsiteLine))}function OM(e){return e==="unsupported-protocol"||e==="malformed-request"||e==="expired-request"||e==="handler-error"}function Uu(e){return{ok:!1,code:"malformed-response",error:e}}function cy(e){return{ok:!1,code:"incompatible-response",error:e}}var zM=5e3,gy=10,GM=3e4;function uy(e,t,n,r=Sy){let i=r.engineIdentity(e),o={protocolVersion:ci,projectRoot:r.canonicalProjectRoot(e),projectFingerprint:r.projectFingerprint(e),engine:{engine:i.engine,resolvedBinary:i.resolvedBinary,version:i.version},workerFingerprint:r.fileFingerprint(t),environment:hy(r.environment())};return{key:vy(or(o)),...o}}function Mo(e,t,n,r){if(e.protocolVersion!==ci||!n(e.pid))return!1;if(!e.processIdentity)return!0;let i=r?.(e.pid);return i!=null&&ya(e.processIdentity,i)}function zu(e,t,n){let r;try{r=Yl(t,{maxBytes:rn,inputKind:"Rust semantic engine artifact"})}catch{r="missing"}let i=vy(or({projectRoot:li(e),serverPath:li(t),serverFingerprint:r})).slice(0,20);return li(n,`scip-query-rust-session-${i}`)}function dy(e){let t=e===void 0?Number.NaN:Number(e);return Number.isInteger(t)&&t>=0?t:0}function hy(e){return Object.fromEntries(Object.entries(e).filter(([t])=>by(t)).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,n??null]))}function yy(e,t){let n=t.runtime??tD,r=t.identityRuntime??Sy,i=zu(e,t.serverPath,t.tempRoot??qM()),o=!1,s=(a,c)=>{if(o)throw new Error("Durable Rust semantic session was already disposed.");return WM(i,t.serverPath,t.semanticWorkerPath,a,c,n,t.mailboxLimits)};return{requestSemantic(a,c){let l=uy(e,t.semanticWorkerPath,a,r),{readinessDeadlineMs:u,...d}=a;return s({kind:"semantic",identityKey:l.key,workerEnvironment:py(),request:{...d,referenceRetryTimeoutMs:KM(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,a.referenceRetryTimeoutMs),settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:dy(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},requestImportDefinitions(a,c){let l=uy(e,t.semanticWorkerPath,a,r),{readinessDeadlineMs:u,...d}=a;return s({kind:"import-definitions",identityKey:l.key,workerEnvironment:py(),request:{...d,settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:dy(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},shutdown(){o=!0}}}function KM(e,t){return t!==void 0?t:e===void 0?GM:void 0}function WM(e,t,n,r,i,o,s={}){let a=o.now(),c=a+i,l=(o.monotonicNow??Ct)(),u=l+i,d=Tn("rust-semantic-v3",r),m=sr(d),p=ba(e),f=qu(e),g=Sa(p,{mailboxVersion:cn,protocolVersion:ci,id:m,operationKey:d,clientId:o.randomId(),enqueuedAtMs:a,deadlineAtMs:c,sessionIdentity:f,request:r},{nowMs:a,limits:s});for(my(e,t,n,u,o);(o.monotonicNow??Ct)()<=u;){if(fy(g.responsePath)){let y=QM(ht(g.responsePath,{maxBytes:s.maxItemBytes??rn,inputKind:"durable Rust semantic mailbox response"}),{requestId:m,operationKey:d,sessionIdentity:f,deadlineAtMs:g.authoritativeDeadlineAtMs,requestKind:r.kind,nowMs:o.now()});if(!y.ok)throw new Error(y.error);return rD(o,l,y.session,r.kind),y.response}let h=Do(e);(!h||!Mo(h,o.now(),o.isProcessAlive,o.readProcessIdentity))&&my(e,t,n,u,o),o.sleep(gy)}throw new Error(`Durable Rust semantic session timed out after ${(i/1e3).toFixed(0)}s.`)}function my(e,t,n,r,i){let o=Do(e);if(o&&Mo(o,i.now(),i.isProcessAlive,i.readProcessIdentity))return;UM(li(e,"server.json"),{force:!0}),i.spawnServer(t,e,n);let s=i.monotonicNow??Ct,a=Math.min(r,s()+zM);for(;s()<=a;){let c=Do(e);if(c&&Mo(c,i.now(),i.isProcessAlive,i.readProcessIdentity))return;i.sleep(gy)}throw new Error("Durable Rust semantic session helper did not become ready within 5s.")}function VM(e,t){return typeof e.protocolVersion=="number"&&JM(e,t)&&typeof e.pid=="number"&&typeof e.heartbeatAtMs=="number"}function JM(e,t){return e.sessionIdentity===void 0||typeof e.sessionIdentity=="string"&&e.sessionIdentity===qu(t)}function YM(e){return(e.busyUntilMs===void 0||typeof e.busyUntilMs=="number")&&(e.mailbox===void 0||ZM(e.mailbox))}function XM(e,t){return{protocolVersion:e.protocolVersion,...e.sessionIdentity===void 0?{}:{sessionIdentity:e.sessionIdentity},pid:e.pid,...t?{processIdentity:t}:{},heartbeatAtMs:e.heartbeatAtMs,...e.busyUntilMs===void 0?{}:{busyUntilMs:e.busyUntilMs},...e.mailbox===void 0?{}:{mailbox:e.mailbox}}}function Do(e){try{let t=JSON.parse(ht(li(e,"server.json"),{maxBytes:Gs,inputKind:"durable Rust session state"}));if(!VM(t,e)||!YM(t))return null;let n=t.processIdentity===void 0?null:ha(t.processIdentity);return t.processIdentity!==void 0&&(!n||n.pid!==t.pid)?null:XM(t,n)}catch{return null}}function QM(e,t){try{return ly(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 ZM(e){if(!e||typeof e!="object")return!1;let t=e;return nD(t)&&typeof t.totalBytes=="number"&&Number.isFinite(t.totalBytes)&&t.totalBytes>=0&&(t.oldestPendingAt===void 0||Number.isFinite(Date.parse(t.oldestPendingAt)))}function py(){return Object.fromEntries(Object.entries(process.env).filter(([e])=>eD(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t??null]))}function by(e){return e==="HOME"||e==="PATH"||e.startsWith("CARGO_")||e.startsWith("RA_")||e.startsWith("RUST")}function eD(e){return by(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 Sy={canonicalProjectRoot(e){try{return HM(e)}catch{return li(e)}},projectFingerprint(e){return sy(e)},engineIdentity:Hu,fileFingerprint(e){return Yl(e,{maxBytes:rn,inputKind:"Rust semantic engine artifact"})},environment(){return hy(process.env)}},tD={now:Date.now,monotonicNow:Ct,randomId:jM,isProcessAlive:ni,readProcessIdentity:ri,spawnServer(e,t,n){if(!fy(e))throw new Error(`Durable Rust semantic session helper was not found at ${e}. Run npm run build first.`);BM(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 vy(e){return $M("sha256").update(e).digest("hex")}function nD(e){return yt(e.pending)&&yt(e.inflight)&&yt(e.responses)&&yt(e.deadLetters)&&yt(e.invalid)&&yt(e.totalItems)}function rD(e,t,n,r){fe()&&Ys({type:"span",name:"rust.semantic.durable-session.request",durationMs:(e.monotonicNow??Ct)()-t,ok:!0,session:n,kind:r})}import{randomUUID as bae}from"crypto";import{readdirSync as iD,rmSync as vae,writeFileSync as Cae}from"fs";import{join as oD}from"path";var sD="rust-analyzer-owner-",aD=".json",cD=16*1024;async function Cy(e,t){if(!e)return[];let n;try{n=iD(e)}catch{return[]}let r=n.filter(s=>s.startsWith(sD)&&s.endsWith(aD)).map(s=>oD(e,s)),i=[],o=[];for(let s of r){let a=lD(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=>Hg(s,t)))),i}function lD(e){try{let t=ht(e,{maxBytes:cD,inputKind:"rust-analyzer process ownership record"}),n=JSON.parse(t),r=ha(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 Ry=15e3,Ey=8,wy=5e3,fD=64,gD=96,Vu=class{constructor(t,n,r={}){this.projectRoot=t;this.status=n;this.opts=r;this.requester=r.requester??bD(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:ko(n),references:No(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!0});return{...Fo(r),resolvedBinary:n.resolvedBinary,references:Fn(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:No(t)}}}calleesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:ko(n),callees:Ao(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!0});return{...Fo(r),resolvedBinary:n.resolvedBinary,callees:Ju(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:Ao(t)}}}referencesAndCalleesForDefinitions(t,n){let r=this.status(this.projectRoot);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:ko(r),references:No(t),callees:Ao(n)};let i=[...t,...n];try{let o=this.requestSession(r.resolvedBinary,i,{includeReferences:t.length>0,includeCallees:n.length>0,referenceDefinitions:t,calleeDefinitions:n});return{...Fo(o),resolvedBinary:r.resolvedBinary,references:Fn(t,new Map(o.references),new Set(o.incompleteReferenceSymbolIds??[])),callees:Ju(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:ko(n),signatures:Iy(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!1,includeSignatures:!0});return{...Fo(r),resolvedBinary:n.resolvedBinary,signatures:RD(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:Iy(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:ko(r),sourcePaths:new Map(n.map(i=>[i.id,null]))};try{let i=this.requestImportDefinitions(r.resolvedBinary,t,n);return{...Fo(i),resolvedBinary:r.resolvedBinary,sourcePaths:new Map(i.sourcePaths)}}catch(i){return{available:!1,resolvedBinary:r.resolvedBinary,reason:i instanceof Error?i.message:String(i),sourcePaths:new Map(n.map(o=>[o.id,null]))}}}dispose(){this.requester.shutdown()}requestSession(t,n,r){let i=Ka(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Ry),o=Wa(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),s=Ka(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Ey),a=Wa(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=Oo(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,...r}),m={projectRoot:this.projectRoot,rustAnalyzerBinary:t,definitions:[...n],...c?{referenceDefinitions:c}:{},...l?{calleeDefinitions:l}:{},...u?{signatureDefinitions:u}:{},requestTimeoutMs:i,...r.includeReferences!==!1&&o>0?{referenceRetryTimeoutMs:o}:{},diagnosticsTimeoutMs:a,settleDelayMs:d,concurrency:s,includeReferences:r.includeReferences,includeCallees:r.includeCallees,includeSignatures:r.includeSignatures},p=ED(m);return M("rust.semantic.session.request",()=>this.requester.requestSemantic(m,cr(p,Yu(i,m.referenceRetryTimeoutMs),s)),()=>({definitions:n.length,operationDefinitions:p,referenceDefinitions:m.referenceDefinitions?.length,calleeDefinitions:m.calleeDefinitions?.length,signatureDefinitions:m.signatureDefinitions?.length,references:m.includeReferences!==!1,callees:m.includeCallees===!0,signatures:m.includeSignatures===!0,referenceRetryTimeoutMs:m.referenceRetryTimeoutMs}))}fallbackReferencesAndCallees(t,n,r,i){let o=n.length===0?{available:!0,resolvedBinary:t.resolvedBinary,references:No(n)}:this.opts.fallbackReferenceResolver?.referencesForDefinitions(n),s=r.length===0?{available:!0,resolvedBinary:t.resolvedBinary,callees:Ao(r)}:this.opts.fallbackCalleeResolver?.calleesForDefinitions(r);return o&&s?ID(t,n,r,o,s):{available:!1,resolvedBinary:t.resolvedBinary,reason:i instanceof Error?i.message:String(i),references:No(n),callees:Ao(r)}}requestImportDefinitions(t,n,r){let i=Ka(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Ry),o=Ka(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,Ey),s=Wa(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),a=Wa(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,wy),c={projectRoot:this.projectRoot,rustAnalyzerBinary:t,file:n,positions:[...r],requestTimeoutMs:i,diagnosticsTimeoutMs:s,settleDelayMs:a,concurrency:o};return M("rust.semantic.import-definitions.session.request",()=>this.requester.requestImportDefinitions(c,cr(r.length,i,o)),()=>({file:n,positions:r.length}))}};function Fo(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function ko(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function Py(e,t,n={}){return new Vu(e,t,n)}function Oo(e,t){let n=Dy(e);if(n!==null)return n;let r=t.includeReferences!==!1;return r&&t.includeCallees!==!0&&t.includeSignatures!==!0&&t.definitionCount<=fD||r&&t.includeCallees===!0&&t.includeSignatures!==!0&&t.definitionCount<=gD?0:wy}function Ty(e){let t=e?.trim().toLowerCase(),n=["0","false","off","worker"].includes(t??""),r=["1","true","on","durable"].includes(t??""),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 hD(e){return Ty(e).transport}function jae(e,t){let n=Ty(t);if(n.transport==="worker")return{...n,state:"per-command"};let r=_o(My()),i=zu(e,r,Wu()),o=Do(i);return o?{...n,state:Mo(o,Date.now(),ni,ri)?"live":"stale",pid:o.pid,heartbeatAtMs:o.heartbeatAtMs,...o.busyUntilMs===void 0?{}:{busyUntilMs:o.busyUntilMs}}:{...n,state:"stopped"}}function yD(e,t){let n=null,r=!1,i=!1,o=!1,s=()=>n??=t(),a=()=>{i||(e.shutdown(),i=!0)},c=(u,d,m)=>{let p=xD(u);r=!0;try{a()}catch{}fe()&&Ys({type:"span",name:"rust.semantic.durable-session.request",durationMs:m,ok:!1,kind:d,session:"worker-fallback",reason:p})},l=(u,d,m)=>{if(o)throw new Error("Rust semantic failover session was already disposed.");if(r)return m(s());let p=performance.now();try{return d(e)}catch(f){c(f,u,performance.now()-p)}return m(s())};return{requestSemantic(u,d){return l("semantic",m=>m.requestSemantic(u,d),m=>m.requestSemantic(u,d))},requestImportDefinitions(u,d){return l("import-definitions",m=>m.requestImportDefinitions(u,d),m=>m.requestImportDefinitions(u,d))},shutdown(){if(o)return;o=!0;let u=[];try{a()}catch(d){u.push(d)}try{n?.shutdown()}catch(d){u.push(d)}if(u.length>0)throw u[0]}}}function bD(e,t,n={worker:()=>SD(),durable:()=>yy(e,{serverPath:_o(My()),semanticWorkerPath:_o(Ly())})}){return hD(t)==="durable"?yD(n.durable(),n.worker):n.worker()}function SD(e={}){let t=null,n=null,r=1,i=!1,o=null,s=null,a=d=>{d&&Gu(d,{recursive:!0,force:!0})},c=()=>{if(o)return;let d=t,m=n;t=null,n=null;let p=d?d.terminate():Promise.resolve(0);o=Promise.allSettled([p,Cy(m,{gracefulMs:1e3,forceMs:1e3})]).then(([f,g])=>{let y=(g.status==="fulfilled"?g.value:[{reaped:!1,detail:String(g.reason)}]).filter(S=>!S.reaped);if(f.status==="rejected"||y.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?dD(e.semanticWorkerPath):Ly();if(!uD(_o(d)))throw new Error(`Rust semantic session worker was not found at ${_o(d)}. Run npm run build before using built semantic Rust queries.`);return n=xy(Ku(Wu(),"scip-query-rust-session-")),t=new pD(d,e.shareEnvironment?{env:mD}:void 0),t.unref(),t},u=()=>{let d=n??xy(Ku(Wu(),"scip-query-rust-session-"));return n=d,Ku(d,`${r++}.json`)};return{requestSemantic(d,m){if(i)throw new Error("Rust semantic session was already disposed.");let p=l(),f=u(),g=new SharedArrayBuffer(4),h=new Int32Array(g);if(p.postMessage({kind:"semantic",request:d,responsePath:f,sharedBuffer:g}),Atomics.wait(h,0,0,m)==="timed-out")throw c(),new Error(`Rust semantic session worker timed out after ${(m/1e3).toFixed(0)}s`);try{let S=vD(ht(f,{maxBytes:rn,inputKind:"Rust semantic worker response"}));if(!S.ok)throw new Error(S.error);return S.response}finally{Gu(f,{force:!0})}},requestImportDefinitions(d,m){if(i)throw new Error("Rust semantic session was already disposed.");let p=l(),f=u(),g=new SharedArrayBuffer(4),h=new Int32Array(g);if(p.postMessage({kind:"import-definitions",request:d,responsePath:f,sharedBuffer:g}),Atomics.wait(h,0,0,m)==="timed-out")throw c(),new Error(`Rust semantic import-definition session worker timed out after ${(m/1e3).toFixed(0)}s`);try{let S=CD(ht(f,{maxBytes:rn,inputKind:"Rust import-definition worker response"}));if(!S.ok)throw new Error(S.error);return S.response}finally{Gu(f,{force:!0})}},shutdown(){if(i)return;if(i=!0,!t){a(n),n=null;return}let d=u(),m=new SharedArrayBuffer(4),p=new Int32Array(m);t.postMessage({kind:"shutdown",responsePath:d,sharedBuffer:m}),Atomics.wait(p,0,0,5e3),c()}}}function vD(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 CD(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 xD(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 No(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Ao(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Iy(e){return new Map(e.map(t=>[t.symbolId,null]))}function Ju(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??[]]))}function RD(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function ED(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 Yu(e,t){return t&&t>0?Math.max(e,t):e}function Ly(){return new URL("./rust-semantic-session-worker.js",import.meta.url)}function My(){return new URL("./rust-semantic-session-server.js",import.meta.url)}function Ka(e,t){return Dn(e)??t}function Wa(e,t){return Dy(e)??t}function Dy(e){if(!e)return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null}function ID(e,t,n,r,i){let o={resolvedBinary:r.resolvedBinary??i.resolvedBinary??e.resolvedBinary,references:Fn(t,r.references),callees:Ju(n,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 fallback was unavailable.",...o}}var Zu=15e3,ed=8;function Ny(e,t={}){let n=t.status??qa,r=LD(e,n),i=MD(e,n),o=DD(e,n),s=_D(e,t,n,r,i,o),a=t.referenceResolver??s??r,c=t.calleeResolver??s??i,l=t.signatureResolver??s??o,u=OD(t,s),d=t.calleeSymbolResolver,m=t.sourceZeroCalleeOracle,p=t.scipOccurrenceCalleeOracle,f=new Map,g=new Map,h=null,y=null,S=()=>(h??=n(e),h),I=()=>{let C=S();return C.dependencyAvailable?y??C:C},x=C=>{if(C.length===0)return new Map;let R=$o(C);try{let P=a.referencesForDefinitions(R),w=S();return y=Va(w,P),P.available?new Map(P.references):Fn(R,P.references)}catch(P){let w=S();return y=Bo(w,P),ur(R)}},E=C=>{if(C.length===0)return new Map;let R=$o(C),P=R.filter(Fy);if(P.length===0)return dr(R);let w=new Map,T=ky(P,p),G=$D(P,g,T,m,w);if(G.length===0)return ui(R,w,void 0);try{let K=c.calleesForDefinitions(G),ue=S();y=Va(ue,K);let ce=ui(G,K.callees,d);for(let[Ce,pe]of ce)w.set(Ce,pe);return ui(R,w,void 0)}catch(K){let ue=S();return y=Bo(ue,K),dr(R)}},b=(C,R)=>{let P=$o(C),w=$o(R),T=w.filter(Fy),G=new Map,K=ky(T,p),ue=jD(T,K,m,G);if(P.length===0&&ue.length===0)return{references:ur(P),callees:ui(w,G,void 0)};try{let ce=s?s.referencesAndCalleesForDefinitions(P,ue):AD(a,c,{referenceDefinitions:P,calleeDefinitions:ue}),Ce=S();y=Va(Ce,ce);let pe=ce.available?new Map(ce.references):Fn(P,ce.references);for(let[$,U]of ce.callees)G.set($,U);let Je=ui(w,G,d);for(let[$,U]of Je)g.set($,U);return{references:pe,callees:Je}}catch(ce){let Ce=S();return y=Bo(Ce,ce),{references:ur(P),callees:dr(w)}}},v=C=>{if(C.length===0)return new Map;let R=$o(C);try{let P=l.signaturesForDefinitions(R),w=S();return y=Va(w,P),_y(R,P.signatures)}catch(P){let w=S();return y=Bo(w,P),Ja(R)}};return{language:"rust",availability:I,dispose:()=>{s?.dispose()},importUsage:C=>{let R=f.get(C);if(R)return R;try{let P=u.importUsage(C);return f.set(C,P),P}catch(P){let w=S();return y=Bo(w,P),[]}},referencesFor:C=>x([C]).get(C.symbolId)??[],referencesForDefinitions:x,referencesAndCalleesForDefinitions:b,calleesFor:C=>E([C]).get(C.symbolId)??[],calleesForDefinitions:E,signatureFor:C=>v([C]).get(C.symbolId)??null}}function Va(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 Bo(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 PD(e){if(e.usePersistentSession!==void 0)return e.usePersistentSession;let t=process.env.SCIP_RUST_SEMANTIC_SESSION;return t!=="0"&&t!=="false"}function TD(){return{importUsageFacts:()=>({usage:[],positions:[]})}}function $o(e){return e.map(t=>{let n=t;return{...t,leaf:typeof n.leaf=="string"?n.leaf:A(t.symbol),parentTypeName:n.parentTypeName??null,isFunctionLike:typeof n.isFunctionLike=="boolean"?n.isFunctionLike:be(t.symbol),isTypeLike:n.isTypeLike??!1,kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosingSymbol??null}})}function Fy(e){return e.isFunctionLike}function Ay(e,t){if(!t)return!1;try{return t(e)}catch{return!1}}function ky(e,t){if(!t||e.length===0)return new Map;try{return t(e)}catch{return new Map}}function LD(e,t){return{referencesForDefinitions:n=>FD(e,t,n)}}function MD(e,t){return{calleesForDefinitions:n=>kD(e,t,n)}}function DD(e,t){return{signaturesForDefinitions:n=>ND(e,t,n)}}function FD(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:rd(r),references:ur(n)};let i=td();if(!Qu(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:ur(n)};let o=di(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Zu),s=Ya(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),a=di(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,ed),c=Ya(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),l=Oo(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=Xu(process.execPath,[i],{cwd:e,input:JSON.stringify(u),encoding:"utf8",maxBuffer:50*1024*1024,timeout:cr(n.length,Yu(o,u.referenceRetryTimeoutMs),a)}),m=id(d.stdout);if(m)return{...nd(m),resolvedBinary:r.resolvedBinary,references:Fn(n,new Map(m.references),new Set(m.incompleteReferenceSymbolIds??[]))};let p=d.error instanceof Error?d.error.message:d.stderr.trim()||`Rust semantic worker exited with status ${d.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:p,references:ur(n)}}function kD(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:rd(r),callees:dr(n)};let i=td();if(!Qu(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:dr(n)};let o=di(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Zu),s=di(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,ed),a=Ya(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=Oo(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=Xu(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:cr(n.length,o,s)}),d=id(u.stdout);if(d)return{...nd(d),resolvedBinary:r.resolvedBinary,callees:ui(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:dr(n)}}function ND(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:rd(r),signatures:Ja(n)};let i=td();if(!Qu(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:Ja(n)};let o=di(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,Zu),s=di(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,ed),a=Ya(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=Oo(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=Xu(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:cr(n.length,o,s)}),d=id(u.stdout);if(d)return{...nd(d),resolvedBinary:r.resolvedBinary,signatures:_y(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:Ja(n)}}function AD(e,t,n){let r=n.referenceDefinitions.length>0?e.referencesForDefinitions(n.referenceDefinitions):{available:!0,references:ur(n.referenceDefinitions)},i=n.calleeDefinitions.length>0?t.calleesForDefinitions(n.calleeDefinitions):{available:!0,callees:dr(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 ur(e){return new Map(e.map(t=>[t.symbolId,[]]))}function dr(e){return new Map(e.map(t=>[t.symbolId,[]]))}function Ja(e){return new Map(e.map(t=>[t.symbolId,null]))}function ui(e,t,n){let r=0,i=0;return M("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 _y(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function td(){return wD(new URL("./rust-semantic-worker.js",import.meta.url))}function nd(e){return e.available?{available:!0}:{available:!1,reason:e.reason}}function rd(e){return e.available?"rust-analyzer binary path is unavailable.":e.reason}function id(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)||!HD(n))return null;let r=BD(n,n.references);return n.available===!0?{available:!0,...r}:{available:!1,reason:String(n.reason),...r}}catch{return null}}function di(e,t){return Dn(e)??t}function Ya(e,t){if(!e)return t;let n=Number(e);return Number.isInteger(n)&&n>=0?n:t}function _D(e,t,n,r,i,o){return t.referenceResolver||t.calleeResolver||t.signatureResolver||!PD(t)?null:Py(e,n,{fallbackReferenceResolver:r,fallbackCalleeResolver:i,fallbackSignatureResolver:o})}function OD(e,t){return e.importUsageResolver??Zh(e.sourceImportUsageResolver??TD(),e.importDefinitionResolver??t)}function BD(e,t){return{references:t,incompleteReferenceSymbolIds:Array.isArray(e.incompleteReferenceSymbolIds)?e.incompleteReferenceSymbolIds.filter(r=>typeof r=="number"):void 0,callees:Array.isArray(e.callees)?e.callees:void 0,signatures:Array.isArray(e.signatures)?e.signatures:void 0}}function $D(e,t,n,r,i){let o=[];for(let s of e)t.has(s.symbolId)?i.set(s.symbolId,t.get(s.symbolId)??[]):n.has(s.symbolId)?i.set(s.symbolId,n.get(s.symbolId)??[]):Ay(s,r)?i.set(s.symbolId,[]):o.push(s);return o}function jD(e,t,n,r){let i=[];for(let o of e)t.has(o.symbolId)?r.set(o.symbolId,t.get(o.symbolId)??[]):Ay(o,n)?r.set(o.symbolId,[]):i.push(o);return i}function HD(e){return!(e.available===!1&&typeof e.reason!="string"||e.available===!0&&e.reason!==void 0)}import{existsSync as UD}from"fs";import{deserializeSCIP as qD,SymbolRole as zD}from"@c4312/scip";var od=new WeakMap;function By(e,t){let n=t.filter(GD);if(n.length===0)return new Map;let r=!1,i=0,o=0;return M("rust.scip-occurrence.callees",()=>{let s=VD(e);if(r=!!s,!s)return new Map;let a=new Map;for(let c of n){let l=KD(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 GD(e){return!(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||!e.isFunctionLike||e.leaf==="main"||ke(e.symbol))}function KD(e,t,n){let r=z(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)||!WD(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 WD(e,t){let n=Oy(e),r=Oy(t);if(n.size!==r.size)return!1;for(let[i,o]of n)if(r.get(i)!==o)return!1;return!0}function Oy(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 VD(e){if(od.has(e))return od.get(e)??null;let t=JD(e);return od.set(e,t),t}function JD(e){if(!e.generation.indexPath||!UD(e.generation.indexPath))return null;try{let t=Pe(e).filter(o=>o.symbol.startsWith("rust-analyzer ")&&o.relativePath.endsWith(".rs")&&o.isFunctionLike),n=new Map(t.map(o=>[o.symbol,o])),r=qD(Ws(e.generation.indexPath,{inputKind:"SCIP occurrence-callee index",maxBytes:Ks})),i=new Map;for(let o of r.documents??[]){let s=o.relativePath;if(!s||!s.endsWith(".rs")||e.isIgnored(s))continue;let a=YD(o,n);i.set(s,a)}return{occurrencesByFile:i}}catch{return null}}function YD(e,t){let n=[];for(let r of e.occurrences??[]){if(!r.symbol||(r.symbolRoles&zD.Definition)!==0)continue;let i=t.get(r.symbol);if(!i)continue;let o=r.range?.[0];Number.isInteger(o)&&n.push({line:o,leaf:i.leaf,traitImplMember:ke(i.symbol),callee:{symbol:i.symbol,file:i.relativePath,line:i.startLine,callsiteLine:o}})}return n}var Xa=class{sessions=new WeakMap;getOrCreate(t,n,r){let i=XD(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 XD(e,t){return`${e.config.projectRoot}:${t}-workspace`}import{randomUUID as qF}from"crypto";import{existsSync as zF}from"fs";import{dirname as pb}from"path";function QD(e){return(e.tsconfigPath===void 0||typeof e.tsconfigPath=="string")&&(e.tsconfigPaths===void 0||Array.isArray(e.tsconfigPaths)&&e.tsconfigPaths.every(t=>typeof t=="string"))}function ZD(e){return typeof e.available=="boolean"&&(e.dependencyAvailable===void 0||typeof e.dependencyAvailable=="boolean")&&QD(e)&&(e.resolvedBinary===void 0||typeof e.resolvedBinary=="string")&&(e.note===void 0||typeof e.note=="string")}function $y(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(!ZD(t))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 Y}from"perf_hooks";function at(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}import Uy from"path";import{realpathSync as jy}from"fs";function eF(e,t){return e.getReferences().map(n=>{let r=n.getNode();return Qa(r,t)})}function tF(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function qy(e,t,n,r){let i=[];for(let o of tF(e))for(let s of eF(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 mi(i)}function zy(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();pi(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:Qa(a,r),node:a}))}return i}function Qa(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:pi(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function Gy(e,t,n){let r=e.getSourceFile(),i=ad(r,e),o=e.getText(),s=new RegExp(`\\b${Ge(o)}\\b`,"g"),a=r.getFullText().split(`
|
|
15
|
+
`),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 mi(c.filter(l=>pi(n,Uy.join(n,l.file))===t))}function sd(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 ad(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function mi(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 pi(e,t){let n=e||process.cwd(),r=Hy(n,t);if(r)return r;try{return Hy(jy(n),jy(t))}catch{return null}}function Hy(e,t){let n=Uy.relative(e,t).replace(/\\/g,"/");return!n||n===".."||n.startsWith("../")?null:n}function Ky(e,t,n,r){let i=nF(t,r);return i.size===0?new Map:rF(e,n,i)}function nF(e,t){let n=new Map;for(let r of D(e,t)){let i=A(r.symbol)??r.leaf;if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return n}function rF(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of iF(e,o)){let a=n.get(s);if(!a)continue;let c=ad(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 iF(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}function cd(e,t,n){let r=new Map,i=new Set,o=s=>{if(e.isFunctionLike(s)){let a=oF(e,s),l=a.name?.getText(t)??(e.isConstructorDeclaration(s)?"constructor":void 0),u=t.getLineAndCharacterOfPosition(a.getStart(t)),d=n.filter(m=>!i.has(m.symbolId)&&m.leaf===l&&aF(m,u));d.length===1&&(r.set(s,d[0]),i.add(d[0].symbolId))}e.forEachChild(s,o)};return o(t),s=>{for(let a=s.parent;a;a=a.parent)if(e.isFunctionLike(a))return r.get(a)}}function oF(e,t){if(!e.isArrowFunction(t)&&!e.isFunctionExpression(t))return t;let n=t;for(;n.parent&&sF(e,n.parent);)n=n.parent;let r=n.parent;return r&&(e.isVariableDeclaration(r)||e.isPropertyDeclaration(r)||e.isPropertyAssignment(r))&&r.initializer===n?r:t}function sF(e,t){return e.isParenthesizedExpression(t)||e.isAsExpression(t)||e.isSatisfiesExpression(t)}function aF(e,t){return t.line<e.startLine||t.line>e.endLine||t.line===e.startLine&&t.character<(e.startChar??0)?!1:t.line!==e.endLine||t.character<=(e.endChar??1/0)}var cF=Hr("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function Wy(e,t,n,r){let i=dd(e,t),o=ld(i.get(r)??[],n);if(o)return o;let s=[];for(let a of i.values())for(let c of a)((c.leaf||A(c.symbol)||"").includes(r)||c.symbol.includes(r))&&s.push(c);return ld(s,n)}function ud(e,t,n,r){return ld(dd(e,t).get(r)??[],n)}function Vy(e,t){let n=new Map;for(let[r,i]of dd(e,t)){let o=i[0];o&&n.set(r,o)}return n}function dd(e,t){return cF.get(e,t,()=>{let n=new Map;for(let r of D(e,t)){let i=r.leaf||A(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 ld(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 lF from"path";import{realpathSync as uF}from"fs";function Yy(e,t){let n=new Map,r=new Map,i=null,o=()=>(i??=q(e,{extensions:Ca}),i),s=l=>at(r,l,()=>M("typescript.source-file-index",()=>{let u=new Map;for(let d of l.project.getSourceFiles())Jy(u,d);return{project:l.project,sourceFiles:u}},()=>({tsconfigPath:l.tsconfigPath,indexedDocuments:o().length}))),a=(l,u)=>{let d=s(l),m=d.sourceFiles.get(u)??null;return m||(m=l.project.addSourceFileAtPathIfExists(u)??null,m&&Jy(d.sourceFiles,m)),m?{project:d.project,sourceFile:m}:null},c=l=>xt(l)?at(n,l,()=>{let u=dF(e.config.projectRoot,l);if(!u)return null;for(let p of t){if(!p.loaded)continue;let f=s(p).sourceFiles.get(u);if(f)return{project:p.project,sourceFile:f}}let d=t.find(p=>p.fileNames?.has(u));if(d)return a(d,u);for(let p of t){if(!p.loaded)continue;let f=a(p,u);if(f)return f}let m=t[0];return m?a(m,u):null}):null;return{sourceFile:l=>c(l)?.sourceFile??null,sourceFileMatch:c,indexedTypeScriptLikeDocuments:o}}function Jy(e,t){let n=md(t.getFilePath());e.set(n,t);try{e.set(md(uF(n)),t)}catch(r){if(!xe(r))throw r}}function dF(e,t){try{return md(Vs(e,t,{inputKind:"indexed TypeScript source file"}).absolutePath)}catch(n){if(!xe(n))throw n;return null}}function md(e){return lF.resolve(e)}function pd(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Xy(e){let t=`${e.relativeDir}/src`;return[`${t}/index.ts`,`${t}/index.tsx`,`${t}/index.mts`,`${t}/index.cts`]}import{existsSync as jo}from"fs";import Oe from"path";var fd=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"];function gd(e,t){let r=t?Oe.dirname(Oe.join(e,t)):e,i=Oe.resolve(e);for(;r.startsWith(i);){for(let s of fd){let a=Oe.join(r,s);if(jo(a))return a}let o=Oe.dirname(r);if(o===r)break;r=o}for(let o of fd){let s=Oe.join(e,o);if(jo(s))return s}return null}function Qy(e){let t=e.config.projectRoot,n=new Set(mF(t,e.config.semantic?.typescript?.tsconfigs)),r=q(e,{includeIgnored:!1,extensions:Ca});for(let i of r){let o=gd(t,i);o&&n.add(Oe.resolve(o))}if(n.size===0){let i=gd(t);i&&n.add(Oe.resolve(i))}return[...n].filter(i=>!Zy(t,i)).sort((i,o)=>i.localeCompare(o))}function mF(e,t=[]){let n=new Set;for(let r of t){let i=Oe.isAbsolute(r)?r:Oe.join(e,r);jo(i)&&n.add(Oe.resolve(i))}for(let r of pF(e))for(let i of fd){let o=Oe.join(r,i);jo(o)&&n.add(Oe.resolve(o))}if(n.size===0){let r=gd(e);r&&n.add(Oe.resolve(r))}return[...n].filter(r=>!Zy(e,r)).sort((r,i)=>r.localeCompare(i))}function pF(e){let t=Oe.join(e,"package.json");if(!jo(t))return[];let n;try{n=JSON.parse(Ye(t,"project package manifest"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>Yf(e,i))}function Zy(e,t){let n=Oe.relative(e,t).replace(/\\/g,"/");return n.startsWith("..")||n.includes("/node_modules/")||n.startsWith("node_modules/")||n.includes("/dist/")||n.startsWith("dist/")}var fF=32;function sb(e,t){let n=M("typescript.provider.load",()=>xa());if(!n)return Ea("ts-morph is not installed");let r=M("typescript.provider.tsconfig-discovery",()=>Qy(e));if(r.length===0)return Ea("no tsconfig found");try{let i=M("typescript.provider.project-bundles",()=>Ug(n,r),()=>({tsconfigs:r.length}));return gF(e,n,i)}catch(i){return Ea(i instanceof Error?i.message:String(i),r[0],r)}}function gF(e,t,n,r={}){return M("typescript.provider.construct",()=>new hd(e,t,n),()=>({tsconfigs:n.length,reusedProjects:r.reusedProjects===!0}))}var hd=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=Jf(t.config.projectRoot),this.sourceFiles=Yy(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;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){let t=Ra(this.projects);return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(n=>n.tsconfigPath),projectScope:t?"file-closure":"project",...t?{note:"compiler projects are file-scoped: callees, signatures, and import usage are served per file; references and hierarchies are unavailable"}:{}}}attachBatchFiles(t){if(Ra(this.projects))for(let n of new Set(t.map(r=>r.relativePath)))this.sourceFiles.sourceFile(n)}assertProjectWide(){if(Ra(this.projects))throw new Error(qg)}importUsage(t){return at(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let r=yF();return M("typescript.import-usage.file",()=>this.importUsageForSourceFile(t,n,r),()=>({file:t,...r}))})}referencesFor(t){return at(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);return this.referencesForDefinitionNode(t,n)})}referencesForDefinitions(t,n={}){this.assertProjectWide();let r=new Map,i=fe(),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=>!tb(u));if(a.length>=fF){let u=this.referencesForDefinitionsBySymbolScan(a);if(this.cacheScannedReferenceResults(a,u,r),s=o.filter(d=>tb(d)),s.length===0)return r}let c=TF(s),l=[];for(let[u,d]of c){let m=nb();M("typescript.references-map.file",()=>{let p=this.definitionNodesForFile(u);for(let f of d){i&&(m.cacheMisses+=1);let g=p.get(f.symbolId)??null;i&&(g?m.nodeHits+=1:m.nodeMisses+=1);try{let h=this.referencesForDefinitionNode(f,g,i?m:void 0);this.referencesCache.set(f.symbolId,h),r.set(f.symbolId,h)}catch{m.preciseSearchFailures+=1,l.push(f)}}},()=>({relativePath:u,definitions:d.length,...ib(m)}))}if(l.length>0){let u=this.referencesForDefinitionsBySymbolScan(l);this.cacheScannedReferenceResults(l,u,r)}return r}cacheScannedReferenceResults(t,n,r){for(let i of t){let o=n.get(i.symbolId)??[];this.referencesCache.set(i.symbolId,o),r.set(i.symbolId,o)}}referenceFragmentsForFiles(t){this.assertProjectWide();let n=Pe(this.db).filter(o=>xt(o.relativePath)),r=t.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(n,r);return zg(n,i,r)}referencesForDefinitionsBySymbolScan(t,n){let r=fe(),i=nb(),o=new Map,s=new Set(t.map(u=>u.symbolId)),a=new Map(t.map(u=>[u.symbolId,u]));for(let u of t)o.set(u.symbolId,[]);let c=()=>{let u=r?Y.now():0,d=n?this.packageImportReferencesForFiles(n):this.packageImportReferences();for(let m of t){let p=d.get(m.symbolId)??[];if(p.length>0){let f=o.get(m.symbolId)??[];f.push(...p),o.set(m.symbolId,f)}r&&(i.packageReferenceCount+=p.length)}r&&(i.packageRefsMs+=Y.now()-u)},l=()=>{let u=new Map,d=new Map,m=this.hierarchyTargetsForDefinitions(t),p=new Set(t.map(g=>g.leaf).filter(Boolean)),f=r?Y.now():0;for(let g of n??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(g))continue;let h=this.sourceFiles.sourceFile(g);h&&(r&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(h,g,s,a,m,p,u,d,o,r?i:void 0))}r&&(i.scanMs+=Y.now()-f)};return M("typescript.references-map.inverted-scan",()=>{c(),l();let u=r?Y.now():0;this.addHierarchyMemberReferences(t,o,r?i:void 0),r&&(i.hierarchyMs+=Y.now()-u);for(let[d,m]of o){let p=mi(m);o.set(d,p),r&&(i.referenceCount+=p.length)}},()=>({definitions:t.length,...ib(i)})),o}addReferencesFromSourceFileScan(t,n,r,i,o,s,a,c,l,u){let d=this.compilerCheckerForSourceFile(t),m=t.compilerNode,p=vF(t),f=y=>{let S;return a.has(y)?S=a.get(y)??null:(S=this.referenceDefinitionFromCompilerSymbol(y),a.set(y,S)),u&&(S?u.targetHits+=1:u.targetMisses+=1),S},g=y=>{if(u&&(u.identifiers+=1),!s.has(y.text)&&!p.has(y.text))return;let S=this.compilerReferenceSymbol(d,y,u);if(!S)return;let I=f(S),x=at(c,S,()=>this.compilerSymbolKeys(S)),E=null,b=null,v=R=>{if(E??=eb(m,y),CF(R,n,E))return;if(!b){let w=m.getLineAndCharacterOfPosition(y.getStart(m));b={file:n,line:w.line,column:w.character}}let P=l.get(R.symbolId)??[];P.push(b),l.set(R.symbolId,P),u&&(u.requestedHits+=1)},C=DF(I,r,i);C&&v(C);for(let R of x)for(let P of o.get(R)?.values()??[])v(P)},h=y=>{this.tsMorph.ts.isIdentifier(y)&&g(y),this.tsMorph.ts.forEachChild(y,h)};h(m)}hierarchyTargetsMemo=null;hierarchyTargetsForDefinitions(t){let n=IF(t);if(this.hierarchyTargetsMemo?.key===n)return this.hierarchyTargetsMemo.targets;let r=nt(this.db),i=`definitions:${n}`,o=!1,s=M("typescript.references-map.hierarchy-targets",()=>{if(r){let c=rb.read(this.db,i,r);if(c&&c.projectRoot===this.db.config.projectRoot)return o=!0,EF(c,t)}let a=this.computeHierarchyTargets(t);return r&&rb.write(this.db,i,r,{version:ab,projectRoot:this.db.config.projectRoot,entries:[...a].map(([c,l])=>[c,[...l.values()].map(u=>u.symbol)])}),a},()=>({definitions:t.length,hit:o}));return this.hierarchyTargetsMemo={key:n,targets:s},s}computeHierarchyTargets(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,o=(c,l,u,d)=>{for(let m of this.hierarchyMemberSymbols(l,u,d))if(m!==d)for(let p of this.compilerSymbolLocations(m))c.push(p),r&&(r.hierarchyReferences+=1)},s=c=>{let l=this.nodeForDefinition(c),u=l?.compilerNode;if(!u||!this.isHierarchyMethod(u))return;let d=u.parent;if(!this.isHierarchyContainer(d))return;let m=this.compilerCheckerForSourceFile(l.getSourceFile()),p=m.getSymbolAtLocation(u.name);if(!p)return;let f=u.getSourceFile(),g=f.getLineAndCharacterOfPosition(u.name.getStart(f)),h={definition:c,location:{file:c.relativePath,line:g.line,column:g.character}},y=n.get(c.symbolId)??[];o(y,m,d,p),n.set(c.symbolId,y);let S=this.hierarchyRootMemberSymbols(m,d,p);for(let I of S){let x=i.get(I)??new Map;x.set(c.symbolId,h),i.set(I,x)}r&&(r.hierarchyDefinitions+=1)},a=c=>{for(let{definition:l}of c.values()){let u=n.get(l.symbolId)??[];for(let d of c.values())d.definition.symbolId!==l.symbolId&&(u.push(d.location),r&&(r.hierarchyReferences+=1));n.set(l.symbolId,u)}};for(let c of t)s(c);for(let c of i.values())c.size<2||(r&&(r.hierarchyFamilies+=1),a(c))}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=pi(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 at(this.calleesCache,t.symbolId,()=>at(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}calleesForDefinitions(t){let n=new Map;this.attachBatchFiles(t);let 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}calleeCoverageForDefinitions(t){this.attachBatchFiles(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]),n.set(i.symbolId,{callSites:0,resolvedInRepository:0,resolvedExternal:0,unresolved:0})}for(let[i,o]of r){let s=this.sourceFiles.sourceFile(i);if(!s)continue;let a=this.compilerCheckerForSourceFile(s),c=s.compilerNode,l=new Map,u=cd(this.tsMorph.ts,c,o),d=m=>{if(this.tsMorph.ts.isCallExpression(m)||this.tsMorph.ts.isNewExpression(m)||ob(this.tsMorph.ts,m)){let p=u(m),f=p?n.get(p.symbolId):void 0;f&&this.recordCallSiteCoverage(m,a,f,l)}this.tsMorph.ts.forEachChild(m,d)};d(c)}return n}callNodeExpression(t){return this.tsMorph.ts.isJsxOpeningElement(t)||this.tsMorph.ts.isJsxSelfClosingElement(t)?this.tsMorph.ts.isJsxNamespacedName(t.tagName)?null:t.tagName:t.expression}recordCallSiteCoverage(t,n,r,i){r.callSites+=1;let o=this.callNodeExpression(t),s=o?this.compilerSymbolForExpression(n,o):void 0;if(!s){r.unresolved+=1;return}let a=i.get(s);a===void 0&&(a=this.definitionFromCompilerSymbol(s),i.set(s,a)),a?r.resolvedInRepository+=1:r.resolvedExternal+=1}referencesForDefinitionNode(t,n,r){let i=r?Y.now():0,o=this.packageImportReferencesForDefinition(t);if(r&&(r.packageRefsMs+=Y.now()-i,r.packageReferenceCount+=o.length),!n)return o;let s=r?Y.now():0,a=qy(n,t,o,this.db.config.projectRoot);return r&&(r.semanticRefsMs+=Y.now()-s,r.referenceCount+=a.length),a}signatureFor(t){return at(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];return(a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown").trim()}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${o.trim()}`})}importUsageForSourceFile(t,n,r){let i=[],o=new Map;for(let s of n.getImportDeclarations()){r.declarations+=1;let a=ro(this.db,t,s.getModuleSpecifierValue()),c=s.getImportClause()?.isTypeOnly()??!1;for(let l of yd(s)){let u=LF(a,l,c,r),{bindingSymbol:d}=u;if(i.push(u),c||!l.localName||!d)continue;let m=o.get(l.localName);m?m.push(u):o.set(l.localName,[u])}}return o.size>0&&n.forEachDescendant(s=>{if(s.getKindName()!=="Identifier")return;let a=o.get(s.getText());if(!a||bF(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:Qa(s,this.db.config.projectRoot),node:s}),r.matchedReferences+=1;break}}}),i.map(s=>s.typeOnlyDeclaration?hF(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 zy(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=>!sd(c.node)),s=i.some(c=>sd(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=pd(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,mi(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,mi(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=pd(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of yd(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=Gy(a.identifier,r,this.db.config.projectRoot);l.length>0&&wF(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 Xy(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?ro(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}MF(l,r,u=>this.indexedDefinitionByLeaf(c,u))}}indexedDefinitionByLeaf(t,n){return at(this.indexedDefinitionLeafCache,t,()=>Vy(this.db,t)).get(n)??null}nodeForDefinition(t){return at(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return at(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?Ky(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?Y.now():0,s=t.declarations??[];n&&(n.declarationsMs+=Y.now()-o,n.declarationChecks+=s.length);for(let a of s){let c=n?Y.now():0,l=a.getSourceFile(),u=pi(this.db.config.projectRoot,l.fileName),d=l.getLineAndCharacterOfPosition(a.getStart(l)).line;if(n&&(n.declarationLocationMs+=Y.now()-c),!u||this.db.isIgnored(u))continue;let m=this.indexedMatchForCompilerDeclaration(a,u,d,i,n,r);if(m)return{symbolId:m.symbolId,symbol:m.symbol,file:m.relativePath,line:m.startLine}}return null}indexedMatchForCompilerDeclaration(t,n,r,i,o,s){let a=o?Y.now():0,c=this.compilerDeclarationName(t),l=s?ud(this.db,n,r,i)??(c&&c!==i?ud(this.db,n,r,c):null):Wy(this.db,n,r,i);return o&&(o.indexedLookupMs+=Y.now()-a),l}compilerDeclarationName(t){let n=t.name;return n&&this.tsMorph.ts.isIdentifier(n)?n.text:null}calleeMapForFile(t,n){let r=fe(),i=0,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=r?xF():void 0;return M("typescript.callee-map.file",()=>{let p=r?Y.now():0,f=this.sourceFiles.sourceFile(t);if(r&&(c=Math.round(Y.now()-p)),!f)return new Map;let g=kF(this.db,t,r),h=g.definitions;if(r&&(l=g.durationMs),i=h.length,h.length===0)return new Map;let y=new Map,S=r?Y.now():0,I=this.compilerCheckerForSourceFile(f),x=f.compilerNode,E=cd(this.tsMorph.ts,x,h);r&&(u=Math.round(Y.now()-S));let b=new Map,v=R=>{if(this.tsMorph.ts.isCallExpression(R)||this.tsMorph.ts.isNewExpression(R)||ob(this.tsMorph.ts,R)){r&&(o+=1);let P=this.semanticCalleeForCallNode(I,x,E,R,b,n,m);P&&(r&&(s+=1),SF(y,P.callerId,P.target))}this.tsMorph.ts.forEachChild(R,v)},C=r?Y.now():0;return v(x),r&&(d=Math.round(Y.now()-C)),NF(y),a=y.size,y},()=>({relativePath:t,definitions:i,callNodes:o,resolvedCallees:s,outputRows:a,requestedDefinitions:n?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:u,traversalMs:d,...m?RF(m):{}}))}semanticCalleeForCallNode(t,n,r,i,o,s,a){let c=this.requestedCallSiteOwner(r,i,s,a);if(!c)return null;let l=this.tsMorph.ts.isJsxOpeningElement(i)||this.tsMorph.ts.isJsxSelfClosingElement(i);if(l&&this.tsMorph.ts.isJsxNamespacedName(i.tagName))return null;let u=l?i.tagName:i.expression,d=this.compilerSymbolForExpression(t,u,a),m=this.profiledCalleeTarget(d,o,a);return m?{callerId:c.symbolId,target:{symbol:m.symbol,file:m.file,line:m.line,callsiteLine:eb(n,i),...l?{kind:"jsx-render"}:{}}}:null}requestedCallSiteOwner(t,n,r,i){let o=i?Y.now():0,s=t(n);return i&&(i.callerLookupMs+=Y.now()-o),s?r&&!r.has(s.symbolId)?(i&&(i.skippedUnrequestedCallers+=1),null):s:null}profiledCalleeTarget(t,n,r){if(!t)return r&&(r.targetMisses+=1),null;if(r&&(r.targetSymbolHits+=1),n.has(t))return r&&(r.compilerSymbolCacheHits+=1),n.get(t)??null;r&&(r.compilerSymbolCacheMisses+=1);let i=r?Y.now():0,o=this.definitionFromCompilerSymbol(t,r);return r&&(r.targetLookupMs+=Y.now()-i),n.set(t,o),o}compilerSymbolForExpression(t,n,r){let i=r?Y.now():0,o=t.getSymbolAtLocation(n);if(r&&(r.expressionSymbolMs+=Y.now()-i),o){if((o.flags&this.tsMorph.ts.SymbolFlags.Alias)===0)return o;try{return t.getAliasedSymbol(o)}catch{return o}}r&&(r.typeFallbacks+=1);let s=r?Y.now():0,a=t.getTypeAtLocation(n).getSymbol();return r&&(r.typeSymbolMs+=Y.now()-s),a}compilerCheckerForSourceFile(t){return t.getProject().getTypeChecker().compilerObject}};function yd(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())t.push(FF(i,e));return t.length===0&&t.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),t}function hF(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 yF(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function bF(e){for(let t=e;t;t=t.getParent())if(t.getKindName()==="ImportDeclaration")return!0;return!1}function SF(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function vF(e){let t=new Set;for(let n of e.getImportDeclarations())for(let r of yd(n))r.localName&&t.add(r.localName);return t}function eb(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line}function CF(e,t,n){return t===e.relativePath&&n>=e.startLine&&n<=e.endLine}function tb(e){return e.symbol.includes("#")?vt(e.symbol)==="type"&&e.relativePath.endsWith(".d.ts"):!1}function xF(){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 RF(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 nb(){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}}var ab=1,rb=er({kind:"typescript-hierarchy-targets",invalidation:Re("typescript-hierarchy-targets"),serialize:e=>JSON.stringify(e),deserialize:e=>{try{let t=JSON.parse(e);return t.version!==ab||typeof t.projectRoot!="string"||!Array.isArray(t.entries)?null:t}catch{return null}}});function EF(e,t){let n=new Map(t.map(i=>[i.symbol,i])),r=new Map;for(let[i,o]of e.entries){let s=new Map;for(let a of o){let c=n.get(a);c&&s.set(c.symbolId,c)}s.size>0&&r.set(i,s)}return r}function IF(e){let t=2166136261;for(let n of e)t^=n.symbolId,t=Math.imul(t,16777619)>>>0;return`${e.length}:${t.toString(16)}`}function ib(e){return{...e,scanMs:Math.round(e.scanMs),packageRefsMs:Math.round(e.packageRefsMs),semanticRefsMs:Math.round(e.semanticRefsMs),hierarchyMs:Math.round(e.hierarchyMs)}}function wF(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function ob(e,t){if(!e.isJsxOpeningElement(t)&&!e.isJsxSelfClosingElement(t))return!1;let n=t.tagName;return e.isPropertyAccessExpression(n)?!0:e.isIdentifier(n)?/^[A-Z]/.test(n.text):!1}function PF(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}|${r.line}|${r.callsiteLine??""}`;t.has(i)||(t.add(i),n.push(r))}return n}function TF(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);r?r.push(n):t.set(n.relativePath,[n])}return t}function LF(e,t,n,r){r.entries+=1;let i=n?null:t.identifier?.getSymbol()?.compilerSymbol??null;return!n&&t.identifier&&(i?r.bindingSymbols+=1:r.missingBindingSymbols+=1),{sourcePath:e,entry:t,typeOnlyDeclaration:n,bindingSymbol:i,references:[]}}function MF(e,t,n){for(let r of e){let i=r.getNameNode().getText(),o=r.getAliasNode()?.getText()??i,s=n(i);if(!s)continue;let a=t.get(o);a||(a=new Set,t.set(o,a)),a.add(s.symbolId)}}function DF(e,t,n){return e&&t.has(e.symbolId)?n.get(e.symbolId):void 0}function FF(e,t){let n=e.getNameNode(),i=e.getAliasNode()??(n.getKindName()==="Identifier"?n:null);return{identifier:i,importedName:n.getText(),localName:i?.getText()??n.getText(),kind:"named",isTypeOnly:e.isTypeOnly()||(t.getImportClause()?.isTypeOnly()??!1)}}function kF(e,t,n){let r=n?Y.now():0,i=D(e,t).sort((s,a)=>s.startLine-a.startLine||a.endLine-s.endLine),o=n?Math.round(Y.now()-r):0;return{definitions:i,durationMs:o}}function NF(e){for(let[t,n]of e)e.set(t,PF(n))}import{join as AF}from"path";var fi=3,_F=2,OF="typescript-semantic";function cb(e){let t=AF(e,OF),n=ba(t);return{...n,requestDir:n.legacyRequestDir}}function lle(e){let t=JSON.parse(e),n=t.protocolVersion,r=n===_F;if(!r&&n!==fi||!BF(t)||!r&&!$F(t))throw new Error("TypeScript semantic service received an invalid mailbox request.");if(!r){let o=t,s=Tn("typescript-semantic-v3",{generation:o.generation,profileEnvironment:o.profileEnvironment,request:o.request});if(o.operationKey!==s)throw new Error("TypeScript semantic service received a mismatched mailbox operation identity.");return o}let i=Tn("typescript-semantic-v2",{id:t.id,generation:t.generation,request:t.request});return{protocolVersion:fi,mailboxVersion:cn,id:t.id,operationKey:i,clientId:"legacy-v2",enqueuedAtMs:t.deadlineAtMs,deadlineAtMs:t.deadlineAtMs,generation:t.generation,...t.profileEnvironment?{profileEnvironment:t.profileEnvironment}:{},request:t.request}}function BF(e){return typeof e.id=="string"&&typeof e.generation=="string"&&typeof e.deadlineAtMs=="number"&&Number.isFinite(e.deadlineAtMs)&&(e.profileEnvironment===void 0||tu(e.profileEnvironment))&&!!e.request&&jF(e.request)}function $F(e){return e.mailboxVersion===cn&&typeof e.operationKey=="string"&&/^[a-f0-9]{64}$/.test(e.operationKey)&&e.id===sr(e.operationKey)&&typeof e.clientId=="string"&&e.clientId!==""&&typeof e.enqueuedAtMs=="number"&&Number.isFinite(e.enqueuedAtMs)&&e.deadlineAtMs>=e.enqueuedAtMs}function jF(e){if(!HF(e))return!1;let t=e;switch(t.kind){case"availability":return!0;case"import-usage":return typeof t.file=="string";case"reference-fragments":return io(t.files)!==null;case"references":return UF(t);case"callees":case"callee-coverage":return lb(t.definitions);case"signature":return ub(t.definition);default:return!1}}function lb(e){return Array.isArray(e)&&e.every(ub)}function ub(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.symbolId=="number"&&typeof t.documentId=="number"&&typeof t.symbol=="string"&&typeof t.relativePath=="string"&&typeof t.leaf=="string"&&typeof t.startLine=="number"&&typeof t.endLine=="number"}function HF(e){return!!e&&typeof e=="object"&&e!==null&&"kind"in e}function UF(e){return lb(e.definitions)&&(e.exact===void 0||typeof e.exact=="boolean")}var GF=12e4,KF=5;function fb(e,t,n={}){let r=n.requester??new Sd(e,n),i=null,o=null,s=process.env.SCIP_QUERY_SKIP_WATCH_SERVICE==="1",a=null,c=()=>(i??=sb(e,t),i),l=(f,g,h)=>(s=!0,XF(e)?g():(a=f instanceof Error?f.message:String(f),console.error(`TypeScript semantic service request failed (${a}); semantic enrichment is disabled for the rest of this run because the index is too large for an in-process compiler.`),h())),u=(f,g,h,y=h)=>{if(a!==null)return y();if(s)return h();try{return g(r.request(f))}catch(S){return db(S)?y():l(S,h,y)}},d=(f,g,h,y)=>{if(a!==null)return new Map;if(s)return y();let S=I=>{try{return h(r.request(g(I)))}catch(x){if(!WF(x))throw x;let E=VF(I);if(!E)throw x;return new Map([...S(E[0]),...S(E[1])])}};try{return S(f)}catch(I){return db(I)?new Map:l(I,y,()=>new Map)}},m=(f,g)=>d(f,h=>({kind:"references",definitions:[...h],...g?.exact?{exact:!0}:{}}),h=>bd(h),()=>c().referencesForDefinitions?.(f,g)??new Map(f.map(h=>[h.symbolId,c().referencesFor(h)]))),p=f=>d(f,g=>({kind:"callees",definitions:[...g]}),g=>bd(g),()=>c().calleesForDefinitions?.(f)??new Map(f.map(g=>[g.symbolId,c().calleesFor(g)])));return{language:"typescript",availability:()=>(o??=u({kind:"availability"},tk,()=>c().availability(),()=>({available:!1,reason:`TypeScript semantic service declined: ${a??"unknown"}`})),o),importUsage:f=>u({kind:"import-usage",file:f},g=>g,()=>c().importUsage(f),()=>[]),referencesFor:f=>m([f]).get(f.symbolId)??[],referencesForDefinitions:m,referenceFragmentsForFiles:f=>u({kind:"reference-fragments",files:[...f]},g=>ek(g),()=>c().referenceFragmentsForFiles?.(f)??new Map,()=>new Map),calleesFor:f=>p([f]).get(f.symbolId)??[],calleesForDefinitions:p,calleeCoverageForDefinitions:f=>d(f,g=>({kind:"callee-coverage",definitions:[...g]}),g=>bd(g),()=>c().calleeCoverageForDefinitions?.(f)??new Map),signatureFor:f=>u({kind:"signature",definition:f},nk,()=>c().signatureFor(f),()=>null),dispose:()=>i?.dispose?.()}}function WF(e){let t=e instanceof Error?e.message:String(e);return/memory limit|heap out of memory|worker terminated|worker failed/iu.test(t)}function VF(e){let t=[...new Set(e.map(r=>r.relativePath))].sort();if(t.length<2)return null;let n=new Set(t.slice(0,Math.ceil(t.length/2)));return[e.filter(r=>n.has(r.relativePath)),e.filter(r=>!n.has(r.relativePath))]}function db(e){let t=e instanceof Error?e.message:String(e);return t.includes("invalid mailbox request")||t.includes("Unhandled TypeScript semantic request")||t.includes("compiler project is file-scoped")}var JF=2500,YF=25e3,mb=new WeakMap;function XF(e){let t=mb.get(e);if(t!==void 0)return t;let n=QF(e);return mb.set(e,n),n}function QF(e){try{let t=e.get("SELECT (SELECT count(*) FROM documents) AS documents, (SELECT count(*) FROM global_symbols) AS symbols");return!t||t.documents<JF&&t.symbols<YF}catch{return!0}}var Sd=class{constructor(t,n={}){this.db=t;this.runtime=n.runtime??hb,this.timeoutMs=n.timeoutMs??rk(),this.mailboxLimits=n.mailboxLimits??{},this.cacheDir=pb(t.config.dbPath),this.projectRoot=Zl(t.config.projectRoot)}db;runtime;timeoutMs;cacheDir;projectRoot;mailboxLimits;request(t){let n=yu(this.cacheDir),r=cb(this.cacheDir),i=va(n.statePath);if(!vd(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??Ct)()+this.timeoutMs,l=Zf(),u=Tn("typescript-semantic-v3",{generation:o,profileEnvironment:l,request:t}),d=sr(u),m=Sa(r,{mailboxVersion:cn,operationKey:u,clientId:this.runtime.randomId(),enqueuedAtMs:s,deadlineAtMs:a,protocolVersion:fi,id:d,generation:o,profileEnvironment:l,request:t},{nowMs:s,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??Ct)()<=c;){if(zF(m.responsePath))return ZF(ht(m.responsePath,{maxBytes:this.mailboxLimits.maxItemBytes??64*1024*1024,inputKind:"TypeScript semantic mailbox response"}),d,o,u);let p=va(n.statePath);if(!vd(p,this.projectRoot,this.runtime))throw new Error("TypeScript semantic service stopped while processing a request.");this.runtime.sleep(KF)}throw new Error(`TypeScript semantic service timed out after ${this.timeoutMs}ms.`)}};function gb(e){if(process.env.SCIP_QUERY_SKIP_WATCH_SERVICE==="1")return!1;try{let t=va(yu(pb(e.config.dbPath)).statePath);return vd(t,Zl(e.config.projectRoot),hb)}catch{return!1}}function vd(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptSemantic?.protocolVersion===fi&&n.isProcessAlive(e.pid)&&(!e.processIdentity||r!=null&&ya(e.processIdentity,r))}function ZF(e,t,n,r){let i=JSON.parse(e);if(i.protocolVersion!==fi||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 bd(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid numeric map.");return new Map(e)}function ek(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid string map.");return new Map(e)}function tk(e){let t=$y(e);if(!t)throw new Error("TypeScript semantic service wrote invalid availability.");return t}function nk(e){if(e!==null&&typeof e!="string")throw new Error("TypeScript semantic service wrote an invalid signature.");return e}function rk(){let e=Number(process.env.SCIP_TYPESCRIPT_SEMANTIC_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:GF}var hb={now:Date.now,monotonicNow:Ct,randomId:qF,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:ni,readProcessIdentity:ri};var yb=new Xa;qf({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>yb.clear(e)});function un(e,t){let n=Se(t)??"typescript";return yb.getOrCreate(e,n,()=>n==="rust"?Ny(e.config.projectRoot,{sourceImportUsageResolver:{importUsageFacts:r=>Qh(e,r)},calleeSymbolResolver:Xh(e),sourceZeroCalleeOracle:r=>ik(e,r),scipOccurrenceCalleeOracle:r=>By(e,r)}):fb(e,t))}function Se(e){return e?se(e)==="rust"?"rust":xt(e)?"typescript":null:"typescript"}function ik(e,t){let n=z(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 ok=/^[A-Za-z_][A-Za-z0-9_]*$/,bb=/\bDefault::default\b/g,sk=/^\.\.\s*Default::default\b/;function Sb(e,t){let n=new Map,r=new Map;for(let i of t){let o=Cd(e,i,r);o!==null&&n.set(i.symbolId,o)}return n}function Cd(e,t,n=new Map){let r=pk(t.symbol);if(!r)return null;let i=da(e,[t.symbolId]);if(i.length===0)return null;let o=new RegExp(`(^|[^A-Za-z0-9_])${Ge(r)}::default\\b`,"g"),s=new RegExp(`(^|[^A-Za-z0-9_])${Ge(r)}\\s*$`),a=mk(e,t.symbolId),c={owner:r,ownerDefaultCall:o,ownerLiteralBeforeBrace:s,canUseStructUpdateDefault:a},l=[];for(let u of i){let d=fk(e,u.relative_path,n);if(d===null)return null;let m=ak(u,d,c);if(m===null)return null;for(let p of m)l.push(p)}return za(l)}function ak(e,t,n){let r=t.split(/\r?\n/),i={braceDepth:0,ownerLiteralDepths:[]},o=[];for(let s=e.chunk_start;s<=e.chunk_end&&s<r.length;s+=1){let a=r[s]??"";for(let u of ck(e.relative_path,s,a,n))o.push(u);let c=lk(e.relative_path,s,a,n,i);for(let u of c)o.push(u);let l=new Set(c.map(u=>u.column));if(dk(a,l))return null}return o.length===0?null:o}function ck(e,t,n,{owner:r,ownerDefaultCall:i}){let o=[];i.lastIndex=0;let s;for(;s=i.exec(n);)o.push({file:e,line:t,column:s.index+s[1].length+r.length+2});return o}function lk(e,t,n,r,i){let o=[];for(let s=0;s<n.length;s+=1){let a=sk.exec(n.slice(s));if(a){r.canUseStructUpdateDefault&&i.ownerLiteralDepths.includes(i.braceDepth)&&o.push({file:e,line:t,column:s+a[0].lastIndexOf("default")}),s+=a[0].length-1;continue}uk(n,s,r.ownerLiteralBeforeBrace,i)}return o}function uk(e,t,n,r){let i=e[t];if(i==="{"){let o=n.test(e.slice(0,t));r.braceDepth+=1,o&&r.ownerLiteralDepths.push(r.braceDepth);return}if(i==="}")for(r.braceDepth=Math.max(0,r.braceDepth-1);r.ownerLiteralDepths.length>0&&r.ownerLiteralDepths[r.ownerLiteralDepths.length-1]>r.braceDepth;)r.ownerLiteralDepths.pop()}function dk(e,t){bb.lastIndex=0;let n;for(;n=bb.exec(e);)if(!t.has(n.index+9))return!0;return!1}function mk(e,t){return e.get("SELECT 1 AS present FROM mentions WHERE symbol_id = ? AND role = 1 LIMIT 1",t)?.present===1}function pk(e){let t=/impl#\[([^\]]+)\]\[Default\]default\(\)\./.exec(e)?.[1]??null;return!t||!ok.test(t)?null:t}function fk(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:gk(e,t);return n.set(t,i),i}function gk(e,t){try{return te(e.config.projectRoot,t,{inputKind:"indexed Rust source file"})}catch(n){if(!xe(n))throw n;return null}}var hk="typescript-import-usage-v1",yk="typescript-signatures-v2",xd=X("semantic-prefetched-callees",{clearGroups:["whole-project","source-file","semantic-provider"]}),vb=er({kind:"semantic-import-usage",invalidation:Re("semantic-import-usage"),serialize:e=>JSON.stringify(e),deserialize:Nb}),Cb=er({kind:"semantic-signatures",invalidation:Re("semantic-signatures"),serialize:e=>JSON.stringify(e),deserialize:Ak}),xb=rt({kind:"typescript-import-usage",invalidation:Re("typescript-import-usage"),serialize:e=>JSON.stringify(e),deserialize:Nb}),Rb=rt({kind:"typescript-signatures",invalidation:Re("typescript-signatures"),serialize:e=>JSON.stringify(e),deserialize:_k}),bk=256;function Eb(e,t={}){let n=t.coldFragmentLimit??bk,r=Gg(e);return r===null||r.missing<=n?{ready:!0}:(t.serviceAvailable??gb)(e)?{ready:!0}:{ready:!1,reason:`TypeScript reference fragments are cold for ${r.missing} of ${r.files} files and no watch service is running; start the service with \`scip-query watch --daemon\`, then re-run this command.`}}var Sk=X("typescript-reference-map",{clearGroups:["whole-project"]});function vk(e){return Sk.get(e,()=>{let t=nt(e);if(!t)return null;let n=Pe(e).filter(i=>Se(i.relativePath)==="typescript"),r=Su(e,n,i=>un(e,i));return r?{projectFingerprint:t,references:r.references,files:r.files,cacheHits:r.cacheHits,cacheMisses:r.cacheMisses,computedFiles:r.computedFiles}:null})}function Gt(e){let t=new Map,n=new Set;return{capability:(r,i)=>Ab(e,r,i),importUsage:r=>xk(e,r),references:r=>Pb(e,r),materializeReferences:(r,i)=>Lb(e,r,t,n,i),callerMap:r=>Rk(e,r,t,n),calleeMap:r=>Mk(e,r),signature:r=>kk(e,r)}}function Ck(e,t){if(t.size===0)return;let n=xd.get(e,()=>new Map);for(let[r,i]of t)n.set(r,[...i])}function Ib(e,t){if(!xd.has(e))return{hits:[],misses:[...t]};let n=xd.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 Ho(e,t){return Gt(e).importUsage(t)}function xk(e,t){if(Se(t)==="typescript"){let o="fallback",s=0,a=0,c=0,l=0;return M("typescript.import-usage.materialize",()=>{let u=go(e,t,hk);if(u?.key){s=1;let m=xb.read(e,t,u.key);if(m)return o="hit",a=1,m;c=1;let p=zt(e,t);if(!p)return o="unavailable",[];let f=p.importUsage(t);return xb.write(e,t,u.key,f),o="computed",f}l=1;let d=zt(e,t);return d?(o="direct-fallback",d.importUsage(t)):(o="unavailable",[])},()=>({state:o,eligible:s,cacheHits:a,cacheMisses:c,fallbacks:l}))}let n=kb(e,"semantic-import-usage",t);if(n){let o=vb.read(e,t,n);if(o)return o}let r=zt(e,t);if(!r)return[];let i=r.importUsage(t);return n&&vb.write(e,t,n,i),i}function wb(e,t){return Gt(e).references(t)}function Pb(e,t){let n=Cd(e,t);if(n)return n;let r=ty(e,t);if(r)return r;let i=zt(e,t.relativePath);return i?i.referencesFor(t):[]}function gi(e,t){return Gt(e).callerMap(t)}function Tb(e,t){let n=new Map,r=[];for(let i of t){if(Se(i.relativePath)==="typescript"){r.push(i);continue}Rd(e,n,i,Pb(e,i))}if(r.length>0){let i=jk(e,r);for(let o of r)Rd(e,n,o,i.get(o.symbolId)??[])}return n}function Rk(e,t,n=new Map,r=new Set){let i=new Map,o=Lb(e,t,n,r),s=0;return M("semantic.callers.from-references",()=>{for(let a of t)s+=Rd(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 Ek(e,t){let n=[];for(let r of e)t.materializedReferences.has(r.symbolId)?t.inMemoryHits+=1:t.incompleteReferences.has(r.symbolId)?t.incompleteInMemoryHits+=1:n.push(r);return n}function Ik(e,t,n,r,i){let o=Ek(r,i);if(o.length===0){i.fullyInMemoryFiles+=1;return}let s=Pk(e,t,n);if(!s){for(let c of o)Se(c.relativePath)||(i.skippedUnsupportedLanguage+=1),i.unkeyed.push(c);return}i.cacheReadFiles+=1;let a=Wf(e,n,s);for(let c of o)wk(c,a.get(c.symbol)??null,s,i)}function wk(e,t,n,r){if(t!==null){let i=Lk(t);if(i){r.cacheHits+=1,r.materializedReferences.set(e.symbolId,i);return}r.parseFailures+=1}r.misses.push({definition:e,cacheFingerprint:n})}function Lb(e,t,n,r,i={}){let o=nt(e),s=[],a=[],c=[],l={skippedUnsupportedLanguage:0,inMemoryHits:0,cacheHits:0,parseFailures:0,cacheReadFiles:0,fullyInMemoryFiles:0,incompleteInMemoryHits:0,materializedReferences:n,incompleteReferences:r,misses:a,unkeyed:c},u=0,d=0,m=0,p=0,f=0,g=[],h=new Map,y=t.filter(I=>Se(I.relativePath)==="typescript"&&!n.has(I.symbolId)&&!r.has(I.symbolId)),S=y.length>0?vk(e):null;if(S){d=y.length,m=S.cacheHits,p=S.cacheMisses,f=S.computedFiles;for(let I of y)n.set(I.symbolId,S.references.get(I.symbolId)??[])}return M("semantic.references.cache-scan",()=>{for(let[I,x]of Ha(t))Ik(e,o,I,x,l)},()=>({definitions:t.length,skippedUnsupportedLanguage:l.skippedUnsupportedLanguage,cacheHits:l.cacheHits,parseFailures:l.parseFailures,misses:a.length,unkeyed:c.length,inMemoryHits:l.inMemoryHits,incompleteInMemoryHits:l.incompleteInMemoryHits,fullyInMemoryFiles:l.fullyInMemoryFiles,cacheReadFiles:l.cacheReadFiles})),(a.length>0||c.length>0)&&(g=[...c,...a.map(I=>I.definition)],h=M("semantic.references.compute-misses",()=>{let I=Ed(e,g,i);return u=I.size,I},()=>({definitions:g.length,misses:a.length,unkeyed:c.length,rows:u})),Ok(e,g,h,n,r,a,s)),s.length>0&&M("semantic.references.cache-write",()=>Vf(e,s),()=>({entries:s.length})),h.size>0&&bu(e,g,h,I=>un(e,I)),{definitions:t.length,inMemoryHits:l.inMemoryHits,incompleteInMemoryHits:l.incompleteInMemoryHits,cacheHits:l.cacheHits,misses:a.length,unkeyed:c.length,skippedUnsupportedLanguage:l.skippedUnsupportedLanguage,parseFailures:l.parseFailures,computed:u,incomplete:r.size,cacheWrites:s.length,fragmentDefinitions:d,fragmentCacheHits:m,fragmentCacheMisses:p,fragmentComputedFiles:f}}function Pk(e,t,n){if(!t)return null;let r=Se(n);return r==="typescript"?t:r==="rust"?At(JSON.stringify({kind:"semantic-references",language:r,engine:lr(e.config.projectRoot),projectFingerprint:t})):null}function Ed(e,t,n={}){let r=fe(),i=new Map,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=0,p=0,f=(E,b)=>{Tk(i,E,b,r,v=>{d+=1,m+=v})},g=(E,b)=>{for(let v of b)E.has(v.symbolId)&&f(v.symbolId,E.get(v.symbolId)??[])},h=(E,b,v)=>{let C=E.get(b);C?C.push(v):E.set(b,[v])},y=(E,b,v)=>{b?.referencesAndCalleesForDefinitions&&(h(E,b,v),p+=1)},S=(E,b,v)=>{let C=b.get(E.symbolId);if(C)return a+=1,c+=C.length,f(E.symbolId,C),!0;let R=v.get(E.symbolId);return R?(l+=1,u+=R.length,f(E.symbolId,R),!0):!1},I=(E,b)=>{let v=new Map,C=n.prefetchCallees?new Map:null,R=[];for(let P of t){let w,T=()=>(w??=zt(e,P.relativePath),w);if(C&&y(C,T(),P),S(P,E,b))continue;let G=T();if(!G){r&&(s+=1);continue}r&&(o+=1),Hk(G,P,v,R)}return{bulkGroups:v,prefetchCalleeGroups:C,scalarDefinitions:R}},x=E=>{let b=new Set;if(!E.prefetchCalleeGroups)return b;for(let[v,C]of E.prefetchCalleeGroups){if(!v.referencesAndCalleesForDefinitions)continue;let R=E.bulkGroups.get(v)??[],P=v.referencesAndCalleesForDefinitions(R,C);b.add(v),Ck(e,P.callees),g(P.references,R)}return b};return M("semantic.references.provider-loop",()=>{let E=Sb(e,t),b=ey(e,t),v=I(E,b),C=x(v);for(let[R,P]of v.bulkGroups)C.has(R)||g(R.referencesForDefinitions(P),P);for(let{provider:R,definition:P}of v.scalarDefinitions)f(P.symbolId,R.referencesFor(P));return i},()=>({definitions:t.length,providerHits:o,providerMisses:s,rustDefaultFastPathRows:a,rustDefaultFastPathReferences:c,rustScipOccurrenceFastPathRows:l,rustScipOccurrenceFastPathReferences:u,prefetchCalleeDefinitions:p,definitionsWithReferences:d,referenceCount:m,rows:i.size}))}function Tk(e,t,n,r,i){e.set(t,n),r&&n.length>0&&i(n.length)}function Rd(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 Lk(e){try{return JSON.parse(e)}catch{return null}}function Mb(e,t){return Gt(e).calleeMap(t)}function Mk(e,t){let n=fe(),r=new Map,i=0,o=0,s=0,a=0;return M("semantic.callees.provider-loop",()=>{let c=new Map,l=[];for(let u of t){let d=zt(e,u.relativePath);if(!d){n&&(o+=1);continue}n&&(i+=1);let m=u;d.calleesForDefinitions?$k(c,d,m):l.push({provider:d,definition:m})}Bk(c,r,n,u=>{s+=1,a+=u});for(let{provider:u,definition:d}of l){let m=u.calleesFor(d);Db(r,d.symbolId,m,n,p=>{s+=1,a+=p})}return r},()=>({definitions:t.length,providerHits:i,providerMisses:o,definitionsWithCallees:s,calleeCount:a,rows:r.size}))}var Dk=256;function Fk(e){let t=new Map;for(let i of e){let o=t.get(i.relativePath);o?o.push(i):t.set(i.relativePath,[i])}let n=[],r=[];for(let i of t.values())r.length>0&&r.length+i.length>Dk&&(n.push(r),r=[]),r.push(...i);return r.length>0&&n.push(r),n}function Db(e,t,n,r,i){n.length>0&&(e.set(t,n),r&&i(n.length))}function Fb(e,t){return Gt(e).signature(t)}function kk(e,t){if(Se(t.relativePath)==="typescript"){let s="fallback",a=0,c=0,l=0,u=0;return M("typescript.signature.materialize",()=>{let d=go(e,t.relativePath,yk);if(d?.key){a=1;let p=Rb.read(e,t.relativePath,d.key)??{};if(Object.prototype.hasOwnProperty.call(p,t.symbol))return s="hit",c=1,p[t.symbol]??null;l=1;let f=zt(e,t.relativePath);if(!f)return s="unavailable",null;let g=f.signatureFor(t);return Rb.write(e,t.relativePath,d.key,{...p,[t.symbol]:g}),s="computed",g}u=1;let m=zt(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=kb(e,"semantic-signatures",t.relativePath),r=Nk(t);if(n){let s=Cb.read(e,r,n);if(s)return s.signature}let i=zt(e,t.relativePath);if(!i)return null;let o=i.signatureFor(t);return n&&Cb.write(e,r,n,{signature:o}),o}function kb(e,t,n){let r=nt(e);if(!r)return null;let i=Se(n);return i!=="rust"?null:At(JSON.stringify({kind:t,language:i,engine:lr(e.config.projectRoot),projectFingerprint:r}))}function Nk(e){return`${e.relativePath}\0${e.symbol}`}function Nb(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:null}catch{return null}}function Ak(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 _k(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 Ab(e,t,n){let r=Se(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,...un(e,n).availability()}}catch(i){return{slot:t,language:r,available:!1,reason:i instanceof Error?i.message:String(i)}}}function zt(e,t){if(!Se(t))return null;let n=un(e,t);return n.availability().available?n:null}function Ok(e,t,n,r,i,o,s){for(let a of t)n.has(a.symbolId)?(r.set(a.symbolId,n.get(a.symbolId)??[]),i.delete(a.symbolId)):i.add(a.symbolId);for(let{definition:a,cacheFingerprint:c}of o)n.has(a.symbolId)&&Ab(e,"semantic-references",a.relativePath).available&&s.push({relativePath:a.relativePath,symbol:a.symbol,projectFingerprint:c,payload:JSON.stringify(n.get(a.symbolId)??[])})}function Bk(e,t,n,r){for(let[i,o]of e)for(let s of Fk(o)){let a=i.calleesForDefinitions(s);for(let c of s){let l=a.get(c.symbolId)??[];Db(t,c.symbolId,l,n,u=>{r(u)})}}}function $k(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function jk(e,t){let r=Su(e,t,i=>un(e,i))?.references;if(!r){let i=zt(e,t[0].relativePath);r=i?i.referencesForDefinitions?i.referencesForDefinitions(t,{exact:!0}):new Map(t.map(o=>[o.symbolId,i.referencesFor(o)])):new Map,i&&fe()&&bu(e,t,r,o=>un(e,o))}return r}function Hk(e,t,n,r){if(e.referencesForDefinitions){let i=n.get(e);i?i.push(t):n.set(e,[t])}else r.push({provider:e,definition:t})}var ie={references:wb,referenceMap:Ed,callerMap:(e,t)=>Gt(e).callerMap(t),calleeMap:Id};function Id(e,t){let n=fe(),r=new Map,i=Ib(e,t),o=[],s=[],a=0,c=0,l=0,u=0,d=0,m=0,p=0;for(let{definition:b,callees:v}of i.hits)d+=1,v.length>0&&(m+=1,p+=v.length,r.set(b.symbolId,v));let f=Uk(e,i.hits);f.entries.length>0&&M("semantic.callees.prefetch-cache-write",()=>iu(e,f.entries),()=>({entries:f.entries.length,sourceMissing:f.sourceMissing,skippedUnsupportedLanguage:f.skippedUnsupportedLanguage}));function g(b,v){if(!Se(b)){n&&(a+=v.length);return}let C=H(e,b);if(!C){n&&(c+=v.length),s.push(...v);return}let R=bt(e,b,C),P=_b(e,b);if(!P){s.push(...v);return}let w=Kf(e,b,R,P);h(v,w,R,P)}function h(b,v,C,R){for(let P of b){let w=v.get(P.symbol)??null;y(P,w)||o.push({def:P,contentHash:C,depsDigest:R})}}function y(b,v){if(v===null)return!1;let C=zk(v);return C?(n&&(l+=1),C.length>0&&r.set(b.symbolId,C),!0):(n&&(u+=1),!1)}if(M("semantic.callees.cache-scan",()=>{for(let[b,v]of Ha(i.misses))g(b,v)},()=>({definitions:t.length,skippedUnsupportedLanguage:a,sourceMissing:c,cacheHits:l,parseFailures:u,misses:o.length,unkeyed:s.length,inMemoryHits:d,inMemoryRows:m,inMemoryCalleeCount:p,resultRows:r.size,missSample:o.slice(0,8).map(b=>`${b.def.relativePath}#${b.def.symbol}`),unkeyedSample:s.slice(0,4).map(b=>`${b.relativePath}#${b.symbol}`)})),o.length===0&&s.length===0)return r;let S=[...s,...o.map(b=>b.def)],I=0,x=M("semantic.callees.compute-misses",()=>{let b=Mb(e,S);return I=b.size,b},()=>({definitions:S.length,misses:o.length,unkeyed:s.length,rows:I}));for(let[b,v]of x)r.set(b,v);let E=o.filter(b=>Gt(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(x.get(b.def.symbolId)??[])}));return E.length>0?M("semantic.callees.cache-write",()=>iu(e,E),()=>({entries:E.length})):M("semantic.callees.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",misses:o.length})),r}function Uk(e,t){let n=[],r=new Map,i=0,o=0;for(let{definition:s,callees:a}of t){if(!Se(s.relativePath)){o+=1;continue}if(!r.has(s.relativePath)){let l=H(e,s.relativePath),u=l?_b(e,s.relativePath):null;r.set(s.relativePath,l&&u?{contentHash:bt(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 qk="typescript-callees-v4-lexical-owner";function _b(e,t){let n=Se(t);if(n==="typescript")return go(e,t,qk)?.key??null;let r=Kk(e,t);return n==="rust"?At(JSON.stringify({kind:"semantic-callees",language:n,engine:lr(e.config.projectRoot),positionMapping:"nearby-leaf-v2-callsite-line",depsDigest:r})):r}function zk(e){try{return JSON.parse(e)}catch{return null}}var Gk=Hr("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function Kk(e,t){return Gk.get(e,t,()=>{let r=[...Fe(e).get(t)??[]].sort().map(i=>`${i}:${bt(e,i,H(e,i))}`);return At(r.join("|"))})}function bue(e,t,n={}){let r=Bt(e,t);if(!r)return[];let o=!be(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine,evidence:"indexed-definition"}]:[],s=Tg(e,r,{semantic:n.semantic,semanticEvidence:ie}).map(l=>Wk(e,r.symbol,l.file,l.line)),a=new Set,c=[];for(let l of[...o,...s]){let u=`${l.relativePath}:${l.line}`;a.has(u)||(a.add(u),c.push(l))}return c}function Wk(e,t,n,r){return{relativePath:n,line:r,evidence:Yr(e,n,t)?.includes(r)?"indexed-occurrence":"source-or-chunk-candidate"}}import{existsSync as Hd,statSync as N0}from"fs";import{join as A0}from"path";function Uo(e,t,n){e!==void 0&&typeof e!="boolean"&&n.push({level:"error",path:t,message:"Must be a boolean."})}function Za(e,t){if(e.architecture===void 0)return;if(!k(e.architecture)){t.push({level:"error",path:"architecture",message:"Must be an object."});return}let n=e.architecture,r=n.boundaries;if(!Array.isArray(r)||r.length===0){t.push({level:"error",path:"architecture.boundaries",message:"Must be a non-empty array."});return}let i={names:new Set,paths:new Set};for(let[o,s]of r.entries())Vk(s,`architecture.boundaries[${o}]`,i,t);Yk(n.allowedDependencies,i.names,t),Qk(n,t),Zk(n,i.names,t)}function Vk(e,t,n,r){if(!k(e)){r.push({level:"error",path:t,message:"Architecture boundary must be an object."});return}let i=e.name;typeof i!="string"||i.trim()===""?r.push({level:"error",path:`${t}.name`,message:"Boundary name is required."}):n.names.has(i)?r.push({level:"error",path:`${t}.name`,message:`Duplicate boundary name: ${i}`}):n.names.add(i);let o=e.subUnits;o!==void 0&&o!=="directory"&&o!=="file"&&r.push({level:"error",path:`${t}.subUnits`,message:"Must be 'directory' or 'file'."}),Ob(e.maxFiles,`${t}.maxFiles`,r),Jk(e.paths,`${t}.paths`,n.paths,r)}function Jk(e,t,n,r){if(!Array.isArray(e)||e.length===0){r.push({level:"error",path:t,message:"Boundary paths must be a non-empty array."});return}for(let[i,o]of e.entries()){let s=`${t}[${i}]`;if(typeof o!="string"||o.trim()===""){r.push({level:"error",path:s,message:"Boundary path must be a non-empty string."});continue}eN(o)||r.push({level:"error",path:s,message:"Boundary path must be project-relative and may use only one trailing /* or /** glob."}),n.has(o)?r.push({level:"error",path:s,message:`Duplicate boundary path: ${o}`}):n.add(o)}}function Yk(e,t,n){if(e!==void 0){if(!k(e)){n.push({level:"error",path:"architecture.allowedDependencies",message:"Must be an object keyed by boundary name."});return}for(let[r,i]of Object.entries(e))Xk(r,i,t,n)}}function Xk(e,t,n,r){let i=`architecture.allowedDependencies.${e}`;if(n.has(e)||r.push({level:"error",path:i,message:`Unknown source boundary: ${e}`}),!Array.isArray(t)){r.push({level:"error",path:i,message:"Dependency row must be an array."});return}let o=new Set;for(let[s,a]of t.entries()){let c=`${i}[${s}]`;typeof a!="string"||a.trim()===""?r.push({level:"error",path:c,message:"Target boundary name is required."}):n.has(a)?o.has(a)?r.push({level:"error",path:c,message:`Duplicate target boundary: ${a}`}):o.add(a):r.push({level:"error",path:c,message:`Unknown target boundary: ${a}`})}}function Qk(e,t){for(let r of["requireAcyclic","requireCompleteCoverage","requireResolvedBoundaries","requireMinimalPolicy"])Uo(e[r],`architecture.${r}`,t);for(let r of["maxBoundaryFanOut","maxBoundaryFiles"])Ob(e[r],`architecture.${r}`,t);let n=e.testPaths;n!==void 0&&(!Array.isArray(n)||n.some(r=>typeof r!="string"))&&t.push({level:"error",path:"architecture.testPaths",message:"Must be an array of strings."})}function Zk(e,t,n){if(Uo(e.requireCompletePolicy,"architecture.requireCompletePolicy",n),e.requireCompletePolicy!==!0)return;let r=k(e.allowedDependencies)?e.allowedDependencies:{};for(let i of[...t].sort())Object.hasOwn(r,i)||n.push({level:"error",path:`architecture.allowedDependencies.${i}`,message:"A dependency row is required by architecture.requireCompletePolicy."})}function Ob(e,t,n){e!==void 0&&(typeof e!="number"||!Number.isInteger(e)||e<0)&&n.push({level:"error",path:t,message:"Must be a non-negative integer."})}function eN(e){let t=e.replace(/\\/g,"/");if(/^(?:\/|[a-z]:)/i.test(t)||t==="."||t===".."||t.split("/").includes(".."))return!1;let n=t.replace(/\/\*\*?$/,"");return n.length>0&&!/[*?[\]]/.test(n)}import{existsSync as yi}from"fs";import{randomUUID as rS}from"crypto";import{isAbsolute as lA,join as mn,relative as uA,resolve as dA}from"path";var kn=1,Nn=2,tN="./node_modules/scip-query/docs/schemas/project-config.schema.json";function mr(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(n){return{kind:"malformed",reason:`invalid JSON: ${n instanceof Error?n.message:String(n)}`}}return k(t)?nN(t):{kind:"malformed",reason:"project config must be a JSON object"}}function nN(e){let t=e.schemaVersion;if(t!==void 0&&!Number.isInteger(t))return{kind:"malformed",reason:"schemaVersion must be an integer"};let n=t===void 0?kn:t;return n!==kn&&n!==Nn?{kind:"unsupported",schemaVersion:n,direction:n<kn?"older":"future"}:rN(e,n)}function rN(e,t){let n=e.$schema;if(n!==void 0&&(typeof n!="string"||n.trim()===""))return{kind:"malformed",reason:"$schema must be a non-empty string when present"};let r=ec(e),i=t!==Nn||typeof e.$schema!="string";return t===kn?{kind:"legacy",sourceVersion:kn,config:r,needsMigration:i}:{kind:"supported",sourceVersion:Nn,config:r,needsMigration:i}}function ec(e){let t=e,{$schema:n,schemaVersion:r,...i}=t;return{$schema:typeof n=="string"&&n.trim()!==""?n:tN,schemaVersion:Nn,...i}}function hi(e){return`${JSON.stringify(ec(e),null,2)}
|
|
16
|
+
`}import{createHash as iN}from"crypto";var Wt=1,An=2,Ub=1,Td=1,wd="sha256",oN=1;function fr(e,t,n){if(!wt(e)||!Js(t))throw new Error("Observation identity requires a bounded projection name and positive projection version.");return{schemaVersion:Ub,canonicalizationVersion:Td,hashAlgorithm:wd,projection:{name:e,version:t},digest:iN(wd).update(sN(e,t,n)).digest("hex")}}function sN(e,t,n){return`{"canonicalizationVersion":${Td},"projection":${JSON.stringify(e)},"projectionVersion":${t},"value":${JSON.stringify(n)}}`}function aN(e){if(!k(e))return{kind:"malformed",reason:"observation receipt must be an object"};let t=e.schemaVersion;if(!Number.isInteger(t))return{kind:"malformed",reason:"observation receipt schemaVersion must be an integer"};if(t===Wt)return fN(e)?{kind:"legacy",schemaVersion:Wt,receipt:e}:{kind:"malformed",reason:"observation receipt v1 fields are malformed or contradictory"};if(t===An)return yN(e)?{kind:"supported",schemaVersion:An,receipt:e}:{kind:"malformed",reason:"observation receipt v2 facts are malformed or contradictory"};let n=t;return{kind:"unsupported",schemaVersion:n,direction:n<Wt?"older":"future"}}function tc(e){let t=aN(e);return t.kind==="legacy"||t.kind==="supported"}function cN(e,t){return{collaborationDomain:pr(Kt(e,n=>n.facts.collaborationDomain),Kt(t,n=>n.facts.collaborationDomain)),repositoryLineage:pr(Kt(e,n=>n.facts.repositoryLineage),Kt(t,n=>n.facts.repositoryLineage)),workspaceInstance:pr(Kt(e,n=>n.facts.workspaceInstance),Kt(t,n=>n.facts.workspaceInstance)),wholeContent:pr(Kt(e,n=>n.facts.wholeContent),Kt(t,n=>n.facts.wholeContent)),relevantInputs:lN(e,t),indexInput:pr(Kt(e,n=>n.facts.index?.inputs),Kt(t,n=>n.facts.index?.inputs)),indexGeneration:uN(e,t),observationStability:mN(e,t)}}function Tue(e,t,n=cN(e,t)){let r=[["collaborationDomain",n.collaborationDomain],["wholeContent",n.wholeContent],["observationStability",n.observationStability]],i=[];for(let[s,a]of r)a.state!=="established"&&i.push(`${s}:${a.state}`);for(let[s,a]of[["left",e],["right",t]]){let c=pN(a);c!=="not-applicable"&&c!=="established"&&i.push(`${s}IndexAlignment:${c}`)}let o=r.some(([,s])=>s.state==="disproven")||i.some(s=>s.endsWith(":disproven"));return{policyVersion:oN,authority:i.length===0?"completion":o?"none":"advisory",requiredRelationships:["collaborationDomain","wholeContent","observationStability"],reasons:i}}function lN(e,t){let n=Bb(e),r=Bb(t);return[...new Set([...n.keys(),...r.keys()])].sort().map(o=>{let s=n.get(o),a=r.get(o),c=s?.subject??a?.subject??o,l=s?.identity.projection.name??a?.identity.projection.name??o;return{subject:c,projection:l,judgment:pr(s?.identity,a?.identity)}})}function Bb(e){return e.schemaVersion!==An?new Map:new Map((e.facts.relevantInputs??[]).map(t=>[`${t.subject}\0${t.identity.projection.name}`,t]))}function uN(e,t){return e.schemaVersion===Wt&&t.schemaVersion===Wt?dN(e.index?.generationIdentity,t.index?.generationIdentity):e.schemaVersion===Wt||t.schemaVersion===Wt?dn("unknown",["legacy-fact-not-comparable"],jb(e),jb(t)):pr(e.facts.index?.generation,t.facts.index?.generation)}function dN(e,t){let n=e?[{kind:"legacy-index-generation",value:e}]:[],r=t?[{kind:"legacy-index-generation",value:t}]:[];return e===void 0||t===void 0?qb(n,r):dn(e===t?"established":"disproven",[e===t?"identities-equal":"identities-different"],n,r)}function pr(e,t){let n=e?[{kind:"identity",identity:e}]:[],r=t?[{kind:"identity",identity:t}]:[];return!e||!t?qb(n,r):Ld(e,t)?dn(e.digest===t.digest?"established":"disproven",[e.digest===t.digest?"identities-equal":"identities-different"],n,r):dn("unknown",["identity-projections-not-comparable"],n,r)}function mN(e,t){if(e.schemaVersion===Wt||t.schemaVersion===Wt)return dn("unknown",["legacy-fact-not-comparable"],[],[]);let n=Hb(e),r=Hb(t),i=$b(e),o=$b(t);return i==="invalidated"||o==="invalidated"?dn("disproven",[...i==="invalidated"?["left-observation-invalidated"]:[],...o==="invalidated"?["right-observation-invalidated"]:[]],n,r):i!=="fixed"||o!=="fixed"?dn("unknown",DN(i,o),n,r):dn("established",["all-observed-sources-fixed"],n,r)}function $b(e){let t=e.observedSources.filter(r=>r.kind!=="process");if(t.length===0)return"no-repository-source";let n=new Map(e.stabilityProofs.map(r=>[r.source,r.kind]));return t.some(r=>n.get(r.kind)==="invalidated")?"invalidated":t.every(r=>{let i=n.get(r.kind);return i==="immutable"||i==="fixed-snapshot"})?"fixed":"unknown"}function pN(e){if(e.schemaVersion!==An)return e.index?"unknown":"not-applicable";if(!e.observedSources.some(r=>r.kind==="index-generation"))return"not-applicable";let t=e.facts.index?.inputs;if(!t)return"unknown";let n=(e.facts.relevantInputs??[]).find(r=>Ld(r.identity,t))?.identity;return n?n.digest===t.digest?"established":"disproven":"unknown"}function Kt(e,t){return e.schemaVersion===An?t(e):void 0}function jb(e){return e.schemaVersion===Wt&&e.index?[{kind:"legacy-index-generation",value:e.index.generationIdentity}]:e.schemaVersion===An&&e.facts.index?[{kind:"identity",identity:e.facts.index.generation}]:[]}function Hb(e){return e.stabilityProofs.map(t=>({kind:"stability",proof:t}))}function qb(e,t){let n=e.length===0&&t.length===0?"both-facts-missing":e.length===0?"left-fact-missing":"right-fact-missing";return dn("unknown",[n],e,t)}function dn(e,t,n,r){return{state:e,reasons:t,facts:{left:n,right:r}}}function Ld(e,t){return e.schemaVersion===t.schemaVersion&&e.canonicalizationVersion===t.canonicalizationVersion&&e.hashAlgorithm===t.hashAlgorithm&&e.projection.name===t.projection.name&&e.projection.version===t.projection.version}function fN(e){if(!k(e))return!1;let t=e.index,n=e.worktree;return $r(e.observedAt)&&wt(e.projectIdentity)&&MN(e.authorityKind)&&gN(t)&&hN(n)&&LN(e.authorityKind,t,n)}function gN(e){return e===void 0||k(e)&&wt(e.generationIdentity)&&(e.source==="immutable"||e.source==="legacy")&&(e.alignment==="not-certified"||e.alignment==="leased")}function hN(e){return e===void 0||k(e)&&wt(e.identity)&&typeof e.clean=="boolean"&&(e.headCommit===void 0||wt(e.headCommit))&&(e.treeOid===void 0||wt(e.treeOid))}function yN(e){if(!k(e))return!1;let t=e.facts,n=e.observedSources;return!$r(e.observedAt)||!k(t)||!bN(n)||!SN(e.stabilityProofs,n,t)||!vN(t)?!1:RN(e.diagnostics)&&PN(t,n)}function bN(e){return Array.isArray(e)&&e.length>0&&e.every(IN)&&Md(e,t=>t.kind)}function SN(e,t,n){return Array.isArray(e)&&e.every(wN)&&Md(e,r=>r.source)&&!e.some(r=>!t.some(i=>i.kind===r.source))&&e.every(r=>TN(r,n))}function vN(e){return["collaborationDomain","repositoryLineage","workspaceInstance","wholeContent"].some(n=>e[n]!==void 0&&!_n(e[n]))?!1:CN(e.relevantInputs)&&xN(e.index)}function CN(e){return e===void 0||Array.isArray(e)&&e.every(EN)&&Md(e,t=>`${t.subject}\0${t.identity.projection.name}`)}function xN(e){return e===void 0||k(e)&&_n(e.generation)&&(e.inputs===void 0||_n(e.inputs))&&(e.source==="immutable"||e.source==="legacy")}function RN(e){return e===void 0||k(e)&&(e.clean===void 0||typeof e.clean=="boolean")&&(e.headCommit===void 0||wt(e.headCommit))&&(e.treeOid===void 0||wt(e.treeOid))}function _n(e){return!k(e)||!k(e.projection)?!1:e.schemaVersion===Ub&&e.canonicalizationVersion===Td&&e.hashAlgorithm===wd&&wt(e.projection.name)&&Js(e.projection.version)&&jr(e.digest)}function EN(e){return k(e)&&wt(e.subject)&&_n(e.identity)}function IN(e){return k(e)&&zb(e.kind)&&(e.identity===void 0||_n(e.identity))}function wN(e){return k(e)&&zb(e.source)&&(e.kind==="immutable"||e.kind==="fixed-snapshot"||e.kind==="bracketed"||e.kind==="not-established"||e.kind==="invalidated")}function PN(e,t){let n=e.index,r=t.find(c=>c.kind==="index-generation");if(!FN(n,r))return!1;let i=e.workspaceInstance,o=t.find(c=>c.kind==="live-workspace");if(o?.identity&&(!_n(i)||!Pd(o.identity,i)))return!1;let s=e.wholeContent,a=t.find(c=>c.kind==="repository-snapshot");return!(a?.identity&&(!_n(s)||!Pd(a.identity,s)))}function TN(e,t){return e.kind==="not-established"||e.kind==="invalidated"?!0:e.source==="index-generation"?e.kind==="immutable"&&k(t.index)&&t.index.source==="immutable":e.source==="repository-snapshot"?e.kind==="fixed-snapshot":e.source==="live-workspace"?e.kind==="bracketed":!1}function Pd(e,t){return Ld(e,t)&&e.digest===t.digest}function LN(e,t,n){return e==="index-worktree"?t!==void 0&&n!==void 0:e==="index-only"?t!==void 0&&n===void 0:e==="worktree-only"?t===void 0&&n!==void 0:e==="process-local"&&t===void 0&&n===void 0}function MN(e){return e==="index-worktree"||e==="index-only"||e==="worktree-only"||e==="process-local"}function zb(e){return e==="index-generation"||e==="repository-snapshot"||e==="live-workspace"||e==="process"}function Md(e,t){return new Set(e.map(t)).size===e.length}function DN(e,t){return[...e==="no-repository-source"?["left-observation-has-no-repository-source"]:e!=="fixed"?["left-observation-not-fixed"]:[],...t==="no-repository-source"?["right-observation-has-no-repository-source"]:t!=="fixed"?["right-observation-not-fixed"]:[]]}function FN(e,t){if(t){if(!k(e)||!_n(e.generation)||t.identity&&!Pd(t.identity,e.generation))return!1}else if(e!==void 0)return!1;return!0}var kN=100,NN=25,AN=.9;function Gb(e,t){return e>kN||t>=NN&&e/t>AN}function qo(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return _N(t)&&ON(t)&&BN(t)}function _N(e){return e.kind==="automated-adjudication"&&e.policyVersion===1&&(e.decidedBy==="agent"||e.decidedBy==="human")&&ru.includes(e.reasonCode)}function ON(e){return Array.isArray(e.evidence)&&e.evidence.length>0&&e.evidence.every(GN)&&(e.observation===void 0||tc(e.observation))}function BN(e){return!!e.invalidateOn&&typeof e.invalidateOn=="object"&&typeof e.invalidateOn.targetContentChange=="boolean"&&typeof e.invalidateOn.detectorMajorChange=="boolean"}function Kb(e,t,n){if(e.expiresAt&&Date.parse(e.expiresAt)<=n.now)return{kind:"expired",reasons:["suppression-expired"]};let r=e.id===t.id?[]:["exact-finding-id-required"],i=e.decision;if(!i)return{kind:"escalated",reasons:[...r,"legacy-unadjudicated"]};r.push(...$N(i));let o=i.evidence.filter(UN);r.push(...jN(i,t,o));let s=HN(o,n);return s.invalidated.length>0?{kind:"invalidated",reasons:s.invalidated}:(r.push(...s.missingHashes),zN(t)&&!i.evidence.some(qN)&&r.push("direct-counterevidence-required"),r.length===0?{kind:"accepted"}:{kind:"escalated",reasons:[...new Set(r)]})}function $N(e){let t=[];return e.kind!=="automated-adjudication"&&t.push("unsupported-decision-kind"),e.policyVersion!==1&&t.push("unsupported-policy-version"),ru.includes(e.reasonCode)||t.push("unsupported-reason-code"),e.evidence.length===0&&t.push("counterevidence-required"),e.invalidateOn.detectorMajorChange||t.push("detector-change-invalidation-required"),t}function jN(e,t,n){let r=[];e.invalidateOn.targetContentChange&&n.length===0&&r.push("content-invalidation-evidence-required");let i=new Set(t.targetFiles??(t.file?[t.file]:[])),o=new Set(n.filter(s=>s.contentHash).map(s=>s.referent));for(let s of i)o.has(s)||r.push(`target-content-evidence-required:${s}`);return r}function HN(e,t){let n=[],r=[];for(let i of e){if(!i.contentHash){n.push(`counterevidence-content-hash-required:${i.referent}`);continue}let o=t.contentHash(i.referent);(!o||o!==i.contentHash)&&r.push(`counterevidence-content-changed:${i.referent}`)}return{missingHashes:n,invalidated:r}}function UN(e){return e.kind==="source"||e.kind==="config"||e.kind==="test"}function qN(e){return e.kind==="source"||e.kind==="config"||e.kind==="graph"}function zN(e){return e.actionTier==="direct"||e.evidence==="graph-fact"||e.evidence==="change-graph"||e.evidence==="baseline"}function GN(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return KN(t)&&WN(t)}function KN(e){return(e.kind==="source"||e.kind==="config"||e.kind==="test"||e.kind==="graph")&&typeof e.referent=="string"&&e.referent.trim()!==""&&typeof e.claim=="string"&&e.claim.trim()!==""}function WN(e){return(e.contentHash===void 0||/^[a-f0-9]{64}$/u.test(e.contentHash))&&(e.generation===void 0||typeof e.generation=="string"&&e.generation.length>0)}var nc=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 gr(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 nc(t,e.length,r);return new RegExp(e,n)}import{createHash as Wb}from"crypto";import{closeSync as VN,fstatSync as Vb,lstatSync as JN,openSync as YN,readlinkSync as XN,realpathSync as QN,rmSync as ZN}from"fs";import{dirname as Xb,resolve as eA}from"path";var tA=2e3,nA=10,rA=3,ic=class extends Error{constructor(n,r,i){super(`Concurrent edit detected for ${n}; expected revision ${Yb(r)}, but found ${Yb(i)}. The latest file was left untouched.`);this.path=n;this.original=r;this.latest=i;this.name="FileRevisionConflictError"}path;original;latest},zo=class extends Error{constructor(n,r){super(`Concurrent edit detected for ${n}: ${r} changed since it was read. The latest file was left untouched; reload it and retry.`);this.path=n;this.field=r;this.name="FileContentConflictError"}path;field};function Go(e,t,n={}){let r=iA(e),i=oA(r,n.lockTimeoutMs??tA,n.monotonicNow??Ct);try{let o=Math.max(0,Math.floor(n.maxRetries??rA));for(let s=0;;s+=1){let a=rc(r),c=t(a,s);if(c.kind==="unchanged")return{changed:!1,attempts:s+1,previous:a,current:a};n.onBeforeCommit?.({attempt:s,snapshot:a,mutation:c});let l=rc(r);if(!aA(a.revision,l.revision)){if(s<o)continue;throw new ic(r,a.revision,l.revision)}if(cA(r,c,a.revision,s,o))return{changed:!0,attempts:s+1,previous:a,current:rc(r)}}}finally{i.release()}}function iA(e){let t;try{if(!JN(e).isSymbolicLink())return e;t=XN(e)}catch{return e}try{return QN(e)}catch{return eA(Xb(e),t)}}function rc(e){for(let t=0;t<4;t+=1){let n;try{n=YN(e,"r");let r=Jb(Vb(n)),i=Tf(n,{maxBytes:rn,inputKind:"revisioned text file"}),o=Jb(Vb(n));if(!Qb(r,o))continue;return{path:e,text:i,revision:{exists:!0,hash:Wb("sha256").update(i).digest("hex"),identity:o}}}catch(r){if(r.code==="ENOENT")return{path:e,text:"",revision:{exists:!1,hash:Wb("sha256").update("").digest("hex")}};throw r}finally{n!==void 0&&VN(n)}}throw new Error(`Could not read a stable revision of ${e}; the file is changing continuously.`)}function oA(e,t,n){let r=`${e}.scip-query-write.lock`,i=n()+Math.max(0,t);for(;;){let o=Ia(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,nA)}}function sA(e,t,n){if(t.kind==="delete"){if(!n.exists)return;ZN(e),Nf(Xb(e));return}let r=t.mode??n.identity?.mode;n.exists?Bg(e,t.text,{durability:"durable",mode:r}):$g(e,t.text,{durability:"durable",mode:r})}function aA(e,t){return e.exists===t.exists&&e.hash===t.hash&&(e.identity===void 0?t.identity===void 0:t.identity!==void 0&&Qb(e.identity,t.identity))}function Jb(e){return{dev:e.dev,ino:e.ino,size:e.size,mtimeMs:e.mtimeMs,mode:e.mode&511}}function Qb(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.mode===t.mode}function Yb(e){return e.exists?e.hash.slice(0,12):"<absent>"}function cA(e,t,n,r,i){try{sA(e,t,n)}catch(o){if(o.code==="EEXIST"){let s=rc(e);if(r<i)return!1;throw new ic(e,n,s.revision)}throw o}return!0}var On=".scipquery.json",iS=2e3,oc=5e3,Dd=oc,oS=15*6e4,Fd={enabled:!0,windowMs:15*6e4,maxRebuilds:2,maxEstimatedWriteBytes:1024*1024*1024},mA={enabled:!1,autoStart:!1,allowExpensiveRebuild:!1,debounceMs:iS,cooldownMs:Dd,gitPollMs:2e3,idleTimeoutMs:oS,autoRefresh:!0,ignore:[],resourceBudget:Fd};var pA=new Set(["$schema","schemaVersion","collaborationDomainId","languages","indexerConcurrency","watch","indexer","dbPath","entryRoots","semantic","suppressions","declaredCouplings","locality","architecture","coverageContracts","docs"]),fA=new Set(["enabled","autoStart","allowExpensiveRebuild","debounceMs","cooldownMs","gitPollMs","idleTimeoutMs","autoRefresh","ignore","resourceBudget"]),gA=new Set(["enabled","windowMs","maxRebuilds","maxEstimatedWriteBytes"]),hA=new Set(["pathPrefixes","files","symbolPatterns","qualifiedVars"]),yA=new Set(["typescript","rust"]),bA=new Set(["tsconfigs"]),SA=new Set(["rustAnalyzerPath"]),Zb=new Set(nu),vA=new Set(["pnpmWorkspaces","projectMode","projects","configPath","maxWarmSessions","workerIdleMs","workerSoftMemoryMb","workerHeapMb","maxHeapMb"]),CA=new Set(["architecturalBoundarySegments"]),xA=new Set(["boundaries","allowedDependencies","requireCompletePolicy","requireCompleteCoverage","requireAcyclic","requireResolvedBoundaries","requireMinimalPolicy","maxBoundaryFanOut","maxBoundaryFiles","testPaths"]),RA=new Set(["name","paths","subUnits","maxFiles"]),EA=new Set(["snapshotPaths"]),IA=new Set(["name","files","reason"]),wA=new Set(["id","check","file","reason","expiresAt","createdAt","decision"]),PA=new Set(["kind","reasonCode","decidedBy","policyVersion","observation","evidence","invalidateOn"]),TA=new Set(["kind","referent","claim","contentHash","generation"]),LA=new Set(["targetContentChange","detectorMajorChange"]),MA=new Set(["name","file","keys","mustEqual","allowExtra"]),DA=new Set(["type","identifier","marker"]),FA=new Set(["type","path","pattern"]),kA=new Set(["object-literal-keys","string-array","markdown-list"]),NA=new Set(["top-level-dirs","file-glob","registered-commands","builtin-skills"]);function sS(e){let t=mn(e,On);if(!yi(t))return{};let n;try{n=ht(t,{maxBytes:Gs,inputKind:"scip-query project config"})}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`unable to read ${On} at ${t}: ${i}`,{cause:r})}return lS(mr(n),t,"read").config}function rde(e,t={}){let n=[];return o0(e,n),AA(e,n),$A(e,n),qA(e,n,t),VA(e,n),Za(e,n),JA(e,n,t),QA(e,n,t),i0(e,n,t),r0(e,n),n}function aS(e,t,n,r,i){if(!r)return;let o=dA(r,n),s=uA(r,o);if(s.startsWith("..")||lA(s)){e.push({level:"error",path:t,message:i.outside});return}yi(o)||e.push({level:"warning",path:t,message:i.missing})}function AA(e,t){_A(e,t),e.collaborationDomainId!==void 0&&!/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(e.collaborationDomainId)&&t.push({level:"error",path:"collaborationDomainId",message:"Must be a lowercase or uppercase UUID v4 generated for this collaboration domain."}),OA(e,t),BA(e,t),e.indexerConcurrency!==void 0&&(!Number.isInteger(e.indexerConcurrency)||e.indexerConcurrency<=0)&&t.push({level:"error",path:"indexerConcurrency",message:"Must be a positive integer."})}function _A(e,t){let n=e;n.schemaVersion!==void 0&&n.schemaVersion!==Nn&&t.push({level:"error",path:"schemaVersion",message:`Must be ${Nn}; unversioned and v${kn} files are migrated while loading.`}),n.$schema!==void 0&&(typeof n.$schema!="string"||n.$schema.trim()==="")&&t.push({level:"error",path:"$schema",message:"Must be a non-empty string."})}function OA(e,t){let n=new Set(nu);for(let[r,i]of(e.languages??[]).entries())n.has(i)||t.push({level:"error",path:`languages[${r}]`,message:`Unsupported language: ${i}`})}function BA(e,t){for(let[n,r]of(e.entryRoots?.symbolPatterns??[]).entries())try{gr(r,`entryRoots.symbolPatterns[${n}]`)}catch(i){t.push({level:"error",path:`entryRoots.symbolPatterns[${n}]`,message:i instanceof Error?i.message:String(i)})}}function $A(e,t){eS(e.watch?.debounceMs,"debounceMs",t),jA(e,t),eS(e.watch?.gitPollMs,"gitPollMs",t),HA(e,t);for(let n of["autoStart","allowExpensiveRebuild","autoRefresh"])Uo(e.watch?.[n],`watch.${n}`,t);UA(e,t)}function eS(e,t,n){e!==void 0&&e<=0&&n.push({level:"error",path:`watch.${t}`,message:"Must be greater than 0."})}function jA(e,t){e.watch?.cooldownMs!==void 0&&(!Number.isInteger(e.watch.cooldownMs)||e.watch.cooldownMs<0)?t.push({level:"error",path:"watch.cooldownMs",message:"Must be a non-negative integer."}):e.watch?.cooldownMs!==void 0&&e.watch.cooldownMs<oc&&t.push({level:"warning",path:"watch.cooldownMs",message:`Values below ${oc}ms are raised to the safety floor at runtime.`})}function HA(e,t){e.watch?.idleTimeoutMs!==void 0&&(!Number.isInteger(e.watch.idleTimeoutMs)||e.watch.idleTimeoutMs<0)&&t.push({level:"error",path:"watch.idleTimeoutMs",message:"Must be a non-negative integer; 0 disables idle shutdown."})}function UA(e,t){let n=e.watch?.resourceBudget;n?.enabled!==void 0&&typeof n.enabled!="boolean"&&t.push({level:"error",path:"watch.resourceBudget.enabled",message:"Must be a boolean."});for(let[r,i]of[["windowMs",n?.windowMs],["maxRebuilds",n?.maxRebuilds],["maxEstimatedWriteBytes",n?.maxEstimatedWriteBytes]])i!==void 0&&(!Number.isSafeInteger(i)||i<=0)&&t.push({level:"error",path:`watch.resourceBudget.${r}`,message:"Must be a positive safe integer."})}function qA(e,t,n){let r=e.indexer?.typescript;r?.projectMode!==void 0&&r.projectMode!=="single"&&r.projectMode!=="workspace"&&t.push({level:"error",path:"indexer.typescript.projectMode",message:'Must be "single" or "workspace".'}),zA(r,t,n),r?.projectMode==="workspace"&&r.pnpmWorkspaces===!0&&t.push({level:"warning",path:"indexer.typescript.pnpmWorkspaces",message:'Ignored when projectMode is "workspace"; explicit TypeScript projects are indexed directly.'}),GA(r,t),KA(e,t),WA(e,t,n)}function zA(e,t,n){if(e?.projects!==void 0)if(!Array.isArray(e.projects))t.push({level:"error",path:"indexer.typescript.projects",message:"Must be an array."});else for(let[r,i]of e.projects.entries()){let o=`indexer.typescript.projects[${r}]`;typeof i!="string"||i.trim()===""?t.push({level:"error",path:o,message:"Project path must be a non-empty string."}):aS(t,o,i,n.projectRoot,{outside:"Project path must stay inside the project root.",missing:`TypeScript project path does not exist: ${i}`})}}function GA(e,t){for(let[n,r]of[["maxWarmSessions",e?.maxWarmSessions],["workerSoftMemoryMb",e?.workerSoftMemoryMb],["workerHeapMb",e?.workerHeapMb],["maxHeapMb",e?.maxHeapMb]])r!==void 0&&(!Number.isInteger(r)||r<=0)&&t.push({level:"error",path:`indexer.typescript.${n}`,message:"Must be a positive integer."});e?.workerIdleMs!==void 0&&(!Number.isInteger(e.workerIdleMs)||e.workerIdleMs<0)&&t.push({level:"error",path:"indexer.typescript.workerIdleMs",message:"Must be a non-negative integer."})}function KA(e,t){let n=e.semantic?.rust;n?.rustAnalyzerPath!==void 0&&(typeof n.rustAnalyzerPath!="string"||n.rustAnalyzerPath.trim()==="")&&t.push({level:"error",path:"semantic.rust.rustAnalyzerPath",message:"Rust analyzer path must be a non-empty string."})}function WA(e,t,n){let r=e.indexer?.clojure;if(r?.configPath!==void 0){let i="indexer.clojure.configPath";typeof r.configPath!="string"||r.configPath.trim()===""?t.push({level:"error",path:i,message:"Config path must be a non-empty string."}):aS(t,i,r.configPath,n.projectRoot,{outside:"Config path must stay inside the project root.",missing:`Clojure indexer config path does not exist: ${r.configPath}`})}}function VA(e,t){if(e.locality===void 0)return;if(!k(e.locality)){t.push({level:"error",path:"locality",message:"Must be an object."});return}let n=e.locality.architecturalBoundarySegments;if(n!==void 0){if(!Array.isArray(n)){t.push({level:"error",path:"locality.architecturalBoundarySegments",message:"Must be an array."});return}for(let[r,i]of n.entries()){let o=`locality.architecturalBoundarySegments[${r}]`;typeof i!="string"||i.trim()===""?t.push({level:"error",path:o,message:"Boundary segment must be a non-empty string."}):(i.includes("/")||i.includes("\\"))&&t.push({level:"error",path:o,message:"Boundary segment must be a single folder name, not a path."})}}}function JA(e,t,n){if(e.declaredCouplings!==void 0&&!Array.isArray(e.declaredCouplings)){t.push({level:"error",path:"declaredCouplings",message:"Must be an array."});return}for(let[r,i]of(e.declaredCouplings??[]).entries())YA(i,`declaredCouplings[${r}]`,t,n)}function YA(e,t,n,r){(!e.name||e.name.trim()==="")&&n.push({level:"error",path:`${t}.name`,message:"Declared coupling name is required."}),!Array.isArray(e.files)||e.files.length<2?n.push({level:"error",path:`${t}.files`,message:"Declared coupling needs at least two files."}):XA(e.files,t,n,r),e.reason!==void 0&&e.reason.trim()===""&&n.push({level:"error",path:`${t}.reason`,message:"Declared coupling reason cannot be blank."})}function XA(e,t,n,r){for(let[i,o]of e.entries())!o||o.trim()===""?n.push({level:"error",path:`${t}.files[${i}]`,message:"Declared coupling file path is required."}):r.projectRoot&&!yi(mn(r.projectRoot,o))&&n.push({level:"warning",path:`${t}.files[${i}]`,message:`Declared coupling file does not exist: ${o}`})}function QA(e,t,n){let r=n.now??new Date;e.suppressions!==void 0&&!Array.isArray(e.suppressions)&&t.push({level:"error",path:"suppressions",message:"Must be an array."});for(let[i,o]of(Array.isArray(e.suppressions)?e.suppressions:[]).entries()){let s=`suppressions[${i}]`;if(!k(o)){t.push({level:"error",path:s,message:"Suppression must be an object."});continue}ZA(o,s,t),e0(o,s,t,n.projectRoot),t0(o,s,t,r),n0(o,s,t,n.projectRoot)}}function ZA(e,t,n){(!e.reason||e.reason.trim()==="")&&n.push({level:"error",path:`${t}.reason`,message:"Suppression reason is required."}),e.id!==void 0&&e.id.trim()===""&&n.push({level:"error",path:`${t}.id`,message:"Suppression id cannot be blank."}),e.check!==void 0&&e.check.trim()===""&&n.push({level:"error",path:`${t}.check`,message:"Suppression check cannot be blank."}),!e.id&&(!e.check||!e.file?n.push({level:"error",path:t,message:"Suppression must include id or both check and file."}):n.push({level:"warning",path:t,message:"Check+file suppressions waive every matching finding in that file; prefer a stable id when available."}))}function e0(e,t,n,r){e.file!==void 0&&(e.file.trim()===""?n.push({level:"error",path:`${t}.file`,message:"Suppression file path cannot be blank."}):r&&!yi(mn(r,e.file))&&n.push({level:"warning",path:`${t}.file`,message:`Suppression file does not exist: ${e.file}`}))}function t0(e,t,n,r){if(e.expiresAt){let i=Date.parse(e.expiresAt);Number.isNaN(i)?n.push({level:"error",path:`${t}.expiresAt`,message:"Must be an ISO date string."}):i<=r.getTime()&&n.push({level:"warning",path:`${t}.expiresAt`,message:"Suppression has expired."})}}function n0(e,t,n,r){if(e.decision!==void 0&&!qo(e.decision))n.push({level:"error",path:`${t}.decision`,message:"Must be a valid automated-adjudication decision with reason code, evidence, and invalidation rules."});else if(e.decision&&r)for(let[i,o]of e.decision.evidence.entries())o.kind!=="graph"&&!yi(mn(r,o.referent))&&n.push({level:"error",path:`${t}.decision.evidence[${i}].referent`,message:`Suppression counterevidence does not exist: ${o.referent}`})}function r0(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 i0(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())u0(i,r,t,n)}}function tS(e,t,n,r,i){if(!k(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 ide(e){return{...mA,...e.watch,cooldownMs:Math.max(oc,e.watch?.cooldownMs??Dd),resourceBudget:{...Fd,...e.watch?.resourceBudget}}}function ode(e,t){let n=mn(e,On),r=rS(),i={collaborationDomainId:r,languages:t,watch:{enabled:!0,debounceMs:iS,cooldownMs:Dd,gitPollMs:2e3,idleTimeoutMs:oS,autoRefresh:!0,resourceBudget:{...Fd}}},o=Go(n,s=>{if(!s.revision.exists)return{kind:"write",text:hi(i)};let a=ac(s,i);return a.config.collaborationDomainId?{kind:"unchanged"}:{kind:"write",text:hi({...a.config,collaborationDomainId:r})}});return{configPath:n,changed:o.changed}}function sde(e,t,n=rS()){let r=mn(e,On),i=t,o=Go(r,s=>{let a=ac(s,t);if(a.config.collaborationDomainId)return i=a.config,{kind:"unchanged"};let c={...a.config,collaborationDomainId:n};return i=c,{kind:"write",text:hi(c)}});return{configPath:r,config:i,changed:o.changed}}function ade(e,t,n){let r=mn(e,On),i=[...n],o=t,s=Go(r,a=>{let c=ac(a,t);if(cS(t.languages,c.config.languages,i))throw new zo(r,"languages");let l={...c.config,languages:i};return o=l,a.revision.exists&&!c.needsMigration&&sc(l,c.config)?{kind:"unchanged"}:{kind:"write",text:hi(l)}});return{configPath:r,config:o,changed:s.changed}}function cde(e,t,n){let r=mn(e,On),i=t,o=Go(r,s=>{let a=ac(s,t);if(cS(t.watch?.enabled,a.config.watch?.enabled,n))throw new zo(r,"watch.enabled");let c={...a.config,watch:{...a.config.watch,enabled:n,...n&&a.config.watch?.autoRefresh===void 0?{autoRefresh:!0}:{}}};return i=c,s.revision.exists&&!a.needsMigration&&sc(c,a.config)?{kind:"unchanged"}:{kind:"write",text:hi(c)}});return{configPath:r,config:i,changed:o.changed}}function ac(e,t){if(!e.revision.exists)return{config:ec(t),needsMigration:!0};let n=lS(mr(e.text),e.path,"update");return{config:n.config,needsMigration:n.needsMigration}}function sc(e,t){return JSON.stringify(e)===JSON.stringify(t)}function cS(e,t,n){return!sc(e,t)&&!sc(t,n)}function lS(e,t,n){if(e.kind==="legacy"||e.kind==="supported")return e;if(e.kind==="malformed"){let i=n==="read"?`invalid ${On} 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 ${On} 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${kn} and current v${Nn}). Upgrade scip-query before retrying; the file was left untouched.`)}function o0(e,t){if(!k(e))return;let n=e;ve(t,n,"",pA),ve(t,n.watch,"watch",fA),ve(t,n.watch?.resourceBudget,"watch.resourceBudget",gA),ve(t,n.entryRoots,"entryRoots",hA),ve(t,n.semantic,"semantic",yA),ve(t,n.semantic?.typescript,"semantic.typescript",bA),ve(t,n.semantic?.rust,"semantic.rust",SA),ve(t,n.locality,"locality",CA),ve(t,n.architecture,"architecture",xA),ve(t,n.docs,"docs",EA),nS(t,n.architecture?.boundaries,"architecture.boundaries",RA),s0(n,t),nS(t,n.declaredCouplings,"declaredCouplings",IA),a0(n,t),l0(n,t)}function nS(e,t,n,r){if(Array.isArray(t))for(let[i,o]of t.entries())ve(e,o,`${n}[${i}]`,r)}function s0(e,t){if(k(e.indexer)){ve(t,e.indexer,"indexer",Zb);for(let[n,r]of Object.entries(e.indexer))Zb.has(n)&&ve(t,r,`indexer.${n}`,vA)}}function a0(e,t){if(Array.isArray(e.suppressions))for(let[n,r]of e.suppressions.entries())ve(t,r,`suppressions[${n}]`,wA),c0(r.decision,`suppressions[${n}].decision`,t)}function c0(e,t,n){if(k(e)){if(ve(n,e,t,PA),Array.isArray(e.evidence))for(let[r,i]of e.evidence.entries())ve(n,i,`${t}.evidence[${r}]`,TA);ve(n,e.invalidateOn,`${t}.invalidateOn`,LA)}}function l0(e,t){if(Array.isArray(e.coverageContracts))for(let[n,r]of e.coverageContracts.entries()){let i=`coverageContracts[${n}]`;ve(t,r,i,MA),k(r)&&(ve(t,r.keys,`${i}.keys`,DA),ve(t,r.mustEqual,`${i}.mustEqual`,FA))}}function ve(e,t,n,r){if(k(t))for(let i of Object.keys(t))r.has(i)||e.push({level:"warning",path:n?`${n}.${i}`:i,message:"Unknown config key."})}function u0(e,t,n,r){let i=`coverageContracts[${t}]`;if(!k(e)){n.push({level:"error",path:i,message:"Coverage contract must be an object."});return}(typeof e.name!="string"||e.name.trim()==="")&&n.push({level:"error",path:`${i}.name`,message:"Coverage contract name is required."}),typeof e.file!="string"||e.file.trim()===""?n.push({level:"error",path:`${i}.file`,message:"Coverage contract file is required."}):r.projectRoot&&!yi(mn(r.projectRoot,e.file))&&n.push({level:"warning",path:`${i}.file`,message:`Coverage contract file does not exist: ${e.file}`}),tS(n,e.keys,`${i}.keys`,kA,"Unknown coverage-contract key extractor type."),tS(n,e.mustEqual,`${i}.mustEqual`,NA,"Unknown coverage-contract ground-truth source type."),e.allowExtra!==void 0&&typeof e.allowExtra!="boolean"&&n.push({level:"error",path:`${i}.allowExtra`,message:"Must be a boolean."})}import{existsSync as cc,lstatSync as d0}from"fs";import{dirname as m0,resolve as p0}from"path";function Ide(e){return e.state==="fresh"?!0:e.state!=="stale"?!1:!e.reason.startsWith("SQLite generation requires repair")}function uS(e,t,n,r={}){let i=new Date().toISOString();if(!cc(n.dbPath))return{state:"missing",checkedAt:i,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!cc(n.metaPath))return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let o=to(Ye(n.metaPath,"reindex metadata"));return o.kind==="unsupported"?{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Reindex metadata version ${o.version} is unsupported by this scip-query build.`,remedy:"Upgrade scip-query or run: scip-query reindex"}:o.kind==="malformed"?{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Could not decode reindex metadata: ${o.reason}`,remedy:"Run: scip-query reindex"}:f0(e,t,n,r,o,i)}catch(o){return{state:"unknown",checkedAt:i,metaPath:n.metaPath,reason:`Could not read reindex metadata: ${o instanceof Error?o.message:String(o)}`,remedy:"Run: scip-query reindex"}}}function f0(e,t,n,r,i,o){let s=i.metadata,a=t.languages??th(e),c=g0(e,t,n,r,a,s.fingerprint),l=[...s.indexedLanguages??[]].sort(),u=i.capabilities.publishableGeneration&&wf(Zi(s.fingerprint),c)&&JSON.stringify(l)===JSON.stringify(c.languages),{accepted:d,reason:m}=b0(n,c,l,u);return{state:d?"fresh":"stale",checkedAt:o,metaPath:n.metaPath,updatedAt:s.updatedAt,lastRefresh:s.lastRefresh,reason:m,remedy:d?void 0:"Run: scip-query reindex"}}function g0(e,t,n,r,i,o){return h0(e,t,n,r,i,o)??x0(e,i,t,n.cacheDir??m0(n.dbPath))}function h0(e,t,n,r,i,o){if(!n.cacheDir||!r.gitContext||!xu(r.gitContext,n.cacheDir,o))return;let s=y0(e,t,i,r.gitContext,r.gitObservation,o);if(!(!s||!xu(s,n.cacheDir,o)))return o}function y0(e,t,n,r,i,o){if(!R0(o,n,t)||!E0(e,o,t))return;let s=i?.context===r?r:Df(r),a=i&&i.context===r?i.projectFileInventorySequence:void 0;return s?.clean&&Ff(e,void 0,{cachedInventoryAfterSequence:a})?s:void 0}function b0(e,t,n,r){let i=Cu(e.dbPath,e.metaPath),o=i.state==="invalid"||i.state==="drifted",s=r?nh(e.dbPath,t,n):void 0,a=s?.state==="incomplete";return{accepted:r&&!o&&!a,reason:S0(i,s,r)}}function S0(e,t,n){return e.state==="invalid"||e.state==="drifted"?`SQLite generation requires repair: ${e.reason}`:t?.state==="incomplete"?`SQLite generation is missing ${t.missingDocumentCount} indexed source document(s): ${t.missingPaths.join(", ")}`:n?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files."}function wde(e){let t=new Date().toISOString();if(!cc(e.dbPath))return{state:"missing",checkedAt:t,metaPath:e.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!cc(e.metaPath))return{state:"unknown",checkedAt:t,metaPath:e.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let n=to(Ye(e.metaPath,"reindex metadata"));return n.kind==="unsupported"?{state:"unknown",checkedAt:t,metaPath:e.metaPath,reason:`Reindex metadata version ${n.version} is unsupported by this scip-query build.`,remedy:"Upgrade scip-query or run: scip-query reindex"}:n.kind==="malformed"?{state:"unknown",checkedAt:t,metaPath:e.metaPath,reason:`Could not decode reindex metadata: ${n.reason}`,remedy:"Run: scip-query reindex"}:v0(e,t,n)}catch(n){return{state:"unknown",checkedAt:t,metaPath:e.metaPath,reason:`Could not read reindex metadata: ${n instanceof Error?n.message:String(n)}`,remedy:"Run: scip-query reindex"}}}function v0(e,t,n){let r=n.metadata,i=C0(n),o=Cu(e.dbPath,e.metaPath),s=o.state==="invalid"||o.state==="drifted",a=i&&!s;return{state:a?"fresh":"stale",checkedAt:t,metaPath:e.metaPath,updatedAt:r.updatedAt,lastRefresh:r.lastRefresh,reason:s?`SQLite generation requires repair: ${o.reason}`:i?"Watcher accepted the newly published index generation with no later changes pending.":"Published index metadata is not a complete queryable generation.",remedy:a?void 0:"Run: scip-query reindex"}}function C0(e){let t=e.metadata,n=[...t.indexedLanguages??[]].sort(),r=Zi(t.fingerprint),i=[...r?.languages??[]].sort();return e.capabilities.publishableGeneration&&r!==null&&JSON.stringify(n)===JSON.stringify(i)}function x0(e,t,n,r=_f(e,n)){return Bf(e,r,()=>jf(e,t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath}))}function R0(e,t,n){let r=I0(t,n);return e.version===r.version&&e.typescriptSymbolIdentityVersion===r.typescriptSymbolIdentityVersion&&JSON.stringify([...e.languages].sort())===JSON.stringify(r.languages)&&e.pnpmWorkspaces===r.pnpmWorkspaces&&e.typescriptProjectMode===r.typescriptProjectMode&&JSON.stringify([...e.typescriptProjects].sort())===JSON.stringify(r.typescriptProjects)&&e.clojureConfigPath===r.clojureConfigPath}function E0(e,t,n){if(!(t.languages.includes("typescript")||!!t.clojureConfigPath))return!0;let i=Br(e);if(t.clojureConfigPath){let o=Qn(t.clojureConfigPath);if(!i.includes(o))return!1;try{if(!d0(p0(e,o)).isFile())return!1}catch{return!1}}return!t.languages.includes("typescript")||kf(e,n.indexer?.typescript?.projectMode,n.indexer?.typescript?.projects??[],i)}function I0(e,t){return Hf(e,{pnpmWorkspaces:t.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:t.indexer?.typescript?.projectMode,typescriptProjects:t.indexer?.typescript?.projects,clojureConfigPath:t.indexer?.clojure?.configPath})}import{existsSync as Ad,lstatSync as w0,readdirSync as P0}from"fs";import{createHash as mS}from"crypto";import{isAbsolute as pS,join as hr,relative as fS,resolve as lc,sep as _d}from"path";function Nd(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(kd(l));break;case"unsupported-future":i+=1,s.push(kd(l));break;case"malformed":o+=1,s.push(kd(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 kd(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 Bd=hr(".scipquery","suppressions"),dS="scip-query-suppression",gS=1,uc=2;function hS(e){return hr(e,Bd)}function yS(e){let t=yr(e);return/^[A-Za-z0-9_-]{1,120}$/.test(t)&&!/^(ID-|CON$|PRN$|AUX$|NUL$|COM[1-9]$|LPT[1-9]$)/i.test(t)?`${t}.json`:`ID-${mS("sha256").update(t).digest("hex")}.json`}function yr(e){if(e.id&&e.id.trim()!=="")return e.id.trim();let t=`${e.check??""}\0${e.file??""}`;return`CHECK-${mS("sha256").update(t).digest("hex").slice(0,12).toUpperCase()}`}function Od(e,t){let n=lc(e),r=fS(n,lc(t));if(pS(r)||r===".."||r.startsWith(`..${_d}`))throw new Error("Suppression path must remain inside the project.");let i=n;for(let o of r.split(_d))if(i=hr(i,o),w0(i,{throwIfNoEntry:!1})?.isSymbolicLink())throw new Error(`Symbolic links are not allowed in suppression storage: ${i}`)}function _de(e,t){let n=hS(e),r=hr(n,yS(t));Od(e,r);let i=hr(n,`${yr(t)}.json`),o=fS(lc(n),lc(i));if(i!==r&&o!==".."&&!o.startsWith(`..${_d}`)&&!pS(o)&&(Od(e,i),Ad(i))){if(Ad(r))throw new Error(`Duplicate suppression records require reconciliation: ${r}, ${i}`);return i}return r}function $d(e,t){if(!k(e))return{state:"malformed",error:"not a suppression object"};let n=T0(e);if(typeof n!="number")return n;let r=L0(e.decision,n);if(r)return{state:"malformed",error:r};let i=M0(e);if("error"in i)return i;if(n===0)return{state:"legacy",suppression:i,record:e,schemaVersion:0};let o=D0(e,i,t);return o?{state:"malformed",error:o}:{state:n===uc?"current":"legacy",suppression:i,record:e,schemaVersion:n}}function T0(e){let t=e.schemaVersion;return t===void 0?["kind","suppressionIdentity","writer"].some(n=>e[n]!==void 0)?{state:"malformed",error:"suppression envelope metadata requires schemaVersion"}:0:typeof t!="number"||!Number.isSafeInteger(t)?{state:"malformed",error:"schemaVersion must be a positive safe integer"}:t!==gS&&t!==uc?{state:t>uc?"unsupported-future":"unsupported-older",error:`unsupported schemaVersion ${String(t)}`}:e.kind!==void 0&&e.kind!==dS?{state:"malformed",error:`kind must be ${dS}`}:t}function L0(e,t){return t===gS&&e!==void 0?"schemaVersion 1 cannot carry automated adjudication metadata":t===uc&&!qo(e)?"schemaVersion 2 requires a valid automated adjudication decision":t===0&&e!==void 0&&!qo(e)?"invalid automated adjudication decision":null}function M0(e){if(typeof e.reason!="string"||e.reason.trim()==="")return{state:"malformed",error:"missing reason"};let t=k0(e);return!t.id?.trim()&&!t.check?.trim()?{state:"malformed",error:"needs an id or a check"}:t}function D0(e,t,n){return e.suppressionIdentity!==yr(t)||n!==void 0&&e.suppressionIdentity!==n&&yS(t).slice(0,-5)!==n?"suppressionIdentity does not match the suppression target or filename":F0(e.writer)?$r(e.createdAt)?e.updatedAt!==void 0&&!$r(e.updatedAt)?"invalid updatedAt timestamp":null:"missing valid createdAt timestamp":"missing valid writer metadata"}function F0(e){return k(e)&&e.tool==="scip-query"&&typeof e.version=="string"&&e.version.trim()!==""}function dc(e){let t=hS(e);if(Od(e,t),!Ad(t))return{suppressions:[],compatibility:Nd([]),warnings:[]};let n=new Map,r=new Set,i=[];for(let s of bS(t,i)){let a=hr(t,s),c=`${Bd}/${s}`,l;try{l=JSON.parse(Ye(a,"suppression record"))}catch{i.push({path:c,state:"malformed",reason:"malformed JSON"});continue}let u=$d(l,s.slice(0,-5));if("error"in u){i.push({path:c,state:u.state,reason:u.error});continue}let d=yr(u.suppression),m=n.get(d);m&&JSON.stringify(m.suppression)!==JSON.stringify(u.suppression)?(r.add(d),i.push({path:c,state:"malformed",reason:`conflicting suppression identity also in ${m.path}`})):(i.push({path:c,state:u.state}),n.set(d,{suppression:u.suppression,path:c}))}let o=Nd(i);return{suppressions:[...n].filter(([s])=>!r.has(s)).map(([,s])=>s.suppression),compatibility:o,warnings:o.issues.map(s=>`${s.path}: ${s.reason} \u2014 ignored`)}}function bS(e,t,n=""){let r=[];for(let i of P0(hr(e,n),{withFileTypes:!0}).sort((o,s)=>o.name.localeCompare(s.name))){let o=n?`${n}/${i.name}`:i.name;i.isSymbolicLink()?t.push({path:`${Bd}/${o}`,state:"malformed",reason:"symbolic suppression storage entry"}):i.isDirectory()?r.push(...bS(e,t,o)):i.isFile()&&o.endsWith(".json")&&r.push(o)}return r}function k0(e){return{...typeof e.id=="string"?{id:e.id}:{},...typeof e.check=="string"?{check:e.check}:{},...typeof e.file=="string"?{file:e.file}:{},reason:e.reason,...typeof e.expiresAt=="string"?{expiresAt:e.expiresAt}:{},...typeof e.createdAt=="string"?{createdAt:e.createdAt}:{},...e.decision?{decision:e.decision}:{}}}function mc(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var jd,br;function Jde(e){jd=e}function pc(){return br}function SS(e=mc(),t=void 0){if(t===void 0&&jd?.projectRoot===e)return jd;let n=sS(e),r=Of(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(Hd(r.dbPath))return{projectRoot:e,config:n,paths:r,dbPath:r.dbPath,dbPathSource:"configured",gitContext:t};let o=A0(e,"index.db");return{projectRoot:e,config:n,paths:r,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:B0(o,r.dbPath),gitContext:t}}function Yde(e){return SS(e).dbPath}function Xde(e,t,n,r={}){if(Hd(n.dbPath)&&r.gitContext?.clean===!1&&r.watcherGeneration!==void 0&&Vg(n.dbPath)===r.watcherGeneration)return oh(e,t,n,r.gitContext);let i=uS(e,t,n,{gitContext:r.gitContext,gitObservation:r.gitObservation});return i.state==="fresh"?{kind:"local-fresh",freshness:i}:ih(e,t,n,r.gitContext)}function Qde(e){return!e.startsWith("__")&&!_0.has(e)}function Zde(e){return e==="search"||e==="code"}var _0=new Set(["health","review","capabilities","check-deps","config-validate","continue","doctor","init","install-skills","reindex","setup","setup-agent","status","suppress","uninstall","watch"]);function vS(){try{return O0(mc(),{warnOnRootFallback:!0})}catch(e){console.error(`error: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}function O0(e,t={}){let{config:n,paths:r,dbPath:i,dbPathSource:o,rootFallbackWarning:s,gitContext:a}=SS(e);if(!Hd(i))throw new Error("No index.db found. Run: scip-query reindex");t.warnOnRootFallback&&o==="root-fallback"&&s&&console.error(s);let c=dc(e).suppressions,l={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??r.indexPath,projectRoot:e,collaborationDomainId:n.collaborationDomainId,sharedEvidenceDbPath:rh(e,n,a),entryRoots:n.entryRoots,semantic:n.semantic,suppressions:[...n.suppressions??[],...c],declaredCouplings:n.declaredCouplings,locality:n.locality,architecture:n.architecture,coverageContracts:n.coverageContracts,docs:n.docs},u=eh(e);return new Jg(l,u)}function B0(e,t){let n="unknown time";try{n=N0(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 fc(e){return Lf(()=>{let t=vS(),n=br;br=t;try{return e(t)}finally{br=n,t.close()}})}async function eme(e){let t=Mf();try{let n=vS(),r=br;br=n;try{return await e(n)}finally{br=r,n.close()}}finally{t()}}function tme(e,t){return t.concat([e])}function Ud(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 nme(e){switch(e.state){case"idle":return"Watching (idle)";case"waiting":{let t=Math.round((e.reindexAt-Date.now())/1e3);return`${e.changedFiles} file(s) changed, reindexing in ${t}s...`}case"indexing":return`Reindexing... (${Math.round((Date.now()-e.startedAt)/1e3)}s)`;case"cooldown":return`Cooldown (${Math.round((e.until-Date.now())/1e3)}s)${e.dirty?" \u2014 changes pending":""}`;case"budget-paused":return`Automatic reindex paused by resource budget (${Math.max(0,Math.round((e.until-Date.now())/1e3))}s; ${e.reason}; ${e.rebuilt} rebuilds, ${Ud(e.estimatedWriteBytes)} estimated writes)${e.dirty?" \u2014 changes pending":""}`;case"draining":return`Stopping safely \u2014 ${e.reason}`;default:return $0(e)}}function $0(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}var j0=new Map([[8,"\u2408"],[9,"\u2409"],[10,"\u2424"],[13,"\u240D"]]),ime=6500,ome=8e3,sme=6500,ame=3500;function CS(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=q0(e,o);continue}if(s===155){o=xS(e,o+1);continue}if(H0(s)){o=RS(e,o+1);continue}if(K0(s)){i+=U0(s,n,r),o+=1;continue}if(W0(s)){i+="\uFFFD",o+=1;continue}i+=e[o],o+=1}return i}function H0(e){return e===144||e===152||e===157||e===158||e===159}function U0(e,t,n){return e===10&&t?`
|
|
17
|
+
`:e===9&&n?" ":j0.get(e)??"\uFFFD"}function Rt(e){return CS(e,{allowNewlines:!1,allowTabs:!1})}function zd(e,t=n=>process.stdout.write(n)){t(`${e}
|
|
18
|
+
`)}function cme(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(qd)),e.error=(...n)=>t.error(...n.map(qd)),e.warn=(...n)=>t.warn(...n.map(qd)),()=>{e.log=t.log,e.error=t.error,e.warn=t.warn}}function qd(e){return typeof e=="string"?CS(e):e}function q0(e,t){let n=e.charCodeAt(t+1);if(Number.isNaN(n))return e.length;if(n===91)return xS(e,t+2);if(V0.has(n))return RS(e,t+2);let r=t+1;for(;r<e.length&&z0(e.charCodeAt(r));)r+=1;return r<e.length&&G0(e.charCodeAt(r))?r+1:t+1}function xS(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 RS(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 z0(e){return e>=32&&e<=47}function G0(e){return e>=48&&e<=126}function K0(e){return e<=31||e>=127&&e<=159}function W0(e){return e===1564||e===8206||e===8207||e>=8234&&e<=8238||e>=8294&&e<=8297}var V0=new Set([80,88,93,94,95]);function gc(e){return e+1}function J0(e,t){return`${gc(e)}-${gc(t)}`}function Gd(e,t,n){return`${Rt(e)}:${J0(t,n)}`}function dme(e,t=180){let n=Rt(e).replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var Kd={empty(e){console.log(Rt(e))},list(e,t){for(let n of e)console.log(Rt(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(Rt(o)),r=o),console.log(Rt(t(i)))}},sectionedReport(e){let t=!0;for(let n of e)n.skipIfEmpty&&n.rows.length===0||(t||console.log(""),t=!1,Y0(n))},table(e,t,n){console.log(` ${e.map(Rt).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(Rt(i))}};function Y0(e){e.title!==void 0&&console.log(Rt(e.title)),e.explanation!==void 0&&console.log(Rt(e.explanation));for(let t of e.rows){let n=e.preserveRowNewlines?t.split(`
|
|
19
|
+
`):[t];for(let r of n)console.log(Rt(r))}}import{availableParallelism as ZP,totalmem as Gl}from"os";import{fileURLToPath as Kl}from"url";import{getHeapStatistics as gre}from"v8";import{existsSync as hc,readdirSync as wS}from"fs";import{join as Ko}from"path";var X0={files:new Set,pathPrefixes:[]},Q0={reasonsByFile:new Map},Wd=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,Z0=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,PS=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],e_=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),t_=4,n_=X("package-surface",{clearGroups:["whole-project"]}),r_=X("package-operational-surface",{clearGroups:["whole-project"]});function TS(e){return n_.get(e,()=>o_(e.config.projectRoot))}function fn(e,t){let n=TS(e);return n.files.has(t)?!0:n.pathPrefixes.some(r=>t.startsWith(r))}function LS(e,t){return TS(e).files.has(t)}function i_(e){return r_.get(e,()=>s_(e.config.projectRoot))}function MS(e,t){return i_(e).reasonsByFile.get(t)??[]}function o_(e){let t=new Set,n=[];for(let{manifest:r,packageRoot:i}of DS(e))for(let o of a_(r))AS(e,i,o,t,n);return t.size===0&&n.length===0?X0:{files:t,pathPrefixes:n}}function s_(e){let t=new Map;for(let{manifest:n,packageRoot:r}of DS(e)){let i=c_(n);for(let s of i)ES(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 l_(a))ES(e,r,c,`package script "${s}"`,t)}}return t.size===0?Q0:{reasonsByFile:t}}function DS(e){let t=[],n=kS(e,"");return n&&t.push({manifest:n,packageRoot:""}),FS(e,"",t,0),t}function FS(e,t,n,r){if(r>=t_)return;let i=Ko(e,t);if(hc(i))for(let o of wS(i,{withFileTypes:!0})){if(!o.isDirectory()||e_.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=kS(e,s);a&&n.push({manifest:a,packageRoot:s}),FS(e,s,n,r+1)}}function kS(e,t){let n;try{n=te(e,Ko(t,"package.json"),{maxBytes:8*1024*1024,inputKind:"package manifest"})}catch(r){if(!xe(r))throw r;return null}try{let r=JSON.parse(n);return r&&typeof r=="object"?r:null}catch{return null}}function a_(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 NS(e.exports,t),t}function c_(e){let t=e.bin;return typeof t=="string"?[t]:!t||typeof t!="object"?[]:Object.values(t).filter(n=>typeof n=="string")}function l_(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 ES(e,t,n,r,i){let o=new Set;AS(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 NS(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))NS(n,t)}function AS(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 IS(c))l!==""&&i.push(pn(t,l));return}let a=o.replace(Z0,"");for(let c of IS(a)){c===a&&c===o&&r.add(pn(t,o));for(let l of PS)u_(e,r,t,c+l)}r.add(pn(t,o))}function IS(e){let t=[e];return Wd.test(e)&&(t.push(e.replace(Wd,"src/")),t.push(e.replace(Wd,""))),t}function u_(e,t,n,r){let i=pn(n,r);if(t.add(i),!r.startsWith("src/")||hc(Ko(e,i)))return;let o=PS.find(u=>r.endsWith(u));if(!o)return;let s=r.slice(0,-o.length);d_(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 _S(e,n,c,`${l}${o}`))t.add(u)}function d_(e,t,n,r,i){let o=pn(n,`${r}/index${i}`);hc(Ko(e,o))&&t.add(o)}function _S(e,t,n,r){let i=Ko(e,t,n);if(!hc(i))return[];let o=[];for(let s of wS(i,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(..._S(e,t,a,r)):s.isFile()&&s.name===r&&o.push(pn(t,a))}return o}function pn(e,t){return e?`${e}/${t}`:t}import{existsSync as Vd,readdirSync as m_}from"fs";import{dirname as p_,join as Jd}from"path";var f_={rootFiles:new Set,sourcePrefixes:[]},g_=new Set([".git",".scipquery","node_modules","target"]),h_=6,y_=X("rust-library-surface",{clearGroups:["whole-project"]});function OS(e,t,n){if(!n.endsWith(".rs")||!v_(b_(e),n))return!1;let r=D(e,n).find(i=>i.symbol===t);return r?C_(j(e,n)[r.startLine]??""):!1}function b_(e){return y_.get(e,()=>S_(e.config.projectRoot))}function S_(e){let t=new Set,n=new Set;for(let r of x_(e)){let i=te(e,Jd(r,"Cargo.toml"),{maxBytes:8388608,inputKind:"Cargo manifest"}),o=R_(i),s=pn(r,"src/lib.rs"),a=o?pn(r,o):!E_(i)&&Ae(e,s)?s:null;if(!a)continue;t.add(a);let c=p_(a).replaceAll("\\","/");n.add(c==="."?"":`${c}/`)}return t.size===0?f_:{rootFiles:t,sourcePrefixes:[...n].sort()}}function v_(e,t){return t.endsWith(".rs")?e.rootFiles.has(t)?!0:I_(t)?!1:e.sourcePrefixes.some(n=>t.startsWith(n)):!1}function C_(e){return/^\s*pub\s+(?!\()/.test(e)}function x_(e){if(!Vd(e))return[];let t=[];return BS(e,"",t,0),t}function BS(e,t,n,r){let i=Jd(e,t);if(Vd(i)&&(Vd(Jd(i,"Cargo.toml"))&&n.push(t),!(r>=h_)))for(let o of m_(i,{withFileTypes:!0})){if(!o.isDirectory()||g_.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name;BS(e,s,n,r+1)}}function R_(e){let t=!1;for(let n of e.split(`
|
|
20
|
+
`)){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 E_(e){let t=!1;for(let n of e.split(`
|
|
21
|
+
`)){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 I_(e){return/(?:^|\/)src\/main\.rs$/.test(e)||/(?:^|\/)src\/bin\//.test(e)||/(?:^|\/)(?:examples|tests|benches)\//.test(e)}import{existsSync as w_,readdirSync as P_}from"fs";import{join as T_}from"path";var L_=/^(?:[\w.-]+\.config\.[cm]?[jt]s|package\.json)$/,M_=/(?:\.{1,2}\/)?[\w@./-]+\.(?:[cm]?[jt]sx?)\b/g,D_=X("config-referenced-files",{clearGroups:["whole-project"]});function F_(e){return D_.get(e,()=>k_(e))}function $S(e,t){return F_(e).has(ee(t))}function k_(e){let t=new Set,n=e.config.projectRoot,r;try{r=P_(n)}catch{return t}let i=r.filter(s=>L_.test(s)&&w_(T_(n,s)));if(i.length===0)return t;let o=new Set(q(e,{includeIgnored:!1}).map(s=>ee(s)));for(let s of i){let a;try{a=te(n,s,{inputKind:"root configuration file"})}catch(c){if(xe(c))continue;continue}N_(a,o,t)}return t}function N_(e,t,n){for(let r of e.matchAll(M_)){let i=ee(r[0]).replace(/^\.\//,"");i.startsWith("..")||i.startsWith("/")||t.has(i)&&n.add(i)}}import{existsSync as Yd,readdirSync as A_}from"fs";import{join as yc}from"path";var __=["trigger.config.ts","trigger.config.mts","trigger.config.js","trigger.config.mjs"],O_=["./src/trigger","./trigger"],B_=/\bdirs\s*:\s*\[([^\]]*)\]/,$_=/["'`]([^"'`]+)["'`]/g,j_=["","apps","packages","services"],H_=X("framework-task-surface",{clearGroups:["whole-project"]});function U_(e){return H_.get(e,()=>q_(e))}function jS(e,t){let n=ee(t);return U_(e).directories.some(r=>n===r.directory||n.startsWith(`${r.directory}/`))}function q_(e){let t=new Map;for(let n of z_(e.config.projectRoot))for(let r of G_(e,n))t.has(r)||t.set(r,{directory:r,framework:"trigger.dev",config:n});return{directories:[...t.values()].sort((n,r)=>n.directory.localeCompare(r.directory))}}function z_(e){let t=[],n=r=>{for(let i of __){let o=r?`${r}/${i}`:i;Yd(yc(e,o))&&t.push(o)}};n("");for(let r of j_.slice(1)){let i=yc(e,r);if(!Yd(i))continue;let o;try{o=A_(i)}catch{continue}for(let s of o)n(`${r}/${s}`)}return t}function G_(e,t){let n;try{n=te(e.config.projectRoot,t,{inputKind:"framework task config"})}catch(a){return xe(a)?[]:[]}let r=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=B_.exec(n)?.[1],o=i?[...i.matchAll($_)].map(a=>a[1]):O_,s=[];for(let a of o){let c=ee(yc(r,a)).replace(/\/+$/,"");c===""||c.startsWith("..")||Yd(yc(e.config.projectRoot,c))&&s.push(c)}return s}function Sr(e){return F(e)==="barrel"}function US(e){return K_.get(e,()=>{let n=q(e,{includeIgnored:!1}).filter(s=>{let a=F(s);return a==="entry"||a==="worker"});if(n.length===0)return new Set;let r=Fe(e),i=new Set,o=new Set;for(;n.length>0;){let s=n.shift();if(!i.has(s)){i.add(s),F(s)==="barrel"&&o.add(s);for(let a of r.get(s)??[])i.has(a)||n.push(a)}}return o})}var K_=X("live-barrels",{clearGroups:["whole-project"]});function W_(e,t){return US(e).has(ee(t))}function qS(e){let t=US(e);return q(e,{includeIgnored:!1}).filter(n=>Sr(n)&&!t.has(n)&&!V_(e,n))}function V_(e,t){let n=ee(t),r=on(e).forFile(n,{facts:!0}).facts?.callables;return r&&r.length>0?!0:(e.get(`SELECT COUNT(*) AS n
|
|
22
|
+
FROM defn_enclosing_ranges der
|
|
23
|
+
JOIN documents d ON d.id = der.document_id
|
|
24
|
+
WHERE d.relative_path = ?
|
|
25
|
+
AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function Ke(e,t){let n=ee(t),r=F(t);return r==="entry"||r==="worker"||gn(n)||jS(e,n)||$S(e,n)||W_(e,n)}function bi(e,t,n){let r=ee(n),i=[];fn(e,r)&&i.push("package-surface-file"),X_(e,t,r)&&i.push("transitive-package-surface"),OS(e,t,r)&&i.push("rust-public-library"),uO(t,r)&&i.push("framework-entrypoint");let o=e.config.entryRoots;return o&&(o.files?.some(s=>ee(s)===r)&&i.push("configured-file"),o.pathPrefixes?.some(s=>r.startsWith(ee(s)))&&i.push("configured-path-prefix"),o.qualifiedVars?.some(s=>mO(t,s))&&i.push("configured-qualified-var"),o.symbolPatterns?.some(s=>{try{return gr(s,"entryRoots.symbolPatterns entry").test(t)}catch{return!1}})&&i.push("configured-symbol-pattern")),i}function We(e,t,n){return bi(e,t,n).length>0}var J_=X("package-surface-reachability",{clearGroups:["whole-project"]}),Y_=X("explicit-package-surface-reachability",{clearGroups:["whole-project"]});function X_(e,t,n){let r=Q_(e).get(n);return r===void 0?!1:r===null||r.has(A(t))}function zS(e,t,n){let r=Z_(e).get(n);return r===void 0?!1:r===null||r.has(A(t))}function Q_(e){return J_.get(e,()=>GS(e,t=>fn(e,t)))}function Z_(e){return Y_.get(e,()=>GS(e,t=>LS(e,t)))}function GS(e,t){let n=new Map,r=[];for(let i of q(e,{includeIgnored:!1}))t(i)&&(n.set(i,null),r.push(i));for(;r.length>0;){let i=r.shift(),o=n.get(i);o!==void 0&&pO(e,i,o,n,r)}return n}function eO(e,t){if(e===null)return t.kind==="named"?new Set(t.names):null;if(t.kind==="star")return new Set(e);if(t.kind==="star-as")return t.names.some(r=>e.has(r))?null:void 0;let n=t.names.filter(r=>e.has(r));return n.length>0?new Set(n):void 0}function tO(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 KS=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),nO=new Set(["default","generateMetadata","generateStaticParams"]),rO=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),iO=new Set(["default","middleware","config"]),oO=new Set(["register","onRequestError"]),sO=new Set(["onRouterTransitionStart"]),aO=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),cO=new Set(["load","actions","entries",...KS]),lO=new Set(["default"]);function uO(e,t){let n=A(e);return n===""?!1:fO(t,n)}function gn(e){return WS(e)||VS(e)||JS(e)||YS(e)||XS(e)||QS(e)||ZS(e)||ev(e)}function WS(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function VS(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function JS(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function YS(e){return Xd(e,"(?:middleware|proxy)\\.(?:ts|js|mts|mjs)")}function XS(e){return Xd(e,"instrumentation\\.(?:ts|js|mts|mjs)")}function QS(e){return Xd(e,"instrumentation-client\\.(?:ts|js|mts|mjs)")}function Xd(e,t){return new RegExp(`^(?:src/)?${t}$`).test(e)||new RegExp(`(?:^|/)src/${t}$`).test(e)||new RegExp(`(?:^|/)(?:apps|services|packages)/[^/]+/(?:src/)?${t}$`).test(e)}function ZS(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function ev(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function dO(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function mO(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(HS(r)+"/")&&e.includes(HS(i)+".")}function HS(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}function pO(e,t,n,r,i){for(let o of Ot(e,t)){if(!o.sourcePath||e.isIgnored(o.sourcePath))continue;let s=eO(n,o);s!==void 0&&tO(r,o.sourcePath,s)&&i.push(o.sourcePath)}}function fO(e,t){return WS(e)?KS.has(t):VS(e)?nO.has(t):JS(e)?rO.has(t):YS(e)?iO.has(t):XS(e)?oO.has(t):QS(e)?sO.has(t):ZS(e)?aO.has(t):ev(e)?cO.has(t):dO(e)?lO.has(t):!1}function oe(e){return e.endLine-e.startLine+1}function bc(e,t={}){let{scope:n,files:r,minLoc:i=1,maxLoc:o=Number.POSITIVE_INFINITY,excludeSymbol:s,excludeEntrySurfaces:a=!1,excludeTypesFiles:c=!1,excludeRootedSymbols:l=!1,requireFunctionLikeSymbol:u=!1,requireCallableSymbol:d=!1,excludeRustTraitImplMembers:m=!1,includeSuppressed:p=!1,sortByLocDesc:f=!1}=t,g=[],h=bO(e,{scope:n,files:r,requireFunctionLikeSymbol:u,requireCallableSymbol:d}),y=new Map,S=new Map,I=v=>{let C=y.get(v);if(C!==void 0)return C;let R=Ke(e,v);return y.set(v,R),R},x=v=>{let C=S.get(v);if(C!==void 0)return C;let R=F(v);return S.set(v,R),R},E={excludeEntrySurfaces:a,requireFunctionLikeSymbol:u,requireCallableSymbol:d,excludeSymbol:s,minLoc:i,maxLoc:o},b={excludeTypesFiles:c,excludeRootedSymbols:l,excludeRustTraitImplMembers:m};for(let v of h)gO(e,v,E,I)&&hO(e,v,b)&&yO(e,v,p,x)&&g.push(v);return f?g.sort((v,C)=>oe(C)-oe(v)):g}function gO(e,t,n,r){let i=t.relativePath;if(e.isIgnored(i)||n.excludeEntrySurfaces&&r(i)||!SO(t,n)||n.excludeSymbol!==void 0&&t.symbol===n.excludeSymbol)return!1;let o=oe(t);return!(o<n.minLoc||o>n.maxLoc)}function hO(e,t,n){let r=t.relativePath;return n.excludeTypesFiles&&vO(r)||n.excludeRootedSymbols&&We(e,t.symbol,r)?!1:!n.excludeRustTraitImplMembers||!ke(t.symbol)}function yO(e,t,n,r){let i=t.relativePath;return r(i)==="test"||ta(t.symbol)?!1:n||!_e(e,i,t.startLine,"")}function bO(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=>D(e,r)):t.requireCallableSymbol?lo(e,{scope:t.scope,symbolMatches:Xe,sqlPrefilter:"callable"}):t.requireFunctionLikeSymbol?lo(e,{scope:t.scope,symbolMatches:be,sqlPrefilter:"function-like"}):hg(e,t.scope)}function SO(e,t){return t.requireCallableSymbol?Xe(e.symbol):t.requireFunctionLikeSymbol?be(e.symbol):e.isFunctionLike}function vO(e){return(e.split("/").pop()??"").includes("types")}import{statSync as CO}from"fs";function Wo(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,...xO(e.generation.databasePath)}}function xO(e){try{let t=CO(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function RO(e,t){return yg(e).filter(n=>EO({pattern:t,relativePath:n})).filter(n=>Ae(e.config.projectRoot,n)).map(n=>({relativePath:n}))}function EO(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=Qn(n.pattern),i=Qn(n.relativePath);if(!/[*?]/.test(r))return i.includes(r);let o=r.includes("/")?r:`**/${r}`;return Sc(o.split("/"),i.split("/"))}function Sc(e,t){if(e.length===0)return t.length===0;let[n,...r]=e;return n==="**"?Sc(r,t)||t.length>0&&Sc(e,t.slice(1)):t.length===0||!IO(n??"",t[0]??"")?!1:Sc(r,t.slice(1))}function IO(e,t){let n="^";for(let r of e)r==="*"?n+="[^/]*":r==="?"?n+="[^/]":n+=wO(r);return n+="$",new RegExp(n).test(t)}function wO(e){return/[\\^$.*+?()[\]{}|]/.test(e)?`\\${e}`:e}function nv(e,t,n){let r=[],i=[],o=new Map;for(let s of[...e].sort(n)){let a=s.channel??"default",c=t[a]??Number.MAX_SAFE_INTEGER,l=o.get(a)??0;if(l>=c){i.push(s);continue}r.push(s),o.set(a,l+1)}return{selected:r,omitted:i}}function vc(e,t,n,r,i=!1){let o=[...e],s=[],a=new Set,c=0;for(;o.length>0&&s.length<t;){let l=o.filter(m=>c+m.evidenceCharacters<=n||i&&s.length===0);if(l.length===0)break;let u=l.filter(m=>m.roles.includes("location")||m.roles.includes("definition")).sort(r);l.sort((m,p)=>tv(p,a)-tv(m,a)||r(m,p));let d=u[0]??l[0];s.push(d),c+=d.evidenceCharacters;for(let m of rv(d))a.add(m.key);o.splice(o.indexOf(d),1)}return{selected:s,omitted:o.sort(r)}}function tv(e,t){let n=rv(e).reduce((o,s)=>o+(t.has(s.key)?0:s.weight),0),r=Math.max(0,8-e.priority)*20,i=Math.min(500,Math.ceil(e.evidenceCharacters/160));return n+r-i}function rv(e){return[...e.reasons.map(PO),...e.roles.map(t=>({key:`role:${t}`,weight:TO(t)})),{key:`file:${e.relativePath}`,weight:180},{key:`scope:${LO(e.relativePath)}`,weight:120},{key:`kind:${e.fileKind}`,weight:40},...e.symbols.map(t=>({key:`symbol:${t}`,weight:100})),...e.behaviorSignals.map(t=>({key:`behavior:${t}`,weight:70}))]}function PO(e){let t=e.indexOf(":"),n=t<0?e:e.slice(0,t);return n==="dependency"||n==="consumer"?{key:`reason:${n}`,weight:220}:{key:`reason:${e}`,weight:n==="location"||n==="definition"?1400:800}}function TO(e){switch(e){case"location":return 1200;case"definition":return 1100;case"reference":return 600;case"caller":case"callee":return 550;case"dependency":case"consumer":return 500;case"search":return 400;default:return 300}}function LO(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}var iv=64,ov=12;function Cc(e,t,n={}){if(t.length===0)return[];let{context:r,limit:i}=AO(n),o=t.map(s=>{if(s.length===0)throw new Error("The source search pattern must not be empty.");return{pattern:s,regexp:n.regexp?gr(s,"source search pattern",n.ignoreCase?"iu":"u"):null,literal:n.ignoreCase?s.toLocaleLowerCase():s,identities:[],fileCoverage:[],textByPath:new Map}});if(!n.regexp&&!n.ignoreCase){let s=o.map(c=>Buffer.from(c.pattern,"utf8")),a=cu(e,{scope:n.scope,literalBytes:s.length===1?s[0]:s},(c,l)=>{let u=oo(c.text);if(u.length!==0)for(let d of l){let m=o[d];m&&sv(e,m,c,u,n)}});return o.map(c=>cv(c,a,r,i,n))}return o.map(s=>{let a=cu(e,{scope:n.scope},c=>{let l=oo(c.text);l.length>0&&sv(e,s,c,l,n)});return cv(s,a,r,i,n)})}function sv(e,t,n,r,i){let o=[];for(let l=0;l<r.length;l+=1)MO(t,r[l]??"",i.ignoreCase)&&o.push(l);if(o.length===0)return;let s=n.relativePath;t.textByPath.set(s,n.text);let a=n.freshness.semantic.state!=="stale"&&n.freshness.semantic.basis!=="no-compiler-document"?D(e,s):[],c=z(e,s)?.callables??[];for(let l of o)t.identities.push(DO(e,n,l,a,c));t.fileCoverage.push({relativePath:s,matchingLines:o.length,returnedMatches:0,freshness:n.freshness})}function MO(e,t,n){let r=t.endsWith("\r")?t.slice(0,-1):t;return e.regexp?e.regexp.test(r):(n?r.toLocaleLowerCase():r).includes(e.literal)}function DO(e,t,n,r,i){let o=t.relativePath,s=ir(r,n),a=co(i,n),c=s&&!he(s.symbol)?s:null,l=av(c?.startLine,a?.startLine,s?.startLine,n),u=av(c?.endLine,a?.endLine,s?.endLine,n),d=To(e,o,n,l,u);return{relativePath:o,focusLine:n,ownerSymbol:c?.symbol??null,ownerShort:c?L(c.symbol):a?.name??(s?L(s.symbol):null),ownerStartLine:d.startLine,ownerEndLine:d.endLine,fileKind:F(o),freshness:t.freshness}}function av(e,t,n,r){return e??t??n??r}function cv(e,t,n,r,i){e.identities.sort(uv);let o=e.identities.length>iv?lv(e.identities,iv):e.identities,a=_O(e,r,i).flatMap(u=>{let d=e.textByPath.get(u.relativePath),m=d===void 0?null:FO(u.relativePath,d,u.focusLine,n);return m?[{...m,...u}]:[]}),c=new Map;for(let u of a)c.set(u.relativePath,(c.get(u.relativePath)??0)+1);for(let u of e.fileCoverage)u.returnedMatches=c.get(u.relativePath)??0;let l=kO(e.fileCoverage);return{pattern:e.pattern,mode:i.regexp?"regexp":"literal",identities:e.identities,...o.length<e.identities.length?{identityManifest:o}:{},identityCoverage:{mode:o.length===e.identities.length?"complete":"bounded",returned:o.length,total:e.identities.length,omitted:e.identities.length-o.length},matches:a,matchingLines:e.identities.length,matchingFiles:e.fileCoverage.length,omittedMatches:Math.max(0,e.identities.length-a.length),fileCoverage:e.fileCoverage,scopeHints:l.slice(0,ov),omittedScopeHints:Math.max(0,l.length-ov),scannedFiles:t.scannedTextFiles,textCoverage:{basis:"current-project-text-files",candidateFiles:t.candidateFiles,scannedTextFiles:t.scannedTextFiles,scannedBytes:t.scannedBytes,skippedBinaryPaths:t.skippedBinaryPaths,skippedUnreadablePaths:t.skippedUnreadablePaths,skippedOversizedPaths:t.skippedOversizedPaths,semanticFiles:t.semanticFiles}}}function FO(e,t,n,r){let i=t.split(`
|
|
26
|
+
`),o=t.endsWith(`
|
|
27
|
+
`)?i.length-1:i.length;if(n<0||n>=o)return null;let s=Math.max(0,n-r),a=Math.min(o-1,n+r);return{relativePath:e,startLine:s,endLine:a,focusLine:n,source:i.slice(s,a+1).join(`
|
|
28
|
+
`)}}function kO(e){let t=new Map;for(let n of e){let r=NO(n.relativePath),i=t.get(r)??{matchingLines:0,matchingFiles:0};i.matchingLines+=n.matchingLines,i.matchingFiles+=1,t.set(r,i)}return[...t.entries()].map(([n,r])=>({scope:n,...r})).sort((n,r)=>r.matchingLines-n.matchingLines||r.matchingFiles-n.matchingFiles||n.scope.localeCompare(r.scope))}function NO(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function lv(e,t){let n=e.map((i,o)=>({...i,priority:sn(i.fileKind),sequence:o,evidenceCharacters:1,roles:["search"],reasons:["search"],symbols:i.ownerSymbol?[i.ownerSymbol]:[],behaviorSignals:[]})),r=[];for(let i of[0,1,2]){let o=t-r.length;if(o===0)break;let s=n.filter(a=>sn(a.fileKind)===i);r.push(...vc(s,o,Number.MAX_SAFE_INTEGER,uv).selected)}return r.map(({priority:i,sequence:o,evidenceCharacters:s,roles:a,reasons:c,symbols:l,behaviorSignals:u,...d})=>d)}function uv(e,t){return sn(e.fileKind)-sn(t.fileKind)||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||e.relativePath.localeCompare(t.relativePath)||e.focusLine-t.focusLine}function AO(e){let t=e.context??6;if(!Number.isSafeInteger(t)||t<0)throw new RangeError(`context must be a non-negative safe integer; received ${t}`);let n=e.limit??12;if(!Number.isSafeInteger(n)||n<=0)throw new RangeError(`limit must be a positive safe integer; received ${n}`);return{context:t,limit:n}}function _O(e,t,n){return t===Number.MAX_SAFE_INTEGER?e.identities:n.ranking?lv(e.identities,t):e.identities.slice(0,t)}function OO(e,t,n={}){if(t.length===0)throw new Error("The source search pattern must not be empty.");return Cc(e,[t],n)[0]}import{createHash as Wv}from"crypto";function dv(e,t){return oe(e)-oe(t)||e.relativePath.localeCompare(t.relativePath)}function ge(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function mv(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 Ee(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))]}function Vo(e){return e.replace(/^#/u,"").replace(/\(\)$/u,"")}function Jo(e,t,n={}){let r=J(e,t);if(r.candidates.length>0)throw new Error(`Ambiguous symbol: ${t}. Use an exact symbol.`);let i=r.match;if(!i)return null;let o=n.semantic!==!1,s=ti(e,i,{semantic:o,semanticEvidence:ie}).filter(u=>be(u.symbol)),a=mv(jt(e,i,{additive:!0,callableOnly:!0,semantic:o,semanticEvidence:ie}).sort((u,d)=>+(ye(d.source)==="exact")-+(ye(u.source)==="exact"))),c=s.map(u=>({symbol:u.symbol,shortName:L(u.symbol),file:u.file,relationship:u.source!=="caller-map-inversion"?"reference-candidate":u.callEvidence==="scip-chunk"?"chunk-candidate":ye(u.callEvidence)==="exact"?"resolved-call":"source-call-candidate",evidenceStrength:u.source==="caller-map-inversion"?ye(u.callEvidence):"candidate",evidenceSource:u.callEvidence??u.source})),l=a.map(u=>({symbol:u.symbol,shortName:L(u.symbol),file:u.file,relationship:u.source==="scip-chunk"?"chunk-candidate":ye(u.source)==="exact"?"resolved-call":"source-call-candidate",evidenceStrength:ye(u.source),evidenceSource:u.source,...u.kind==="jsx-render"?{interaction:"render"}:{}}));return{symbol:i.symbol,shortName:L(i.symbol),callers:c.map(({symbol:u,shortName:d,file:m})=>({symbol:u,shortName:d,file:m})),callees:l.map(({symbol:u,shortName:d,file:m})=>({symbol:u,shortName:d,file:m})),callerEvidence:c,calleeEvidence:l,coverage:{scope:"indexed-static-call-graph",blindSpots:["unresolved dynamic dispatch and reflection","external or unindexed callees without a resolved symbol identity","SCIP chunk co-occurrence and source-name resolution are candidate call evidence"]}}}function Yo(e,t){let n=Ht(e,t);return n?Vr(e,"forward",[n]).filter(i=>!e.isIgnored(i)).map(i=>({relativePath:i,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):[]}function Xo(e,t){let n=Ht(e,t);return n?Vr(e,"reverse",[n]).filter(i=>!e.isIgnored(i)).map(i=>({relativePath:i,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):[]}function pv(e,t,n={}){let r=Qd(e,t,n);return{definitions:r.definitions,referencedBy:r.referencedBy}}function Qd(e,t,n={}){let r=J(e,t);if(r.total>1)throw new Error(`Ambiguous symbol: ${t}. Use an exact symbol.`);let i=r.match;if(!i)return{definitions:[],referencedBy:[],referenceEvidence:[],claimSupport:null};let o=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",i.symbolId),s=oa(o?.documentation??null),a=e.isIgnored(i.relativePath)?[]:[{relativePath:i.relativePath,startLine:i.startLine,endLine:i.endLine,signature:UO(s,o?.display_name??null,i.symbol),source:HO(e,i.relativePath,i.startLine,i.endLine)}],c=n.referenceContext??2,l=Lg(e,i,{semantic:n.semantic,semanticEvidence:ie}).map(d=>{let m=kh(e,d.file,d.line,c,A(i.symbol));return{relativePath:d.file,line:d.line,enclosingSymbol:d.enclosingSymbol,enclosingShort:d.enclosingSymbol?L(d.enclosingSymbol):"(top-level)",provenance:d.provenance,sourceStartLine:m?.startLine??null,sourceEndLine:m?.endLine??null,source:m?.source??null,sourceKind:m?.kind??"unavailable"}}),u=l.map(BO);return{definitions:a,referencedBy:u,referenceEvidence:l.map(d=>({relativePath:d.relativePath,line:d.line,provenance:d.provenance,sourceKind:d.sourceKind})),claimSupport:$O(l)}}function BO(e){return{relativePath:e.relativePath,line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort,sourceStartLine:e.sourceStartLine,sourceEndLine:e.sourceEndLine,source:e.source}}function $O(e){return{referenceAbsence:{status:"ineligible",scope:"observed reference sites",reason:"This source bundle does not establish complete compiler-binding or freshness coverage.",followup:null},callsitePredicates:{status:"ineligible",scope:"source windows around observed references",reason:"Line and name matching does not establish the referenced callee binding for every invocation.",followup:jO(e)}}}function jO(e){let t=[...new Set(e.map(n=>`${n.relativePath}:${n.line+1}`))];return t.length===0||t.length>24?null:`scip-query inspect ${t.map(n=>`--at ${O(n)}`).join(" ")} --view behavior`}function HO(e,t,n,r){let i=it(e,t);if(!i||i.freshness.semantic.state==="stale")return null;let s=i.text.split(`
|
|
29
|
+
`).slice(n,r+1).join(`
|
|
30
|
+
`);return s.length>0?s:null}function UO(e,t,n){let r=ia(e);if(r&&!qO(r))return r;let i=(t??"").trim();return i?be(n)&&!i.endsWith("()")?`${i}()`:i:L(n)}function qO(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function hv(e,t,n={}){let r=zO(e,t,n);if(r.kind!=="matched")return r;let{referenceEvidence:i,claimSupport:o,...s}=r;return s}function zO(e,t,n={}){let r=J(e,t);if(!r.match)return{kind:"missing",query:t};if(r.total>1)return{kind:"ambiguous",query:t,total:r.total,candidates:[{symbol:r.match.symbol,shortName:L(r.match.symbol),relativePath:r.match.relativePath,startLine:r.match.startLine},...r.candidates]};let i=r.match,o=VO(n.parts),s=GO(e,i.symbol,o,n),a=KO(e,i.symbol,o,n),c=n.relatedSourceLines??80;return{kind:"matched",query:t,symbol:i.symbol,shortName:L(i.symbol),file:i.relativePath,parts:o,definition:o.includes("definition")?Bh(e,i.symbol):null,referenceWindows:o.includes("references")?WO(e,s.referencedBy):[],callers:fv(e,a,"callers",o,c),callees:fv(e,a,"callees",o,c),dependencies:o.includes("dependencies")?Yo(e,i.relativePath):[],consumers:o.includes("consumers")?Xo(e,i.relativePath):[],referenceEvidence:s.referenceEvidence,claimSupport:s.claimSupport}}function GO(e,t,n,r){return n.includes("definition")||n.includes("references")?Qd(e,t,{semantic:r.semantic,referenceContext:r.referenceContext}):{definitions:[],referencedBy:[],referenceEvidence:[],claimSupport:null}}function KO(e,t,n,r){return n.includes("callers")||n.includes("callees")?Jo(e,t,{semantic:r.semantic}):null}function fv(e,t,n,r,i){if(!r.includes(n))return[];let o=n==="callers"?t?.callerEvidence??[]:t?.calleeEvidence??[];return JO(e,o,i)}function WO(e,t){let n=t.filter(i=>i.sourceStartLine!==null&&i.sourceEndLine!==null&&i.source!==null).sort((i,o)=>i.relativePath.localeCompare(o.relativePath)||i.sourceStartLine-o.sourceStartLine||i.line-o.line),r=[];for(let i of n){let o=r[r.length-1];if(o&&o.relativePath===i.relativePath&&i.sourceStartLine<=o.endLine+1){o.endLine=Math.max(o.endLine,i.sourceEndLine),o.references.push(gv(i)),o.source=j(e,o.relativePath).slice(o.startLine,o.endLine+1).join(`
|
|
31
|
+
`);continue}r.push({relativePath:i.relativePath,startLine:i.sourceStartLine,endLine:i.sourceEndLine,source:i.source,references:[gv(i)]})}return r}function gv(e){return{line:e.line,enclosingSymbol:e.enclosingSymbol,enclosingShort:e.enclosingShort}}function VO(e){let t=e&&e.length>0?e:["definition","references"];return[...new Set(t)]}function JO(e,t,n){let r=[],i=new Set;for(let o of t){if(i.has(o.symbol))continue;i.add(o.symbol);let s=(o.file?D(e,o.file).find(c=>c.symbol===o.symbol):void 0)??J(e,o.symbol).match;if(!s)continue;let a=Nh(e,s.relativePath,s.startLine,s.endLine,n);a&&r.push({...a,symbol:o.symbol,shortName:o.shortName,evidenceStrength:o.evidenceStrength,omittedLines:Math.max(0,s.endLine-a.endLine)})}return r}var yv=new WeakMap,bv=new WeakMap,Sv=new WeakMap,vv=new WeakMap,Cv=new WeakMap;function Rv(e,t){let n=bv.get(e);n||(n=new Map,bv.set(e,n));let r=n.get(t);if(r)return r;let i=_(e,t)?.rootNode;if(!i)return n.set(t,[]),[];let o=new Set;Vt(i,l=>{if(l.type!=="call_expression")return;let u=l.childForFieldName("function")??l.namedChild(0),d=/^([A-Za-z_$][\w$]*(?:\.Service)?)\.of$/u.exec(u?.text.replace(/\s+/gu,"")??"");d&&o.add(d[1])});let s=V(e,t).filter(l=>!!l.sourcePath),a=new Set;for(let l of o)YO(e,t,s,l,a);let c=tm([...a]).sort();return n.set(t,c),c}function YO(e,t,n,r,i){let o=/^([A-Za-z_$][\w$]*)\.Service$/u.exec(r);if(o){for(let s of n)s.localName===o[1]&&i.add(s.sourcePath);return}if(r==="Service"){D(e,t).some(s=>s.leaf==="Service")&&i.add(t);for(let s of n)(s.localName??s.importedName)==="Service"&&i.add(s.sourcePath)}}function Qo(e,t,n={}){let i=rr(e,t)?.filter(l=>!n.ranges||n.ranges.some(u=>l.line>=u.startLine&&l.line<=u.endLine));if(!i)return{targets:[],unresolvedCallsites:0};let o=XO(e,t),s=ei(e),a=[],c=0;for(let l of i){if(!l.memberAccess)continue;let u=Zr(t,s.get(l.calleeLeaf)??[]);if(n.excludeIndexedTargets!==!1&&ma(e,t,u,!0,l.calleeQualifier))continue;let d=QO(o,l);d.length===0&&(c+=1);for(let m of d)a.push(m)}return{targets:a,unresolvedCallsites:c}}function XO(e,t){let n=V(e,t).filter(a=>!!a.sourcePath),r=MB(H(e,t)??""),i=_(e,t)?.rootNode??null,o=i?tB(i):Ev();return{db:e,sourceFile:t,sourceImports:n,sourceAliases:r,serviceReceivers:o,callablesByFile:new Map}}function QO(e,t){let{db:n,sourceFile:r,sourceImports:i,serviceReceivers:o}=e,s=TB(n,r,t,i);if(s)return[s];let a=eB(n,r,t,i,oB(o,t.calleeQualifier,t.line));if(a.length>0)return a;let c=sB(n,r,t);return c.length>0?c:ZO(e,t)}function ZO(e,t){let{db:n,sourceFile:r,sourceImports:i,sourceAliases:o,callablesByFile:s}=e,a=t.calleeQualifier,c=a?o.get(a)??a:null,u=(c?tm(i.filter(m=>(m.localName??m.importedName)===c).map(m=>m.sourcePath)):[]).flatMap(m=>{let p=s.get(m);return p||(p=_t(n,m)??[],s.set(m,p)),p.filter(f=>f.name===t.calleeLeaf).map(f=>({file:m,callable:f}))});if(u.length!==1)return[];let d=u[0];return[{calleeLeaf:t.calleeLeaf,line:t.line,sourceFile:r,targetFile:d.file,targetStartLine:d.callable.startLine,targetEndLine:d.callable.endLine,resolution:"direct-import-receiver",strength:"candidate"}]}function eB(e,t,n,r,i){let o=n.calleeQualifier;if(!o||!/^[A-Za-z_$][\w$]*$/u.test(o))return[];if(i.size!==1)return[];let s=[...i][0],a=tm(r.filter(u=>u.localName===s||u.importedName===s).map(u=>u.sourcePath));if(a.length!==1)return[];let c=a[0],l=pB(e,c,n.calleeLeaf);return l.map(u=>({calleeLeaf:u.name,line:n.line,sourceFile:t,targetFile:u.file,targetStartLine:u.startLine,targetEndLine:u.endLine,serviceFile:c,resolutionAlternativeCount:l.length,resolution:"imported-service-object-member",strength:"candidate"}))}function Ev(){return{declarations:new Map,callbacks:[]}}function tB(e){let t=Ev();return Vt(e,n=>{if(n.type==="variable_declarator"){nB(n,t);return}rB(n,t)}),t}function nB(e,t){let n=e.childForFieldName("name")??e.namedChild(0),r=e.childForFieldName("value")??e.namedChild(1);if(n?.type!=="identifier"||!r)return;let i=new Set;if(Vt(r,o=>{if(o.type!=="member_expression")return;let s=o.childForFieldName("object")??o.namedChild(0),a=o.childForFieldName("property")??o.namedChild(1);s?.type==="identifier"&&a?.text==="Service"&&i.add(s.text)}),i.size===1){let o=t.declarations.get(n.text)??[];o.push({line:e.startPosition.row,alias:[...i][0]}),t.declarations.set(n.text,o)}}function rB(e,t){if(!["arrow_function","function_expression","generator_function"].includes(e.type))return;let n=e.childForFieldName("parameters")??e.childForFieldName("parameter");if(!n)return;let r=iB(e);if(r===null)return;let i=new Set;Vt(n,o=>{o.type==="identifier"&&i.add(o.text)}),i.size!==0&&t.callbacks.push({startLine:e.startPosition.row,endLine:e.endPosition.row,receivers:i,alias:r})}function iB(e){let t=e.parent;for(;t&&t.type!=="call_expression";)t=t.parent;if(!t)return null;let n=t.childForFieldName("function")??t.namedChild(0),r=/^([A-Za-z_$][\w$]*)\.Service\.use$/u.exec(n?.text??"");return r?r[1]:null}function oB(e,t,n){if(!t||!/^[A-Za-z_$][\w$]*$/u.test(t))return new Set;let r=new Set((e.declarations.get(t)??[]).filter(i=>i.line<=n).map(i=>i.alias));for(let i of e.callbacks)i.startLine<=n&&i.endLine>=n&&i.receivers.has(t)&&r.add(i.alias);return r}function sB(e,t,n){let r=aB(e,t,n);if(!r)return[];let i=vv.get(e);i||(i=new Map,vv.set(e,i));let o=`${r.symbol}\0${n.calleeLeaf}`,s=i.get(o);if(!s){let a=[];for(let c of mo(e,r))a.push(...cB(e,r.leaf,c.file,c.line,n.calleeLeaf));s=a.filter((c,l,u)=>u.findIndex(d=>d.file===c.file&&d.startLine===c.startLine&&d.endLine===c.endLine&&d.name===c.name)===l),i.set(o,s)}return s.map(a=>({calleeLeaf:a.name,line:n.line,sourceFile:t,targetFile:a.file,targetStartLine:a.startLine,targetEndLine:a.endLine,resolutionAlternativeCount:s.length,resolution:"factory-callback-member",strength:s.length===1?"exact":"candidate"}))}function aB(e,t,n){let r=n.calleeQualifier;if(!r||!/^[A-Za-z_$][\w$]*$/u.test(r))return null;let i=_(e,t)?.rootNode;if(!i)return null;let o=uB(e,t,i,n.line,n.calleeLeaf,r),s=o?mB(o,r):null;if(!s||!dB(s))return null;let a=(_t(e,t)??[]).filter(l=>l.startLine<=s.startPosition.row&&l.endLine>=s.endPosition.row).sort((l,u)=>l.endLine-l.startLine-(u.endLine-u.startLine))[0];if(!a)return null;let c=D(e,t).filter(l=>l.isFunctionLike&&l.leaf===a.name);return c.length!==1?null:c[0]}function cB(e,t,n,r,i){let o=_(e,n)?.rootNode;if(!o)return[];let s=Xs(o,"call_expression").filter(l=>l.startPosition.row>r||l.endPosition.row<r?!1:(l.childForFieldName("function")??l.namedChild(0))?.text.replace(/\s+/gu,"").replace(/<[^<>]*>$/u,"").match(/[A-Za-z_$][\w$]*$/u)?.[0]===t);if(s.length!==1)return[];let c=s[0].childForFieldName("arguments")?.namedChildren.find(l=>vr(l).type==="object");return c?vr(c).namedChildren.flatMap(l=>lB(e,n,i,l)):[]}function lB(e,t,n,r){if(r.type==="shorthand_property_identifier"&&r.text===n)return xc(e,t,n,r,r);if(r.type!=="pair")return[];let i=r.childForFieldName("key")??r.namedChild(0),o=r.childForFieldName("value")??r.namedChild(1);return Rc(i?.text)!==n||!o?[]:xc(e,t,n,o,r)}function uB(e,t,n,r,i,o){let s=Sv.get(e);s||(s=new Map,Sv.set(e,s));let a=s.get(t);return a||(a=FB(n),s.set(t,a)),a.get(`${r}\0${o}\0${i}`)??null}function dB(e){return e.descendantsOfType("return_statement").some(t=>{let n=t.childForFieldName("argument")??t.namedChild(0);return!!(n&&vr(n).type==="object")})}function mB(e,t){let n=e.parent;for(;n;){if(/(?:function|method|lambda)/u.test(n.type)||n.type==="arrow_function"){let r=n.childForFieldName("parameters")??n.childForFieldName("parameter"),i=!1;if(r&&Vt(r,o=>{o.type==="identifier"&&o.text===t&&(i=!0)}),i)return n}n=n.parent}return null}function xc(e,t,n,r,i){if(r.type==="identifier")return(_t(e,t)??[]).filter(c=>c.name===r.text).map(c=>({...c,file:t}));let o=Zd(e,t,r.text);if(o.length>0)return o;if(!em(r))return[];let a=(_t(e,t)??[]).filter(c=>c.startLine>=i.startPosition.row&&c.endLine<=i.endPosition.row&&(c.name===n||c.name.startsWith("source@"))).sort((c,l)=>c.endLine-c.startLine-(l.endLine-l.startLine))[0];return[a?{...a,file:t}:{name:n,file:t,startLine:i.startPosition.row,endLine:i.endPosition.row}]}function pB(e,t,n){let r=Cv.get(e);r||(r=new Map,Cv.set(e,r));let i=`${t}\0${n}`,o=r.get(i);if(o)return o;let s=hB(e,t).flatMap(a=>fB(e,a,t,n));return r.set(i,s),s}function fB(e,t,n,r){let i=_(e,t)?.rootNode,o=_t(e,t)??[];if(!i)return[];let s=yB(e,t,n);if(s.size===0)return[];let a=new Set,c=[],l=[],u=[];return Vt(i,m=>{if(gB(m,s)){if(m.type==="pair"){let{key:p,value:f}=OB(m);if(Rc(p?.text)!==r||!f)return;f.type==="identifier"?a.add(f.text):em(f)?c.push({name:r,startLine:m.startPosition.row,endLine:m.endPosition.row}):DB(e,t,f,m,u,l);return}m.type==="shorthand_property_identifier"&&m.text===r&&a.add(r)}}),[...o.filter(m=>a.has(m.name)).map(m=>({...m,file:t})),...c.map(m=>({...m,file:t})),...l.map(m=>({...m,file:t})),...u].filter((m,p,f)=>f.findIndex(g=>g.file===m.file&&g.name===m.name&&g.startLine===m.startLine&&g.endLine===m.endLine)===p)}function gB(e,t){let n=e,r=null;for(;n;){if(n.type==="object"&&(r=n),n.type==="call_expression"){if(!r)return!1;let i=n.childForFieldName("function")??n.namedChild(0);return i?t.has(i.text.replace(/\.of$/u,""))&&i.text.endsWith(".of"):!1}n=n.parent}return!1}function hB(e,t){let n=yv.get(e);n||(n=new Map,yv.set(e,n));let r=n.get(t);if(r)return r;let i=new Set([t]),o=D(e,t).filter(a=>a.leaf==="Service"&&a.isTypeLike);for(let a of o)for(let c of mo(e,a))i.add(c.file);let s=[...i].sort();return n.set(t,s),s}function yB(e,t,n){let r=new Set;ze(t,n)&&r.add("Service");for(let i of V(e,t))!i.sourcePath||!ze(i.sourcePath,n)||kB(i,r);return r}function Zd(e,t,n){let r=Iv(e,t,n);if(!r)return[];let{factory:i,memberName:o}=r,s=_(e,i.relativePath)?.rootNode;if(!s)return[];let a=ou(s,i.startLine,i.endLine);if(!a)return[];let c=[];for(let l of a.descendantsOfType("return_statement")){let u=l.childForFieldName("argument")??l.namedChild(0);if(!u)continue;let d=vr(u);if(d.type==="object")for(let m of d.namedChildren)for(let p of bB(e,i.relativePath,o,m))c.push(p)}return c.filter((l,u,d)=>d.findIndex(m=>m.file===l.file&&m.name===l.name&&m.startLine===l.startLine&&m.endLine===l.endLine)===u)}function xv(e,t,n){return(_t(e,t)??[]).filter(r=>r.name===n).map(r=>({...r,file:t}))}function bB(e,t,n,r){if(r.type==="shorthand_property_identifier"&&r.text===n)return xv(e,t,n);if(r.type!=="pair")return[];let i=r.childForFieldName("key")??r.namedChild(0),o=r.childForFieldName("value")??r.namedChild(1);return Rc(i?.text)!==n||!o?[]:o.type==="identifier"?xv(e,t,o.text):em(o)?[{name:n,startLine:r.startPosition.row,endLine:r.endPosition.row,file:t}]:[]}function SB(e,t,n){let r=Iv(e,t,n);if(!r)return[];let{factory:i,factoryCall:o}=r,s=_(e,i.relativePath)?.rootNode;if(!s)return[];let a=ou(s,i.startLine,i.endLine);if(!a)return[];let c=vB(a);if(c.size===0)return[];let l=Zd(e,t,n);if(l.length===0)return[];let u=CB(e,i,l,c);return u.size===0?[]:xB(e,t,o,u)}function Iv(e,t,n){let r=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(n.replace(/\s+/gu,""));if(!r)return null;let i=_(e,t)?.rootNode;if(!i)return null;let o=RB(i,r[1]),s=o?EB(o):null,a=s?.childForFieldName("function")??s?.namedChild(0),c=a?IB(e,t,a.text):[];return c.length!==1||!s?null:{factory:c[0],factoryCall:s,memberName:r[2]}}function vB(e){let t=new Set,n=e.childForFieldName("parameters")??e.childForFieldName("parameter");return n&&Vt(n,r=>{r.type==="identifier"&&t.add(r.text)}),t}function CB(e,t,n,r){let i=(_t(e,t.relativePath)??[]).filter(l=>l.startLine>=t.startLine&&l.endLine<=t.endLine),o=(rr(e,t.relativePath)??[]).filter(l=>l.line>=t.startLine&&l.line<=t.endLine),s=new Set,a=n.map(l=>({name:l.name,startLine:l.startLine,endLine:l.endLine})),c=new Set;for(;a.length>0&&c.size<32;){let l=a.shift(),u=`${l.name}\0${l.startLine}\0${l.endLine}`;if(!c.has(u)){c.add(u);for(let d of o.filter(m=>m.line>=l.startLine&&m.line<=l.endLine))NB(d,r,s,i,a)}}return s}function xB(e,t,n,r){let o=n.childForFieldName("arguments")?.namedChildren.find(a=>vr(a).type==="object");if(!o)return[];let s=[];for(let a of vr(o).namedChildren){if(a.type==="shorthand_property_identifier"&&r.has(a.text)){s.push(...xc(e,t,a.text,a,a));continue}s.push(...AB(e,t,a,r))}return s.filter((a,c,l)=>l.findIndex(u=>u.file===a.file&&u.name===a.name&&u.startLine===a.startLine&&u.endLine===a.endLine)===c)}function RB(e,t){for(let n of Xs(e,"variable_declarator"))if((n.childForFieldName("name")??n.namedChild(0))?.text===t)return n.childForFieldName("value")??n.namedChild(1);return null}function EB(e){return e.type==="call_expression"?e:e.descendantsOfType("call_expression")[0]??null}function IB(e,t,n){let r=n.replace(/\s+/gu,"").replace(/<[^<>]*>$/u,""),i=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(r);if(i)return wB(e,t,i[1],i[2]);if(!/^[A-Za-z_$][\w$]*$/u.test(r))return[];let o=D(e,t).filter(u=>u.leaf===r&&u.isFunctionLike);if(o.length>0)return o;let s=(_t(e,t)??[]).filter(u=>u.name===r).map(u=>({...u,relativePath:t}));if(s.length>0)return s;let a=V(e,t).filter(u=>u.localName===r&&u.sourcePath&&u.kind!=="namespace");if(a.length!==1||!a[0].sourcePath)return[];let c=a[0].sourcePath,l=a[0].importedName==="default"?r:a[0].importedName;return wv(e,c,l)}function wB(e,t,n,r){let i=V(e,t).filter(o=>o.localName===n&&o.sourcePath);return i.length!==1||!i[0].sourcePath?[]:wv(e,i[0].sourcePath,r)}function wv(e,t,n){let r=En(e,t,n).filter(i=>i.isFunctionLike);return r.length>0?r:(_t(e,t)??[]).filter(i=>i.name===n).map(i=>({...i,relativePath:t}))}function em(e){return["arrow_function","function_expression","generator_function"].includes(e.type)||e.descendantsOfType(["arrow_function","function_expression","generator_function"]).length>0}function PB(e){let t=e.parent;for(;t;){if(t.type==="variable_declarator"){let n=t.childForFieldName("name")??t.namedChild(0);if(n?.type==="identifier")return{name:n.text,startLine:t.startPosition.row,endLine:t.endPosition.row}}t=t.parent}return null}function Rc(e){return e?e.replace(/^(?:['"])(.*)(?:['"])$/u,"$1"):null}function TB(e,t,n,r){let i=/^this\.([A-Za-z_$][\w$]*)$/u.exec(n.calleeQualifier??"");if(!i)return null;let o=_(e,t)?.rootNode;if(!o)return null;let s=LB(o,n.line);if(!s)return null;let a=new Set;if(Vt(s,p=>{if(p.type!=="assignment_expression")return;let f=p.childForFieldName("left")??p.namedChild(0),g=p.childForFieldName("right")??p.namedChild(p.namedChildCount-1);if(f?.text.replace(/\s+/gu,"")!==`this.${i[1]}`||!g)return;let h=vr(g);if(h.type!=="new_expression")return;let S=(h.childForFieldName("constructor")??h.namedChild(0))?.text.match(/[A-Za-z_$][\w$]*$/u)?.[0];S&&a.add(S)}),a.size!==1)return null;let c=[...a][0],l=r.filter(p=>p.localName===c);if(l.length!==1)return null;let u=_B(e,l[0],c),d=D(e,l[0].sourcePath).filter(p=>p.isFunctionLike&&p.leaf===n.calleeLeaf&&mg(p.symbol)===u);if(d.length!==1)return null;let m=d[0];return{calleeLeaf:n.calleeLeaf,line:n.line,sourceFile:t,targetFile:m.relativePath,targetStartLine:m.startLine,targetEndLine:m.endLine,targetSymbol:m.symbol,resolution:"constructed-member-receiver",strength:"exact"}}function LB(e,t){let n=[];return Vt(e,r=>{["class","class_declaration","class_definition"].includes(r.type)&&r.startPosition.row<=t&&r.endPosition.row>=t&&n.push(r)}),n.sort((r,i)=>r.endPosition.row-r.startPosition.row-(i.endPosition.row-i.startPosition.row))[0]??null}function vr(e){let t=e;for(;["parenthesized_expression","as_expression","type_assertion","satisfies_expression"].includes(t.type)&&t.namedChildCount===1;)t=t.namedChild(0);return t}function Vt(e,t){t(e);for(let n of e.namedChildren)Vt(n,t)}function MB(e){let t=new Map,n=/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*([A-Za-z_$][\w$]*)\s*;/gu;for(let r of e.matchAll(n)){let i=r[1],o=r[2];i&&o&&t.set(i,o)}return t}function tm(e){let t=[];for(let n of e)t.some(r=>ze(r,n))||t.push(n);return t}function DB(e,t,n,r,i,o){let s=SB(e,t,n.text),a=Zd(e,t,n.text);if(s.length>0)i.push(...s);else if(a.length>0)i.push(...a);else{let c=PB(r);c&&o.push(c)}}function FB(e){let t=new Map;for(let n of Xs(e,"call_expression")){let r=n.childForFieldName("function")??n.namedChild(0),i=/^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/u.exec(r?.text.replace(/\s+/gu,"")??"");if(i)for(let o=n.startPosition.row;o<=n.endPosition.row;o+=1){let s=`${o}\0${i[1]}\0${i[2]}`,a=t.get(s);(!a||n.endIndex-n.startIndex<a.endIndex-a.startIndex)&&t.set(s,n)}}return t}function kB(e,t){if(e.kind==="namespace"&&e.localName){t.add(`${e.localName}.Service`);return}(e.importedName==="default"?e.localName:e.importedName)==="Service"?t.add(e.localName??e.importedName):e.localName&&e.importedName!=="default"&&t.add(`${e.localName}.Service`)}function NB(e,t,n,r,i){if(e.memberAccess&&e.calleeQualifier&&t.has(e.calleeQualifier)){n.add(e.calleeLeaf);return}if(e.memberAccess)return;let o=r.filter(s=>s.name===e.calleeLeaf);o.length===1&&i.push(o[0])}function AB(e,t,n,r){if(n.type!=="pair")return[];let i=n.childForFieldName("key")??n.namedChild(0),o=n.childForFieldName("value")??n.namedChild(1),s=Rc(i?.text);return!s||!r.has(s)||!o?[]:xc(e,t,s,o,n)}function _B(e,t,n){let r=t.importedName==="default"?n:t.importedName,i=t.importedName==="default"?En(e,t.sourcePath,n):[];return i.length===1?i[0].leaf:r}function OB(e){let t=e.childForFieldName("key")??e.namedChild(0),n=e.childForFieldName("value")??e.namedChild(1);return{key:t,value:n}}function nm(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=q(e,{includeIgnored:!1}),o=ei(e),s=t??Pe(e),a=new Set(s.map(l=>l.symbolId)),c=KB(s);return BB(e,r,i,o,a,c),jB(e,r,s,a),zB(e,r,i,o,a,c),n.semantic!==!1&&n.semanticEvidence&&VB(r,n.semanticEvidence.callerMap(e,WB(s))),r}function BB(e,t,n,r,i,o){for(let s of n){if(!se(s))continue;let a=rr(e,s);if(a)for(let c of a)o&&!o.has(c.calleeLeaf)||$B(e,t,s,c,r,i)}}function $B(e,t,n,r,i,o){let s=Zr(n,i.get(r.calleeLeaf)??[]);if(!s||s.length===0)return;let a=ma(e,n,s,r.memberAccess,r.calleeQualifier);a&&o.has(a.symbolId)&&a.file!==n&&rm(t,a.symbolId,n)}function jB(e,t,n,r){let i=UB(n);for(let o of HB(e,r))e.isIgnored(o.relative_path)||qB(o,i.get(o.symbol_id))||rm(t,o.symbol_id,o.relative_path)}function HB(e,t){return da(e,t?[...t]:void 0)}function UB(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 qB(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function zB(e,t,n,r,i,o){for(let s of n){if(se(s)!=="rust")continue;let a=Wr(e,s,{includeRustAttributeNames:!0});if(a.length!==0)for(let{name:c}of a)o&&!o.has(c)||GB(t,s,r.get(c),i)}}function GB(e,t,n,r){if(n)for(let i of n)r.has(i.symbolId)&&i.file!==t&&rm(e,i.symbolId,t)}function rm(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function KB(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"?A(n.symbol):"";r&&t.add(r)}return t.size>0?t:null}function WB(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function VB(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)}}var JB=X("cross-file-caller-files",{clearGroups:["whole-project","source-file"]}),YB=X("source-fallback-caller-files",{clearGroups:["whole-project","source-file"]});function Pv(e,t,n){let r=t.filter(o=>!e.has(o.symbolId));if(r.length>0){let o=n(r);for(let s of r)e.set(s.symbolId,o.get(s.symbolId)??new Set)}let i=new Map;for(let o of t){let s=e.get(o.symbolId);s&&s.size>0&&i.set(o.symbolId,new Set(s))}return i}function im(e,t,n={}){if(t===void 0)return nm(e,t,n);let r=Pv(JB.get(e,()=>new Map),t,i=>nm(e,i,{semantic:!1}));return n.semantic===!1||!n.semanticEvidence?r:Lv(r,n.semanticEvidence.callerMap(e,t.filter(i=>"relativePath"in i&&"symbol"in i&&"leaf"in i)))}function Zo(e,t,n={}){return n.skipPath?uu(e,t,n):Pv(YB.get(e,()=>new Map),t,r=>uu(e,r))}function Tv(e,t,n={}){let r=im(e,t,{semantic:n.semantic,semanticEvidence:n.semanticEvidence});return n.sourceFallback===!1?r:Lv(r,Zo(e,t))}function Lv(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 Mv(e,t,n){let r=t.identifierResolution==="strict"?lu:Pg,i=t.candidateNames?Rg(t.candidateNames):null,o={scannedPaths:0,candidateMatchedPaths:0,visitedNames:0,visitedHits:0,currentPath:""};for(let s of t.paths)if(o.scannedPaths+=1,o.currentPath=s,!!XB(e,s,t))try{if(i&&!Eg(H(e,s),i))continue;o.candidateMatchedPaths+=1,QB(e,s,t,r,n,o)}finally{t.afterPath?.(s),o.scannedPaths%10===0&&M("source-reference-scan.progress",()=>{},()=>({scannedPaths:o.scannedPaths,currentPath:o.currentPath,candidateMatchedPaths:o.candidateMatchedPaths,visitedNames:o.visitedNames,visitedHits:o.visitedHits}))}}function XB(e,t,n){return!(!se(t)&&!(n.includeVueSfc&&rg(t))||e.isIgnored(t)||n.skipPath?.(t))}function QB(e,t,n,r,i,o){let s=(c,l,u,d)=>{if(n.candidateNames&&!n.candidateNames.has(c))return;o.visitedNames+=1;let m=n.resolveTargets?n.resolveTargets({sourceFile:t,name:c,kind:l,defaultTargets:d}):d();for(let p of m)o.visitedHits+=1,i({sourceFile:t,name:c,target:p,occurrences:u,kind:l})},a=Sg(e,t);for(let[c,l]of a)s(c,"identifier",l.length,()=>r(e,t,c));for(let c of Wr(e,t,{includeCrossLanguageDispatchNames:n.includeCrossLanguageDispatchNames,includeRustAttributeNames:n.includeRustAttributeNames})){let l=c.kind==="cross-language-dispatch"?()=>lu(e,t,c.name):()=>r(e,t,c.name);s(c.name,c.kind,c.occurrences,l)}}var N=class{constructor(t){this.db=t}db;scopedDefinitions(t){return gg(this.db,t)}definitionsForFile(t){return D(this.db,t)}productionCallableDefinitions(t={}){return bc(this.db,t)}calleeMap(t,n={}){return fo(this.db,t,{...n,semanticEvidence:ie})}callableCallees(t,n={}){return jt(this.db,t,{...n,additive:!0,callableOnly:!0,semanticEvidence:ie}).map(r=>({...r,evidenceStrength:ye(r.source)}))}crossFileCallerMap(t,n={}){return im(this.db,t,{...n,semanticEvidence:ie})}sourceFallbackCallerFiles(t,n={}){return Zo(this.db,t,n)}callerFileMap(t,n={}){return Tv(this.db,t,{...n,semanticEvidence:ie})}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 q(this.db,{includeIgnored:!1}))if(se(i)==="rust")for(let{name:o}of Wr(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 Fe(this.db,t)}fileKind(t){return F(t)}hasSuppressionComment(t){return eg(this.db,t.relativePath,t.startLine)}sourceFiles(){return Kr(this.db)}scanSourceReferences(t,n){Mv(this.db,t,n)}callableSignature(t){let n=on(this.db).forFile(t.relativePath,{facts:!0}).facts?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};var kv=6;function Nv(e,t,n){return`${e}\0${t}\0${n??t}`}function Av(e,t,n,r={}){let i=r.limit??kv;if(!Number.isSafeInteger(i)||i<=0)throw new RangeError(`next-anchor limit must be a positive safe integer; received ${i}`);let o=r.sourceAllowed??(()=>!0),s=new Map(t.nodes.map(C=>[C.id,C])),a=new Set(n.steps.map(C=>C.nodeId)),c=new Set(n.steps.flatMap(C=>{let R=om(s.get(C.nodeId));return R?[R]:[]})),l=new Set;E$(n,c,l);let u=C=>C.symbol!==null&&c.has(C.symbol)||l.has(Nv(C.file,C.line,C.endLine)),d=new Map(n.steps.flatMap(C=>{if(!C.location)return[];let R=om(s.get(C.nodeId));if(!R)return[];let P=D(e,C.location.file).find(w=>w.symbol===R);return P?[[C.id,P]]:[]})),m=new N(e).calleeMap([...d.values()],{additive:!1,semantic:!0}),p=[],f=new Set,g=new Set,h=0,y=0,S=0,I=0,x=0,E=0,b=0,v=0;for(let C of n.steps){if(!C.location||!C.behavior)continue;let R=ZB(C,{db:e,topology:t,nodeById:s,returnedNodeIds:a,sourceAllowed:o,alternativeAlreadyReturned:u});p.push(...R.candidates),E+=R.upstreamCandidates,v+=R.runtimeCandidates,b+=R.resultCandidates;let P=r$(C,{db:e,topology:t,nodeById:s,returnedNodeIds:a,sourceAllowed:o,alternativeAlreadyReturned:u},f);p.push(...P);let w=i$(C,{db:e,topology:t,nodeById:s,returnedNodeIds:a,sourceAllowed:o,alternativeAlreadyReturned:u},{evidencedCallsiteKeys:f,consideredCandidateKeys:g,calleeMap:m,stepDefinition:d.get(C.id)});p.push(...w.candidates),h+=w.scannedBehaviorSteps,y+=w.visibleCallsites,S+=w.identityCandidateCallsites,I+=w.ambiguousCallsites,x+=w.unresolvedCallsites}return jv(e,p,n.steps,i,{scannedBehaviorSteps:h,visibleCallsites:y,graphEvidencedCallsites:f.size,identityCandidateCallsites:S,ambiguousCallsites:I,unresolvedCallsites:x,upstreamCandidates:E,resultCandidates:b,runtimeCandidates:v},r.selectionTerms)}function ZB(e,t){let n=[],r=0,i=0,o=0;if(!e.location||!e.behavior)return{candidates:n,upstreamCandidates:r,resultCandidates:i,runtimeCandidates:o};let s=t.topology.edges.filter(c=>["call","runtime-boundary"].includes(c.kind)&&(c.fromNodeId===e.nodeId||c.toNodeId===e.nodeId)&&c.disposition!=="excluded"&&c.disposition!=="unsupported");for(let c of s){let l=t$(e,t,c);l&&(n.push(l),l.anchor.direction==="upstream"&&(r+=1),c.kind==="runtime-boundary"&&(o+=1))}let a=t.topology.edges.filter(c=>c.kind==="reference"&&c.fromNodeId===e.nodeId&&c.disposition!=="excluded"&&c.disposition!=="unsupported"&&!t.returnedNodeIds.has(c.toNodeId));for(let c of a){let l=n$(e,t,c,e.location,e.behavior);l&&(n.push(l),l.anchor.causalRole==="result-callback"&&(i+=1))}return{candidates:n,upstreamCandidates:r,resultCandidates:i,runtimeCandidates:o}}function e$(e,t){return e.kind==="runtime-boundary"?t?"runtime-producer":"runtime-consumer":t?"caller":"callee"}function _v(e,t){return!!(t?.location&&e.sourceAllowed(t.location.file))}function t$(e,t,n){let r=n.toNodeId===e.nodeId,i=r?n.fromNodeId:n.toNodeId;if(t.returnedNodeIds.has(i))return;let o=t.nodeById.get(i);if(!_v(t,o))return;let s=n.kind==="call"?cm(t.db,o):am(o);if(!s||t.alternativeAlreadyReturned(s))return;let a=lm(n,o.location.file)??o.location,c=r?"upstream":"downstream",l=e$(n,r),u=um(n.evidence),d=es(o),m=()=>{let p=j(t.db,a.file)[a.line]?.trim();return{file:a.file,line:a.line,endLine:a.endLine??a.line,text:p||`${o.label} \u2192 ${e.label}`,signals:["call"],calleeLeaf:d}};return{anchor:{id:Cr(e.id,a.line,o.id),status:u,source:"graph-relation",direction:c,causalRole:l,relationKind:n.kind,fromStepId:e.id,fromLabel:e.label,callsite:m(),alternatives:[s],alternativeCount:1,evidence:n.evidence}}}function n$(e,t,n,r,i){let o=t.nodeById.get(n.toNodeId);if(!_v(t,o))return;let s=cm(t.db,o);if(!s||t.alternativeAlreadyReturned(s))return;let a=es(o),c=lm(n,r.file)?.line,l=i.lines.find(m=>(c===void 0||c>=m.line&&c<=m.endLine)&&m.text.includes(a));if(!l)return;let u=Bv(l.signals),d=um(n.evidence);return{anchor:{id:Cr(e.id,l.line,o.id),status:d,source:"graph-relation",direction:"downstream",causalRole:u,relationKind:"reference",fromStepId:e.id,fromLabel:e.label,callsite:{file:r.file,line:l.line,endLine:l.endLine,text:l.text,signals:l.signals,calleeLeaf:a},alternatives:[s],alternativeCount:1,evidence:n.evidence}}}function r$(e,t,n){let r=[];if(!e.location)return r;let i=wn(t.db,e.location.file,e.location.line,e.location.endLine??e.location.line),o=j(t.db,e.location.file),s=ln(t.db,e.location.file,e.location.line,e.location.endLine??e.location.line);for(let a of i.targets){if(!t.sourceAllowed(a.definition.relativePath))continue;let c=Si(e.location.file,a.sourceLine,a.calleeLeaf);if(n.has(c))continue;n.add(c);let l=sm(s.get(a.sourceLine)),u={symbol:a.definition.symbol,label:a.definition.leaf,file:a.definition.relativePath,line:a.definition.startLine,endLine:a.definition.endLine};t.alternativeAlreadyReturned(u)||r.push({anchor:{id:Cr(e.id,a.sourceLine,a.definition.symbol),status:"exact",source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:e.id,fromLabel:e.label,callsite:{file:e.location.file,line:a.sourceLine,endLine:a.sourceLine,text:o[a.sourceLine]?.trim()||`${a.calleeLeaf}()`,signals:l,calleeLeaf:a.calleeLeaf},alternatives:[u],alternativeCount:1,evidence:[{method:"scip-occurrence-callsite",strength:a.implementationStatus==="unresolved"?"candidate":"exact",identity:a.definition.symbol,location:{file:e.location.file,line:a.sourceLine}}]}})}return r}function i$(e,t,n){let r={candidates:[],scannedBehaviorSteps:0,visibleCallsites:0,identityCandidateCallsites:0,ambiguousCallsites:0,unresolvedCallsites:0};if(!e.location||!e.behavior)return r;let i=e.behavior.lines.filter(x=>x.signals.includes("call"));if(i.length===0)return r;let o=e.location.file,s=[],a=0,c=0,l=0,u=(z(t.db,o)?.callSites??[]).filter(x=>i.some(E=>x.line>=E.line&&x.line<=E.endLine)),d=t.topology.edges.filter(x=>x.kind==="call"&&x.fromNodeId===e.nodeId&&x.disposition!=="excluded"&&x.disposition!=="unsupported"),m=o$(d,t.nodeById),p=S$(t.db,n.stepDefinition?n.calleeMap.get(n.stepDefinition.symbolId)??[]:[]),f=v$(p),g=(x,E,b)=>{let v=C$(u,i,x,E,b);if(!v)return null;let C=Ec(i,v.line,x);if(!C)return null;let R=Si(o,v.line,x);return n.evidencedCallsiteKeys.has(R)?null:(n.evidencedCallsiteKeys.add(R),{callsite:v,materialLine:C})},h=(x,E,b,v,C,R)=>{let{callsite:P,materialLine:w}=E;s.push({anchor:{id:Cr(e.id,P.line,b),status:v,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:e.id,fromLabel:e.label,callsite:{file:o,line:w.line,endLine:w.endLine,text:w.text,signals:w.signals,calleeLeaf:x},alternatives:[C],alternativeCount:1,evidence:R}})},y=()=>{for(let x of p){if(!t.sourceAllowed(x.alternative.file)||t.alternativeAlreadyReturned(x.alternative))continue;let E=Vo(x.alternative.label),b=g(E,x.row.callsiteLine,f.get(E)===1);if(!b)continue;let{callsite:v}=b,C=ye(x.row.source);h(E,b,x.alternative.symbol??x.alternative.file,C,x.alternative,[{method:x.row.source,strength:C,identity:x.row.symbol,location:{file:o,line:v.line}}])}},S=()=>{for(let x of d){if(t.returnedNodeIds.has(x.toNodeId))continue;let E=t.nodeById.get(x.toNodeId);if(!E?.location||!t.sourceAllowed(E.location.file))continue;let b=es(E),v=x.evidence.find(w=>{let T=w.location;return T!==null&&T.file===e.location?.file&&T.line>=0})?.location?.line,C=g(b,v,m.get(b)===1);if(!C)continue;let R=am(E);if(!R||t.alternativeAlreadyReturned(R))continue;let P=um(x.evidence);h(b,C,E.id,P,R,x.evidence)}},I=()=>{for(let x of u){let E=Si(o,x.line,x.calleeLeaf);if(n.evidencedCallsiteKeys.has(E))continue;let b=Ec(i,x.line,x.calleeLeaf);if(!b)continue;let v=Zr(o,ei(t.db).get(x.calleeLeaf)??[]).flatMap(w=>D(t.db,w.file).filter(T=>T.symbol===w.symbol&&T.isFunctionLike)).filter(w=>t.sourceAllowed(w.relativePath)&&!t.alternativeAlreadyReturned({symbol:w.symbol,label:w.leaf,file:w.relativePath,line:w.startLine,endLine:w.endLine})),C=wc(v.map(w=>({symbol:w.symbol,label:w.leaf??x.calleeLeaf,file:w.relativePath,line:w.startLine,endLine:w.endLine})));if(C.length===0){l+=1;continue}let R=`${e.id}\0${x.line}\0${x.calleeLeaf}`;if(n.consideredCandidateKeys.has(R))continue;n.consideredCandidateKeys.add(R);let P=C.length>1;P?c+=1:a+=1,s.push({anchor:{id:Cr(e.id,x.line,x.calleeLeaf),status:P?"ambiguous":"candidate",source:"leaf-identity-candidate",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:e.id,fromLabel:e.label,callsite:{file:o,line:b.line,endLine:b.endLine,text:b.text,signals:b.signals,calleeLeaf:x.calleeLeaf},alternatives:C.slice(0,3),alternativeCount:C.length,evidence:[]}})}};return y(),S(),I(),{candidates:s,scannedBehaviorSteps:1,visibleCallsites:u.length,identityCandidateCallsites:a,ambiguousCallsites:c,unresolvedCallsites:l}}function o$(e,t){let n=new Map;for(let r of e){let i=t.get(r.toNodeId);if(!i)continue;let o=es(i);n.set(o,(n.get(o)??0)+1)}return n}function Ov(e,t,n){let r=new Map(t.nodes.map(i=>[i.id,i]));for(let i of n.steps)!i.behavior||!i.location||s$(e,t,r,i,i.behavior,i.location)}function s$(e,t,n,r,i,o){for(let s of t.edges){if(!a$(s,r.nodeId))continue;let a=n.get(s.toNodeId);if(!a?.location||!cm(e,a))continue;let c=es(a),l=lm(s,o.file)?.line,u=i.lines.find(d=>(l===void 0||l>=d.line&&l<=d.endLine)&&d.text.includes(c));!u||Bv(u.signals)!=="result-callback"||s.semantics?.some(({family:d,subtype:m})=>d==="control"&&m==="result-callback")||(s.semantics=[...s.semantics??[],{family:"control",subtype:"result-callback",attributes:{evidenceRole:"result-producing-callable-reference"}}])}}function a$(e,t){return e.kind==="reference"&&e.fromNodeId===t&&e.disposition!=="excluded"&&e.disposition!=="unsupported"}function Bv(e){return e.includes("call")&&e.some(t=>["return","mutation","shape","spread","binding"].includes(t))?"result-callback":"callable-reference"}function $v(e,t,n={}){let r=n.limit??kv;if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`next-anchor limit must be a positive safe integer; received ${r}`);let i=n.sourceAllowed??(()=>!0),o=[],s=t.map((p,f)=>({id:p.id,nodeId:p.id,order:f,role:"anchor",kind:"source-construct",label:p.label,location:{file:p.file,line:p.startLine,endLine:p.endLine},behavior:null})),a=t.map(p=>({file:p.file,startLine:p.startLine,endLine:p.endLine})),c=0,l=0,u=0,d=0,m=0;for(let p of t){let f=c$(e,p,i,a,o);c+=f.visibleCallsites,l+=f.graphEvidencedCallsites,m+=f.unresolvedCallsites}return jv(e,o,s,r,{scannedBehaviorSteps:t.length,visibleCallsites:c,graphEvidencedCallsites:l,identityCandidateCallsites:u,ambiguousCallsites:d,unresolvedCallsites:m,upstreamCandidates:0,resultCandidates:0,runtimeCandidates:0})}function c$(e,t,n,r,i){let o=0,s=j(e,t.file),c=(z(e,t.file)?.callSites??[]).filter(y=>y.line>=t.startLine&&y.line<=t.endLine),l=c.length,u=ln(e,t.file,t.startLine,t.endLine),d=wn(e,t.file,t.startLine,t.endLine),m=new Set,p={seed:t,sourceLines:s,callsites:c,signalsByLine:u,sourceAllowed:n,materializedRanges:r};l$(p,d.targets,m,i);let f=d.resolvedCallsites,g=Qo(e,t.file,{ranges:[{startLine:t.startLine,endLine:t.endLine}]}),h=u$(t,c,g.targets);d$(p,h,m,i),f+=h.size;for(let y of c){let S=Si(t.file,y.line,y.calleeLeaf);m.has(S)||(o+=1)}return{visibleCallsites:l,graphEvidencedCallsites:f,unresolvedCallsites:o}}function l$(e,t,n,r){let{seed:i,sourceLines:o,signalsByLine:s,sourceAllowed:a,materializedRanges:c}=e;for(let l of t){if(!a(l.definition.relativePath)||c.some(p=>p.file===l.definition.relativePath&&p.startLine<=l.definition.startLine&&p.endLine>=l.definition.endLine))continue;let u=Si(i.file,l.sourceLine,l.calleeLeaf);n.add(u);let d=sm(s.get(l.sourceLine)),m={symbol:l.definition.symbol,label:l.definition.leaf,file:l.definition.relativePath,line:l.definition.startLine,endLine:l.definition.endLine};r.push({anchor:{id:Cr(i.id,l.sourceLine,l.definition.symbol),status:"exact",source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:i.id,fromLabel:i.label,callsite:{file:i.file,line:l.sourceLine,endLine:l.sourceLine,text:o[l.sourceLine]?.trim()||`${l.calleeLeaf}()`,signals:d,calleeLeaf:l.calleeLeaf},alternatives:[m],alternativeCount:1,evidence:[{method:"scip-occurrence-callsite",strength:l.implementationStatus==="unresolved"?"candidate":"exact",identity:l.definition.symbol,location:{file:i.file,line:l.sourceLine}}]}})}}function u$(e,t,n){let r=new Map;for(let i of n){let o=t.find(c=>c.line===i.line)?.calleeLeaf??i.calleeLeaf,s=Si(e.file,i.line,o),a=r.get(s)??[];a.push(i),r.set(s,a)}return r}function d$(e,t,n,r){let{sourceAllowed:i,materializedRanges:o}=e;for(let[s,a]of t){if(n.has(s))continue;n.add(s);let c=a.filter(l=>i(l.targetFile)&&!o.some(u=>u.file===l.targetFile&&u.startLine<=l.targetStartLine&&u.endLine>=l.targetEndLine));c.length!==0&&r.push(m$(e,c))}}function m$(e,t){let{seed:n,sourceLines:r,callsites:i,signalsByLine:o}=e,s=t[0],a=i.find(d=>d.line===s.line)?.calleeLeaf??s.calleeLeaf,c=sm(o.get(s.line)),l=wc(t.map(d=>({symbol:d.targetSymbol??null,label:d.calleeLeaf,file:d.targetFile,line:d.targetStartLine,endLine:d.targetEndLine}))),u=p$(t);return{anchor:{id:Cr(n.id,s.line,l.map(d=>`${d.file}:${d.line}`).join("|")),status:l.length>1?"ambiguous":u,source:"graph-call",direction:"downstream",causalRole:"callee",relationKind:"call",fromStepId:n.id,fromLabel:n.label,callsite:{file:n.file,line:s.line,endLine:s.line,text:r[s.line]?.trim()||`${s.calleeLeaf}()`,signals:c,calleeLeaf:a},alternatives:l.slice(0,3),alternativeCount:l.length,evidence:t.map(d=>f$(d,n.file,s.line,u))}}}function p$(e){return e.some(t=>(t.resolutionAlternativeCount??0)>1)?"candidate":e.every(t=>t.strength==="exact")?"exact":"derived"}function f$(e,t,n,r){return{method:g$(e.resolution),strength:r,identity:e.targetSymbol??`${e.targetFile}:${e.targetStartLine}-${e.targetEndLine}`,location:{file:t,line:n}}}function g$(e){switch(e){case"constructed-member-receiver":return"ast-constructed-member-callsite";case"factory-callback-member":return"ast-factory-callback-callsite";case"imported-service-object-member":return"ast-service-member-callsite";default:return"ast-import-member-callsite"}}function jv(e,t,n,r,i,o=[]){let s=x$(t).sort(Hv),a=s.filter(f=>b$(e,f)).slice(0,r),c=new Set(a.map(f=>f.anchor.id)),l=s.filter(f=>!c.has(f.anchor.id)),u=a.map(f=>f.anchor),d=l.map(f=>f.anchor),m=wc(u.flatMap(f=>f.alternativeCount===1?f.alternatives:[])),p=wc(d.flatMap(f=>f.alternativeCount===1?f.alternatives:[]));return{anchors:u,withheldAnchors:d,candidateAnchors:s.length,omittedAnchors:Math.max(0,s.length-u.length),...i,inspectCommand:m.length===0?null:`scip-query inspect ${m.map(Fv).join(" ")} --view behavior`,remainingInspectCommands:yo(p,8).map(f=>`scip-query inspect ${f.map(Fv).join(" ")} --view behavior`)}}function Hv(e,t){return h$(e,t)||y$(e,t)}function h$(e,t){return Ic(e.anchor.status)-Ic(t.anchor.status)||(e.anchor.direction??"").localeCompare(t.anchor.direction??"")||(e.anchor.relationKind??"").localeCompare(t.anchor.relationKind??"")||(e.anchor.causalRole??"").localeCompare(t.anchor.causalRole??"")}function y$(e,t){let n=e.anchor.alternatives[0],r=t.anchor.alternatives[0];return e.anchor.fromStepId.localeCompare(t.anchor.fromStepId)||e.anchor.callsite.file.localeCompare(t.anchor.callsite.file)||e.anchor.callsite.line-t.anchor.callsite.line||(n?.file??"").localeCompare(r?.file??"")||(n?.line??0)-(r?.line??0)||e.anchor.id.localeCompare(t.anchor.id)}function b$(e,t){if(t.anchor.alternativeCount!==1)return!0;let n=t.anchor.alternatives[0],r=n.endLine??n.line;return j(e,n.file).slice(n.line,r+1).join(`
|
|
32
|
+
`).length<=2e4}function sm(e){return e?.includes("call")?[...e]:["call",...e??[]]}function S$(e,t){let n=new Map;for(let r of t){let i=D(e,r.file).find(a=>a.symbol===r.symbol&&a.isFunctionLike);if(!i)continue;let o={symbol:i.symbol,label:i.leaf,file:i.relativePath,line:i.startLine,endLine:i.endLine},s=n.get(i.symbol);!s||Dv(r.source)>Dv(s.row.source)?n.set(i.symbol,{row:{...r,...r.callsiteLine===void 0&&s?.row.callsiteLine!==void 0?{callsiteLine:s.row.callsiteLine}:{}},alternative:o}):s.row.callsiteLine===void 0&&r.callsiteLine!==void 0&&n.set(i.symbol,{...s,row:{...s.row,callsiteLine:r.callsiteLine}})}return[...n.values()]}function v$(e){let t=new Map;for(let n of e){let r=Vo(n.alternative.label);t.set(r,(t.get(r)??0)+1)}return t}function Dv(e){return ye(e)==="exact"?2:1}function Ec(e,t,n){return e.find(r=>t>=r.line&&t<=r.endLine&&r.text.includes(n))??e.find(r=>t>=r.line&&t<=r.endLine)??null}function C$(e,t,n,r,i){if(r!==void 0)return e.find(s=>s.line===r&&s.calleeLeaf===n&&Ec(t,s.line,n)!==null)??null;let o=e.filter(s=>s.calleeLeaf===n&&Ec(t,s.line,s.calleeLeaf)!==null);return i&&o.length===1?o[0]:null}function es(e){let t=e.attributes.leaf;if(typeof t=="string"&&t.length>0)return Vo(t);let n=e.label.slice(e.label.lastIndexOf(":")+1);return Vo(n)}function om(e){if(e?.kind!=="symbol"||!e.id.startsWith("symbol:"))return null;try{return decodeURIComponent(e.id.slice(7))}catch{return null}}function am(e){return e.location?{symbol:om(e),label:e.label,file:e.location.file,line:e.location.line,endLine:e.location.endLine??null}:null}function cm(e,t){let n=am(t);return n?.symbol&&D(e,n.file).some(i=>i.symbol===n.symbol&&i.isFunctionLike)?n:null}function lm(e,t){return e.evidence.find(n=>n.location?.file===t)?.location??e.evidence.find(n=>n.location!==null)?.location??null}function um(e){let t={exact:5,derived:4,mixed:3,candidate:2,unknown:1};return e.reduce((n,r)=>t[r.strength]>t[n]?r.strength:n,"unknown")}function x$(e){let t=new Map;for(let n of e){let i=n.anchor.alternatives[0]?.symbol??`${n.anchor.callsite.file}:${n.anchor.callsite.line}:${n.anchor.callsite.calleeLeaf}`,o=t.get(i);(!o||R$(n,o)<0)&&t.set(i,n)}return[...t.values()]}function R$(e,t){return Ic(e.anchor.status)-Ic(t.anchor.status)||e.anchor.alternativeCount-t.anchor.alternativeCount||Hv(e,t)}function Ic(e){return{exact:0,derived:1,mixed:2,candidate:3,unknown:4,ambiguous:5}[e]}function wc(e){let t=new Map;for(let n of e)t.set(n.symbol??`${n.file}:${n.line}`,n);return[...t.values()].sort((n,r)=>n.file.localeCompare(r.file)||n.line-r.line||n.label.localeCompare(r.label))}function Fv(e){return`--at ${O(`${e.file}:${e.line+1}`)}`}function Si(e,t,n){return`${e}\0${t}\0${n}`}function Cr(e,t,n){return["next-anchor",e,String(t),n].map(encodeURIComponent).join(":")}function E$(e,t,n){for(let r of e.steps)for(let i of r.behavior?.supportingDeclarations??[])t.add(i.symbol),n.add(Nv(i.file,i.line,i.endLine))}var Vv=6,I$=12,w$=48,P$=2e4,Uv=12,xr=Number.MAX_SAFE_INTEGER,T$=["definition","callers","callees"],fm={search:12,"exact-source":24,definition:24,caller:8,callee:8,"production-reference":6,"test-reference":2,dependency:6,consumer:6};function L$(e,t){if(t.cursor)throw new Error("Inspect no longer accepts semantic packet cursors. Run the original inspect selectors again.");let n=k$(t),r=j$(e,n),i=r.candidates.sort((w,T)=>dm(w,T));n.view==="behavior"&&W$(e,i),V$(e,i),n.view==="behavior"&&G$(e,i);let o=nv(i.map(w=>mm(w,n.view)),n.evidenceBudgets,(w,T)=>dm(w.candidate,T.candidate)),{selected:s,omitted:a}=vc(o.selected,n.maxUnits,n.maxCharacters,(w,T)=>dm(w.candidate,T.candidate),n.view==="source"),c=s.map(w=>w.candidate),l=[...o.omitted,...a].map(w=>w.candidate),u=c.map(rj),d=Ta(c.map(w=>w.kind==="source"?w.bindingClosure:void 0),c.filter(w=>w.kind==="source").map(w=>({relativePath:w.relativePath,startLine:w.startLine,endLine:w.endLine}))),m=u.reduce((w,T)=>w+(T.kind==="source"?sj(T.source):0),0),p=u.reduce((w,T)=>w+(T.kind==="source"?T.source.length:0),0),f=u.reduce((w,T)=>w+Xv(T,n.view),0),g=u.filter(w=>w.kind==="source"&&(w.roles.includes("search")||w.roles.includes("location"))).map(ij),h=i.filter(w=>w.kind==="source"&&(w.roles.includes("search")||w.roles.includes("location"))).length,y=u.filter(w=>w.kind==="source"&&(w.roles.includes("search")||w.roles.includes("location"))).length,S=r.searches.map(w=>X$(w,i,c)),I=Q$(l),x=M$(r,l),E=S.reduce((w,T)=>w+T.omittedMatches,0),b=l.length===0&&E===0,v=b?void 0:Yv(n,!0),C=J$(n,l),R=F$(b,x,l.length+E,C,S,v),P=D$(e,i,n.view);return{searches:S,evidence:r.evidence,locations:r.locations,slices:g,candidateSlices:h,omittedSlices:h-y,maxSlices:h,maxTotalLines:m,units:u,candidateUnits:i.length,omittedUnits:l.length,maxUnits:n.maxUnits,maxCharacters:n.maxCharacters,returnedLines:m,returnedCharacters:p,returnedViewCharacters:f,view:n.view,omissionGroups:C,packetCoverage:{mode:b?"complete":"bounded",candidateUnits:i.length,returnedUnits:u.length,omittedUnits:l.length,omittedByRole:I,exactSelectorsComplete:x,maxUnits:n.maxUnits,maxCharacters:n.maxCharacters,channels:Z$(i,c,n.evidenceBudgets,n.view),...v?{expansionCommand:v}:{}},stoppingSummary:R,...P&&P.candidateAnchors>0?{causalFrontier:P}:{},bindingClosure:d,continuation:null}}function M$(e,t){return e.locations.every(n=>n.matched)&&e.evidence.every(n=>n.kind==="matched")&&e.searches.every(n=>ej(n.textCoverage))&&t.every(n=>!n.roles.some(r=>r==="location"||r==="definition"))}function D$(e,t,n){let r=t.filter(i=>n==="behavior"&&i.kind==="source"&&i.roles.some(o=>o==="location"||o==="definition"||o==="search")).map(i=>({id:`inspect:${i.relativePath}:${i.startLine}-${i.endLine}`,label:i.ownerShort??`${i.relativePath}:${i.startLine+1}`,file:i.relativePath,startLine:i.startLine,endLine:i.endLine}));return r.length>0?$v(e,r):void 0}function F$(e,t,n,r,i,o){let s=Qe([...r.map(a=>a.drillCommand),...i.flatMap(a=>a.exactFollowup?[a.exactFollowup]:[]),...o?[o]:[]]);return e&&t?{queryStatus:"selection-complete",status:"stop-ready",openEvidence:0,guidance:"All evidence requested by this inspect query was materialized.",drillCommands:[]}:t?{queryStatus:"frontier-accounted",status:"relevance-check-required",openEvidence:n,guidance:"Withheld evidence is accounted for by recoverable groups; drill the groups relevant to the current decision.",drillCommands:s}:{queryStatus:"coverage-incomplete",status:"exact-evidence-withheld",openEvidence:n,guidance:"A requested identity, exact source unit, or current-text coverage requirement is unresolved; drill before relying on it.",drillCommands:s}}function k$(e){let t=Ee(e.searches),n=Ee(e.symbols),r=Ee(e.locations),i=t.length+n.length+r.length;if(i===0)throw new Error("inspect requires at least one --search, --symbol, or --at selector.");if(i>24)throw new RangeError(`inspect accepts at most ${24} selectors; received ${i}.`);let o=e.evidence??{};N$(e),A$(e);let s=e.full??!1;return{searches:t,symbols:n,locations:r,...e.scope?.trim()?{scope:e.scope.trim()}:{},..._$(e,s),view:e.view??"source",evidence:O$(o,n.length>0)}}function N$(e){for(let t of["unitLines","totalLines","sliceLimit","maxCharacters","maxUnits"]){let n=e[t];n!==void 0&&Pc(n,t)}}function A$(e){if(e.view!==void 0&&e.view!=="source"&&e.view!=="behavior")throw new Error(`Unknown inspect view: ${String(e.view)}. Use source or behavior.`);if(e.full&&(e.searchLimit!==void 0||e.maxUnits!==void 0||e.maxCharacters!==void 0||e.evidenceBudgets!==void 0))throw new Error("full inspect cannot be combined with searchLimit, maxUnits, maxCharacters, or evidenceBudgets.")}function _$(e,t){return{context:Zv(e.context??Vv,"context"),searchLimit:Pc(e.searchLimit??(t?xr:I$),"searchLimit"),maxUnits:Pc(t?xr:e.maxUnits??w$,"maxUnits"),maxCharacters:Pc(t?xr:e.maxCharacters??P$,"maxCharacters"),evidenceBudgets:t?$$():B$(e.evidenceBudgets??fm)}}function O$(e,t){return{...e.parts?{parts:[...e.parts]}:t?{parts:[...T$]}:{},...e.referenceContext!==void 0?{referenceContext:Zv(e.referenceContext,"referenceContext")}:{},relatedSourceLines:e.relatedSourceLines??60,...e.semantic!==void 0?{semantic:e.semantic}:{}}}function B$(e){let t={...fm};for(let[n,r]of Object.entries(e)){if(!(n in t))throw new Error(`Unknown inspect evidence channel: ${n}.`);if(!Number.isSafeInteger(r)||(r??-1)<0)throw new RangeError(`Evidence budget ${n} must be a non-negative safe integer; received ${r}.`);t[n]=r}return t}function $$(){return Object.fromEntries(Object.keys(fm).map(e=>[e,xr]))}function j$(e,t){let n={candidates:[],sequence:0},r=H$(e,t,n),i=U$(e,t,n),o=z$(e,t,n);return{searches:r,evidence:o,locations:i,candidates:n.candidates}}function H$(e,t,n){let r=Cc(e,t.searches,{scope:t.scope,context:0,limit:t.searchLimit,ranking:"structural"}).map((s,a)=>({pattern:t.searches[a],result:s,matches:s.matches})),i=Math.max(0,...r.map(s=>s.matches.length));for(let s=0;s<i;s+=1)for(let a of r){let c=a.matches[s];if(!c)continue;let l=Ln(e,c.relativePath,c.focusLine,xr,t.context);l&&vi(e,n.candidates,l,"search",`search:${a.pattern}`,c.ownerSymbol,c.ownerShort,1,n.sequence++)}return r.map(({pattern:s,result:a})=>{let c=a.omittedMatches>0?Jv(s,t.scope):void 0,l=a.fileCoverage??[],u=tj(s,l,t.scope);return{pattern:s,matchingLines:a.matchingLines,returnedMatches:a.matches.length,omittedMatches:a.omittedMatches,matchingFiles:l.length,returnedFiles:l.filter(d=>d.returnedMatches>0).length,omittedFiles:l.filter(d=>d.returnedMatches===0).length,candidateUnits:0,selectedUnits:0,omittedUnits:0,scopeHints:u.slice(0,Uv),omittedScopeHints:Math.max(0,u.length-Uv),textCoverage:a.textCoverage,...c?{exactFollowup:c}:{}}})}function U$(e,t,n){return t.locations.map(i=>{let o=oj(i),s=o?uh(e,o.path):null,a=s?Ln(e,s,o.line-1,xr,t.context):null;return a&&vi(e,n.candidates,a,"location",`at:${i}`,null,null,0,n.sequence++),{target:i,matched:a!==null}})}function q$(e,t,n,r){if(r.definition){let i=Ln(e,r.definition.relativePath,r.definition.startLine,xr,t.context);i&&vi(e,n.candidates,i,"definition",`definition:${r.shortName}`,r.symbol,r.shortName,0,n.sequence++)}for(let i of r.referenceWindows){let o=i.references[0];vi(e,n.candidates,{...i,focusLine:o?.line??i.startLine,unitType:null,unitStartLine:i.startLine,unitEndLine:i.endLine,omittedLines:0},"reference",`reference:${r.shortName}`,o?.enclosingSymbol??null,o?.enclosingShort??null,F(i.relativePath)==="test"?5:4,n.sequence++,i.references.map(s=>s.line),r.symbol)}}function z$(e,t,n){let r=t.symbols.map(i=>hv(e,i,t.evidence));for(let i of r)if(i.kind==="matched"){q$(e,t,n,i);for(let o of i.callers)qv(e,n.candidates,o,"caller",i,2,n.sequence++);for(let o of i.callees)qv(e,n.candidates,o,"callee",i,3,n.sequence++);for(let o of i.dependencies)zv(e,n.candidates,"dependency",i.file,o.relativePath,i.symbol,t.context,6,n.sequence++);for(let o of i.consumers)zv(e,n.candidates,"consumer",o.relativePath,i.file,i.symbol,t.context,7,n.sequence++)}return r}function dm(e,t){return e.priority-t.priority||t.roles.length-e.roles.length||t.reasons.length-e.reasons.length||sn(F(e.relativePath))-sn(F(t.relativePath))||e.sequence-t.sequence}function mm(e,t){return{candidate:e,priority:e.priority,sequence:e.sequence,relativePath:e.relativePath,fileKind:F(e.relativePath),evidenceCharacters:Xv(e,t),roles:e.roles,reasons:e.reasons,symbols:e.symbols,behaviorSignals:e.kind==="source"?e.behavior?.signals??[]:[],channel:pm(e)}}function pm(e){let t=e.roles;return t.includes("location")?"exact-source":t.includes("definition")?"definition":t.includes("caller")?"caller":t.includes("callee")?"callee":t.includes("reference")?F(e.relativePath)==="test"?"test-reference":"production-reference":t.includes("dependency")?"dependency":t.includes("consumer")?"consumer":"search"}function G$(e,t){let n=t.filter(i=>i.kind==="source"),r=ho(e,{files:Qe(n.map(i=>i.relativePath))});for(let i of n){i.behavior=oi(e,i.relativePath,i.startLine,i.endLine,i.focusLines)??void 0;let o=r.filter(a=>a.source.file===i.relativePath&&a.source.startLine<=i.endLine&&a.source.endLine>=i.startLine),s=o.filter(a=>!K$(a,o)).map(a=>({observationId:a.id,protocol:a.protocol,action:a.action,role:a.role,strength:a.strength,resolution:a.resolution,line:a.source.startLine,endLine:a.source.endLine,keyParts:a.keyParts.map(c=>({name:c.name,value:c.value,evidence:c.evidence})),derivation:{kind:a.derivation.kind,rule:a.derivation.rule,sourceSpans:a.derivation.sourceSpans.length}}));i.runtimeFacts=s.length>0?s:void 0}}function K$(e,t){if(e.strength!=="candidate"||e.protocol!=="http")return!1;let n=e.keyParts.find(i=>i.name==="path")?.value,r=e.keyParts.find(i=>i.name==="method")?.value;return n?t.some(i=>{if(i===e||i.action!==e.action||i.role!==e.role||i.source.startLine!==e.source.startLine||i.derivation.rule!=="http.mount-prefix")return!1;let o=i.keyParts.find(a=>a.name==="path")?.value,s=i.keyParts.find(a=>a.name==="method")?.value;return!!(o&&o!==n&&o.endsWith(n)&&(!r||r===s))}):!1}function W$(e,t){for(let n of t){if(n.kind!=="source")continue;let r=Lt(e,n.relativePath,n.startLine,n.endLine,n.focusLines);r.startLine===n.startLine&&r.endLine===n.endLine||(n.startLine=r.startLine,n.endLine=r.endLine,n.source=j(e,n.relativePath).slice(r.startLine,r.endLine+1).join(`
|
|
33
|
+
`),n.unitStartLine=r.startLine,n.unitEndLine=r.endLine,n.omittedLines=0)}}function V$(e,t){for(let n of t)n.kind==="source"&&(n.bindingClosure=ii(e,n.relativePath,n.startLine,n.endLine))}function J$(e,t){let n=new Map;for(let r of t){let i=Tc(r.relativePath),o=pm(r),s=[...r.roles].sort().join(","),a=r.kind==="path"?r.relationship:"",c=`${i}|${o}|${s}|${a}`,l=n.get(c)??[];l.push(r),n.set(c,l)}return[...n.entries()].map(([r,i])=>{let o=i[0],s=Qe(i.flatMap(c=>[...c.roles])).sort(),a=Qe(i.flatMap(c=>c.kind==="source"?c.behavior?.signals??[]:[])).sort();return{id:`g-${Wv("sha256").update(r).digest("hex").slice(0,8)}`,scope:Tc(o.relativePath),channel:pm(o),roles:s,behaviorSignals:a,candidateUnits:i.length,sourceCharacters:i.reduce((c,l)=>c+(l.kind==="source"?l.source.length:0),0),anchors:i.map(c=>({relativePath:c.relativePath,line:c.kind==="source"?c.focusLine:0,ownerShort:c.kind==="source"?c.ownerShort:null,roles:[...c.roles],behaviorSignals:c.kind==="source"?[...c.behavior?.signals??[]]:[]})),drillCommand:Y$(e,i)}}).sort((r,i)=>i.candidateUnits-r.candidateUnits||i.sourceCharacters-r.sourceCharacters||r.scope.localeCompare(i.scope)||r.id.localeCompare(i.id))}function Y$(e,t){let n=Qe(t.flatMap(o=>o.reasons.filter(s=>s.startsWith("search:")).map(s=>s.slice(7)))),r=Tc(t[0].relativePath);if(n.length>0&&t.every(o=>o.kind==="source"&&o.roles.includes("search")))return aj(e,n,r);let i=t.filter(o=>o.kind==="source");if(i.length>0&&i.length<=24){let o=["scip-query inspect"];for(let s of i)o.push(`--at ${O(`${s.relativePath}:${s.focusLine+1}`)}`);return e.view==="behavior"&&o.push("--view behavior"),o.join(" ")}return t.length===1&&t[0].kind==="path"?t[0].exactFollowup:Yv(e,!0)}function X$(e,t,n){let r=`search:${e.pattern}`,i=t.filter(a=>a.reasons.includes(r)).length,o=new Set(n),s=t.filter(a=>a.reasons.includes(r)&&o.has(a)).length;return{...e,candidateUnits:i,selectedUnits:s,omittedUnits:i-s}}function Q$(e){let t={};for(let n of e)for(let r of n.roles)t[r]=(t[r]??0)+1;return t}function Z$(e,t,n,r){let i=e.map(s=>mm(s,r).channel),o=t.map(s=>mm(s,r).channel);return Object.fromEntries(Object.keys(n).map(s=>{let a=i.filter(l=>l===s).length,c=o.filter(l=>l===s).length;return[s,{candidateUnits:a,returnedUnits:c,omittedUnits:a-c,maxUnits:n[s]}]}))}function ej(e){return!!(e&&e.skippedUnreadablePaths.length===0&&e.skippedOversizedPaths.length===0)}function tj(e,t,n){let r=new Map;for(let i of t){let o=Tc(i.relativePath),s=r.get(o)??{matchingLines:0,returnedMatches:0};s.matchingLines+=i.matchingLines,s.returnedMatches+=i.returnedMatches,r.set(o,s)}return[...r.entries()].map(([i,o])=>({scope:i,...o,exactFollowup:Jv(e,i||n)})).sort((i,o)=>o.matchingLines-i.matchingLines||o.returnedMatches-i.returnedMatches||i.scope.localeCompare(o.scope))}function Tc(e){let t=e.lastIndexOf("/");return t<0?e:e.slice(0,t)}function Jv(e,t){return`scip-query inspect --search ${O(e)}${t?` --scope ${O(t)}`:""} --full`}function Yv(e,t){let n=["scip-query inspect"];for(let r of e.searches)n.push(`--search ${O(r)}`);for(let r of e.symbols)n.push(`--symbol ${O(r)}`);for(let r of e.locations)n.push(`--at ${O(r)}`);return e.scope&&n.push(`--scope ${O(e.scope)}`),e.context!==Vv&&n.push(`--context ${e.context}`),e.evidence.parts&&n.push(`--include ${O(e.evidence.parts.join(","))}`),t&&n.push("--full"),e.view==="behavior"&&n.push("--view behavior"),n.join(" ")}function qv(e,t,n,r,i,o,s){vi(e,t,{...n,unitType:null,unitStartLine:n.startLine,unitEndLine:n.endLine+n.omittedLines},r,`${n.evidenceStrength==="exact"?r:`candidate-${r}`}:${i.shortName}`,n.symbol,n.shortName,o,s,[n.focusLine],i.symbol)}function zv(e,t,n,r,i,o,s,a,c){let l=`${r} -> ${i}`,u=V(e,r).filter(h=>h.sourcePath===i),d=j(e,r),m=nj(d,u,i),p=m===null?null:Ba(e,r,m,Math.min(s,4));if(p){vi(e,t,{...p,unitType:null,unitStartLine:p.startLine,unitEndLine:p.endLine,omittedLines:0},n,`${n}:${l}`,null,null,a,c,[p.focusLine],o);return}let f=`scip-query inspect --search ${O(Qv(i))} --scope ${O(r)}`,g=t.find(h=>h.kind==="path"&&h.relativePath===r&&h.relationship===l);if(g){g.roles=Qe([...g.roles,n]),g.reasons=Qe([...g.reasons,`${n}:${l}`]),g.symbols=Qe([...g.symbols,o]),g.priority=Math.min(g.priority,a);return}t.push({kind:"path",roles:[n],relativePath:r,relationship:l,reasons:[`${n}:${l}`],symbols:[o],exactFollowup:f,priority:a,sequence:c})}function nj(e,t,n){let r=Qe(t.flatMap(c=>[c.importedName,c.localName??""]).filter(c=>c.length>1)),i=Qv(n).replace(/\.[^.]+$/u,""),o=Qe([...r,i]).filter(Boolean),s=/\b(?:from|import|include|require|use)\b/u,a=e.findIndex(c=>s.test(c)&&o.some(l=>c.includes(l)));return a>=0?a:null}function vi(e,t,n,r,i,o,s,a,c,l=[n.focusLine],u){let d=t.find(m=>m.kind==="source"&&m.relativePath===n.relativePath&&m.startLine<=n.endLine&&n.startLine<=m.endLine);if(d){let m=Math.min(d.startLine,n.startLine),p=Math.max(d.endLine,n.endLine);d.startLine=m,d.endLine=p,d.source=j(e,n.relativePath).slice(m,p+1).join(`
|
|
34
|
+
`),d.focusLine=Math.min(d.focusLine,n.focusLine),d.focusLines=Kv([...d.focusLines,...l]),d.unitStartLine=Math.min(d.unitStartLine,n.unitStartLine),d.unitEndLine=Math.max(d.unitEndLine,n.unitEndLine),d.omittedLines=Math.max(d.omittedLines,n.omittedLines),d.reasons=Qe([...d.reasons,i]),d.roles=Qe([...d.roles,r]),d.symbols=Qe([...d.symbols,...u?[u]:[]]),!d.ownerSymbol&&o&&(d.ownerSymbol=o),!d.ownerShort&&s&&(d.ownerShort=s),d.priority=Math.min(d.priority,a);return}t.push({kind:"source",...n,reasons:[i],focusLines:Kv(l),ownerSymbol:o,ownerShort:s,roles:[r],symbols:u?[u]:[],priority:a,sequence:c})}function rj(e){if(e.kind==="path"){let{priority:o,sequence:s,...a}=e;return{...a,id:Gv(a)}}let{priority:t,sequence:n,bindingClosure:r,...i}=e;return{...i,id:Gv(i),omittedCharacters:0}}function ij(e){let{kind:t,id:n,roles:r,symbols:i,omittedCharacters:o,behavior:s,runtimeFacts:a,...c}=e;return c}function Gv(e){return Wv("sha256").update(JSON.stringify(e)).digest("hex").slice(0,16)}function oj(e){let t=e.match(/^(.+\.\w+):(\d+)$/u);if(!t)return null;let n=Number(t[2]);return Number.isSafeInteger(n)&&n>0?{path:t[1],line:n}:null}function Qe(e){return[...new Set(e)]}function Kv(e){return Qe(e).sort((t,n)=>t-n)}function sj(e){return e.length===0?0:e.split(`
|
|
35
|
+
`).length}function Xv(e,t){if(e.kind==="path")return e.relationship.length+e.exactFollowup.length;let n="bindingClosure"in e?ph(e.bindingClosure):0,r=(e.runtimeFacts??[]).reduce((i,o)=>i+o.action.length+o.derivation.rule.length+o.keyParts.reduce((s,a)=>s+a.name.length+a.value.length+4,0)+24,0);return t!=="behavior"?e.source.length+n:e.behavior?e.behavior.lines.reduce((i,o)=>i+o.text.length+o.signals.join(",").length+12,0)+e.behavior.testCases.reduce((i,o)=>i+o.length+2,0)+r+n:e.source.length+n+r}function Qv(e){return e.split("/").at(-1)??e}function Pc(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new RangeError(`${t} must be a positive safe integer; received ${e}`);return e}function Zv(e,t){if(!Number.isSafeInteger(e)||e<0)throw new RangeError(`${t} must be a non-negative safe integer; received ${e}`);return e}function aj(e,t,n){let r=["scip-query inspect"];for(let i of t)r.push(`--search ${O(i)}`);return r.push(`--scope ${O(n)}`,"--full"),e.view==="behavior"&&r.push("--view behavior"),r.join(" ")}import{basename as cj}from"path";function lj(e,t){let n=t.className,r=J(e,n);return r.match?r.total>1?{kind:"ambiguous",query:n,total:r.total,candidates:[eC(r.match),...r.candidates]}:{kind:"matched",query:n,owner:dj(r.match),methods:uj(e,r.match)}:{kind:"missing",query:n,suggestions:ua(e,n,5)}}function uj(e,t){let n=A(t.symbol),i=new N(e).definitionsForFile(t.relativePath).filter(c=>Xe(c.symbol)),o=i.filter(c=>c.enclosingSymbol===t.symbol||na(t.symbol,c.symbol)),a=(o.length>0?o:mj(cj(t.relativePath))===n?i.filter(c=>c.symbol.includes("<invalid-global-code>")):[]).map(c=>({startLine:c.startLine,endLine:c.endLine,name:A(c.symbol)}));return se(t.relativePath)!=="clojure"?a:fj(a,pj(e,t))}function eC(e){return{symbol:e.symbol,shortName:L(e.symbol),relativePath:e.relativePath,startLine:e.startLine}}function dj(e){return{...eC(e),endLine:e.endLine}}function mj(e){return e.replace(/\.[^.]+$/,"")}function pj(e,t){let n=A(t.symbol);return n?(z(e,t.relativePath)?.clojureMembers??[]).filter(r=>r.ownerName===n).map(r=>({startLine:r.startLine,endLine:r.endLine,name:r.memberName})):[]}function fj(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.name}:${r.startLine}:${r.endLine}`,r);return[...n.values()].sort((r,i)=>r.startLine-i.startLine||r.endLine-i.endLine)}import{createHash as YG}from"crypto";var Dge={exact:"Direct compiler or source evidence establishes this relationship within the provider's reported coverage.",derived:"A deterministic analysis computed this relationship from reported input facts; it was not directly observed.",candidate:"Ambiguous or heuristic evidence identifies a lead that requires exact graph or source confirmation.",mixed:"The relationship combines evidence of different strengths; its constituent methods and strengths remain disclosed.",unknown:"The relationship has no calibrated evidence strength and cannot support a stronger claim than its raw observation."},gj=[{id:"general-interprocedural-value-flow",families:["dataflow"],capability:"Whole-program definition-use flow through arbitrary calls and returns is unavailable.",consequence:"Missing dataflow edges cannot establish that a value never crosses an unmodeled call.",recoverWith:["value-flow","dependence-slice","inspect","code"]},{id:"heap-aliasing",families:["dataflow","state"],capability:"Heap points-to and cross-instance alias analysis are unavailable.",consequence:"Missing field or state edges cannot establish that two references never reach the same object.",recoverWith:["value-flow","dependence-slice","inspect","code"]},{id:"exceptional-flow",families:["execution","dataflow","temporal"],capability:"Interprocedural exception propagation and finally completion flow are unavailable.",consequence:"Normal-path reachability and ordering do not establish behavior after a throw or rejection.",recoverWith:["dependence-slice","inspect","code"]},{id:"dynamic-callable-dispatch",families:["execution","dataflow"],capability:"General virtual dispatch and interprocedural replacement of callable values are unavailable.",consequence:"A static declaration target does not establish a unique runtime implementation or all possible overrides.",recoverWith:["hierarchy","inspect","code"]},{id:"reflection",families:["execution","runtime","identity","dependencies"],capability:"Reflective lookup, dynamic loading, and name-computed invocation are unavailable without exact evidence.",consequence:"Missing static edges cannot establish that a construct is unreachable through reflection.",recoverWith:["search","inspect","code"]},{id:"generated-dispatch",families:["execution","runtime","identity"],capability:"Dispatch tables or names created only by generated or unavailable source are unavailable.",consequence:"Missing dispatch edges cannot establish that no generated consumer exists.",recoverWith:["search","inspect","code"]},{id:"unsupported-framework-adapters",families:["runtime","dataflow","state","temporal"],capability:"Framework runtime crossings without a registered source adapter are unavailable.",consequence:"Missing boundary edges cannot establish that no producer, consumer, state effect, or ordering exists.",recoverWith:["search","inspect","code"]}];function hj(e){let t=new Set(e);return gj.filter(n=>n.families.some(r=>t.has(r)))}function tC(e){return hj(e).map(t=>`[${t.id}] ${t.capability} ${t.consequence} Recover selected paths with: ${t.recoverWith.map(n=>`scip-query ${n}`).join(", ")}.`)}var yj=["incoming","outgoing","both"];function de(e,t,n,r={}){return{family:e,subtype:t,...r.match?{match:r.match}:{},directions:yj,evidenceStrengths:r.strengths??["exact","derived","mixed"],supportCeiling:r.supportCeiling??"partial",establishes:n,nonClaims:r.nonClaims??[],recoverWith:r.recoverWith??["inspect","code"]}}var bj=["predicate-consequence","predicate-alternative","predicate-fallthrough","predicate-case","predicate-default","predicate-return","predicate-throw","loop-iteration","loop-exit","exception-handler","finally-cleanup","handler-return","handler-throw"],Sj=["captured-value-to-state","constant-to-state","expression-to-state","property-to-state","return-to-state","value-to-state"],vj=["await-completion-before","awaits-completion","inside-lock-scope","lexical-successor"],Cj=[{id:"indexed-program-identity",label:"SCIP/compiler identity and source ownership",requirements:["indexed-graph"],relations:[de("execution","call","The source construct may call the resolved target.",{strengths:["exact","derived","candidate","mixed"],nonClaims:["Static may-call reachability does not prove that an invocation occurred at runtime.","Compiler declaration identity does not resolve virtual dispatch, cross-file callable replacement, or runtime receiver identity.","Candidate call edges preserve declaration leads; consult the invocation frontier for implementation resolution. A declaration reference is not an established implementation target."],recoverWith:["call-graph","inspect","code"]}),de("execution","result-callback","The referenced callable can produce the result consumed by this path.",{nonClaims:["A callback relationship does not prove invocation order or runtime selection."],recoverWith:["call-graph","inspect","code"]}),de("contract","uses-contract-symbol","The source construct refers to the identified contract symbol.",{supportCeiling:"exact",nonClaims:["Contract identity does not prove runtime invocation or behavioral conformance."],recoverWith:["hierarchy","inspect","code"]}),de("identity","references","The occurrence resolves to the identified compiler-owned symbol.",{supportCeiling:"exact",nonClaims:["A reference does not establish execution or value transfer."],recoverWith:["refs","inspect"]}),de("ownership","contains","The owner contains the identified program construct.",{supportCeiling:"exact",nonClaims:["Structural containment does not establish runtime lifetime or sharing scope."],recoverWith:["outline","inspect"]}),de("ownership","contains-","The owner contains the identified program construct.",{match:"prefix",supportCeiling:"exact",nonClaims:["Structural containment does not establish runtime lifetime or sharing scope."],recoverWith:["outline","inspect"]}),de("ownership","owns-","The owner owns the identified source or runtime observation.",{match:"prefix",supportCeiling:"exact",nonClaims:["Observation ownership does not establish singleton lifetime or exclusive ownership."],recoverWith:["inspect","code"]}),de("dependencies","imports","The source file or module statically imports the indexed target.",{nonClaims:["An import does not establish that imported code executes."],recoverWith:["imports","deps","code"]}),de("dependencies","imports-external","The source region statically imports an external package.",{nonClaims:["An external import does not establish which package behavior executes."],recoverWith:["imports","code"]})]},{id:"runtime-boundary-join",label:"source-grounded runtime-boundary joins",requirements:["indexed-graph","source-facts"],relations:[de("runtime","runtime-handoff","A producer and consumer share a source-grounded runtime rendezvous.",{strengths:["exact","derived","candidate","mixed"],nonClaims:["A candidate or unresolved join does not prove a runtime handoff."],recoverWith:["evidence","inspect","code"]}),de("runtime","discriminator-dispatch","A serialized discriminator selects the reported consumer.",{strengths:["exact","derived","mixed"],nonClaims:["The dispatch edge does not prove delivery, retry, or successful handling."],recoverWith:["evidence","inspect","code"]}),de("dataflow","serialized-discriminator-transfer","The producer serializes the discriminator consumed by dispatch.",{strengths:["exact","derived","mixed"],nonClaims:["This edge does not establish the flow of every payload field."],recoverWith:["value-flow","inspect","code"]}),de("temporal","enqueue-before-consume","The reported enqueue precedes a possible consume through the queue.",{strengths:["exact","derived","mixed"],nonClaims:["Queue order does not establish delivery time, uniqueness, retry count, or durability."],recoverWith:["evidence","inspect","code"]})]},{id:"parser-control-dependence",label:"parser-proved intraprocedural control dependence",requirements:["indexed-graph","source-facts"],relations:[...bj.map(e=>de("execution",e,"The outcome is control-dependent on the reported predicate or handler.",{strengths:["exact"],nonClaims:["Local control dependence does not establish that the containing function executes."],recoverWith:["dependence-slice","inspect","code"]})),de("execution","returns","The selected construct contains the reported return terminal.",{strengths:["exact"],nonClaims:["A local return terminal does not establish that the containing callable executes."],recoverWith:["inspect","code"]}),de("execution","throws","The selected construct contains the reported throw terminal.",{strengths:["exact"],nonClaims:["A local throw terminal does not establish propagation, handling, or callable execution."],recoverWith:["inspect","code"]})]},{id:"bounded-static-value-flow",label:"compiler callsites and bounded static value evaluation",requirements:["indexed-graph","source-facts"],relations:["argument-to-parameter","constant-to-parameter","property-to-parameter","return-to-parameter","return-to-call-result"].map(e=>de("dataflow",e,"The reported value may reach the target through the evidenced callsite transfer.",{strengths:["exact","derived","mixed"],nonClaims:["This provider does not establish general local definition-use, alias, field, or heap flow."],recoverWith:["value-flow","dependence-slice","inspect","code"]}))},{id:"typescript-local-dependence",label:"TypeScript compiler identities, control-flow graph, and reaching definitions",requirements:["typescript-semantic"],relations:[de("dataflow","definition-to-use","The definition reaches the reported read on a feasible local control-flow path.",{strengths:["exact"],nonClaims:["Local reaching definitions do not establish heap aliasing, exceptional flow, or the runtime order of closure invocation."],recoverWith:["value-flow","dependence-slice","inspect","code"]}),de("dataflow","value-to-definition","The reported right-hand-side read supplies the assigned local definition.",{strengths:["exact"],nonClaims:["A local assignment edge does not establish field or heap points-to flow."],recoverWith:["value-flow","dependence-slice","inspect","code"]}),de("dataflow","closure-capture","The nested callable reads the reported binding from an enclosing callable.",{strengths:["candidate"],supportCeiling:"candidate",nonClaims:["Closure capture does not establish whether or when the nested callable executes."],recoverWith:["call-graph","inspect","code"]}),de("dataflow","field-definition-to-use","The reported same-owner field definition can reach the field read.",{strengths:["exact","candidate"],nonClaims:["Field-name identity does not establish whole-program heap aliasing or cross-instance flow."],recoverWith:["value-flow","dependence-slice","inspect","code"]}),de("execution","control-dependence","Execution of the reported statement depends on the outcome of the predicate.",{strengths:["exact"],nonClaims:["Intraprocedural control dependence does not establish that the containing callable executes."],recoverWith:["dependence-slice","inspect","code"]})]},{id:"parser-state-temporal",label:"parser-proved local state and temporal facts",requirements:["indexed-graph","source-facts"],relations:[...Sj.map(e=>de("dataflow",e,"The reported source value is assigned into the identified state resource.",{strengths:["exact"],nonClaims:["The edge does not establish alias, heap, or later read flow."],recoverWith:["value-flow","inspect","code"]})),...["writes-resource","deletes-resource","reads-resource","enqueues-resource","consumes-resource"].map(e=>de("state",e,"The reported construct performs the named operation on the identified resource.",{strengths:["exact"],nonClaims:["A state operation does not establish transactionality, durability, or exclusive ownership."],recoverWith:["evidence","inspect","code"]})),...vj.map(e=>de("temporal",e,"The reported source constructs have the named local ordering relationship.",{strengths:["exact"],nonClaims:["Local source order does not establish cross-process happens-before or durable completion."],recoverWith:["evidence","inspect","code"]}))]}];function Lc(e,t){let n=Cj.flatMap(r=>r.relations.filter(i=>i.family===e&&(i.match==="prefix"?t.startsWith(i.subtype):t===i.subtype)).map(i=>({provider:r,relation:i})));if(n.length>1)throw new Error(`Ambiguous graph relation provider for ${e}/${t}: ${n.map(r=>r.provider.id).join(", ")}`);return n[0]??null}var Mt=["execution","runtime","dataflow","state","temporal","contract","identity","ownership","dependencies"];function Te(e,t){let n=new Map;for(let r of e){let i=t(r),o=n.get(i)??[];o.push(r),n.set(i,o)}return n}function Ci(e){return e.includes("symbol-anchor")?0:e.includes("literal-owner")?1:e.some(t=>t.startsWith("boundary-import:"))?2:e.includes("reference-owner")?3:4}function nC(e,t){return Ci(e.origins)-Ci(t.origins)||e.depth-t.depth||e.startLine-t.startLine||e.shortName.localeCompare(t.shortName)}import{ts as le}from"@ts-morph/common";var xj=new Set([le.SyntaxKind.ImportSpecifier,le.SyntaxKind.ImportClause,le.SyntaxKind.NamespaceImport]);function rC(e,t){let{sourceFile:n,checker:r}=e,i=Ej(n),{importedBindings:o,consumers:s}=Rj(n,r,t),a=Pj(n,r);return{functions:i.flatMap(l=>{let u=e.functions.find(y=>y.startOffset===l.getStart(n));if(!u)return[];let d=new Set,m=new Set,p=y=>{if(le.isIdentifier(y)){let S=r.getSymbolAtLocation(y),I=S&&o.get(S);I&&m.add(I);for(let x of S?.declarations??[])x.getSourceFile()!==n||x.pos>=l.pos&&x.end<=l.end||xj.has(x.kind)||d.add(x.getStart(n))}le.forEachChild(y,p)};p(l);let f=Ij(l),g=f&&r.getSymbolAtLocation(f),h=(le.isVariableDeclaration(l.parent)?l.parent:l).getStart(n);return[{fn:u,declaration:h,exports:g?a.get(g)??[]:[],bindings:[...d].sort((y,S)=>y-S),dependencies:[...m].sort()}]}),consumers:s}}function Rj(e,t,n){let r=new Map,i=[];for(let o of e.statements.filter(le.isImportDeclaration)){if(!le.isStringLiteralLike(o.moduleSpecifier))continue;let s=o.moduleSpecifier.text,a=e.getLineAndCharacterOfPosition(o.moduleSpecifier.getStart(e)).line+1,c=n.find(l=>l.specifier===s&&l.line===a&&l.syntax==="import"&&l.kind==="value");if(!(!c||c.role==="test"))for(let l of wj(o)){let u=t.getSymbolAtLocation(l.local);u&&r.set(u,c.target??`specifier:${c.specifier}`),c.target&&c.resolution==="internal"&&i.push({file:e.fileName,line:c.line,target:c.target,name:l.imported})}}return{importedBindings:r,consumers:i}}function Ej(e){return e.statements.flatMap(t=>le.isFunctionDeclaration(t)&&t.body?[t]:le.isVariableStatement(t)?t.declarationList.declarations.flatMap(n=>n.initializer&&(le.isArrowFunction(n.initializer)||le.isFunctionExpression(n.initializer))?[n.initializer]:[]):[])}function Ij(e){return le.isVariableDeclaration(e.parent)?e.parent.name:e.name}function wj(e){let t=e.importClause;if(!t||t.isTypeOnly)return[];let n=t.name?[{local:t.name,imported:"default"}]:[],r=t.namedBindings;if(!r)return n;if(le.isNamespaceImport(r))return n.push({local:r.name,imported:"*"}),n;for(let i of r.elements)i.isTypeOnly||n.push({local:i.name,imported:(i.propertyName??i.name).text});return n}function Pj(e,t){let n=t.getSymbolAtLocation(e),r=new Map;if(!n)return r;for(let i of t.getExportsOfModule(n)){let o=i.flags&le.SymbolFlags.Alias?t.getAliasedSymbol(i):i;r.set(o,[...r.get(o)??[],i.name])}return r}function iC(e){if(e.errors.length>0)return[];let{sourceFile:t,checker:n}=e,r=new Map,i=new Set,o=a=>{if(le.isIdentifier(a)){let c=n.getSymbolAtLocation(a),l=c?.valueDeclaration;if(c&&l&&(le.isVariableDeclaration(l)||le.isBindingElement(l))&&l.name===a){let u=oC(l);u&&(i.add(a),r.set(c,{name:a.text,startLine:t.getLineAndCharacterOfPosition(u.parent.getStart(t)).line,endLine:t.getLineAndCharacterOfPosition(u.end-1).line,referenceLines:[]}))}}le.forEachChild(a,o)};o(t);let s=a=>{if(le.isIdentifier(a)&&!i.has(a)){let c=le.isShorthandPropertyAssignment(a.parent)?n.getShorthandAssignmentValueSymbol(a.parent):n.getSymbolAtLocation(a),l=c&&r.get(c);l&&l.referenceLines.push(t.getLineAndCharacterOfPosition(a.getStart(t)).line)}le.forEachChild(a,s)};return s(t),[...r.values()].map(a=>({...a,referenceLines:[...new Set(a.referenceLines)].sort((c,l)=>c-l)}))}function oC(e){return le.isVariableDeclaration(e)?e:le.isBindingElement(e)||le.isObjectBindingPattern(e)||le.isArrayBindingPattern(e)?oC(e.parent):null}var Tj=16,Lj=4,Mj=3e3,Dj=800,Fj=new Set(["assignment","const_declaration","const_item","field_declaration","lexical_declaration","local_declaration_statement","local_variable_declaration","static_item","variable_declaration"]);function pC(e,t,n={}){let r=n.maxSteps??Tj;if(!Number.isSafeInteger(r)||r<=0)throw new RangeError(`maxSteps must be a positive safe integer; received ${r}`);let i=a1(n.focusLocations??[]),o=kj(t,i,r),{candidateNodeIds:s,selectedNodeIds:a,selectedNodeIdSet:c}=o,l=new Map(a.map(h=>[h,v1(h)])),{steps:u,matchedFocusLocations:d}=_j(e,t,o,i,l),m=Oj(t,o,l),p=new Map(m.map(h=>[h.edgeId,h.id])),f=Bj(t,l,p),g=u.flatMap(h=>h.location?[`${h.location.file}:${h.location.line+1}`]:[]);return{status:$j(t,u,f),steps:u,transitions:m,paths:f,coverage:{candidateNodes:s.length,returnedNodes:a.length,omittedNodeIds:s.filter(h=>!c.has(h)),returnedTransitions:m.length,withheldStatements:u.reduce((h,y)=>h+(y.behavior?.coverage.omittedStatements??0),0),requestedFocusLocations:i,matchedFocusLocations:i.filter(h=>d.has(xi(h.file,h.line))),unmatchedFocusLocations:i.filter(h=>!d.has(xi(h.file,h.line)))},behaviorCommand:dC(g,"behavior"),exactSourceCommand:dC(g,"source")}}function kj(e,t,n){let r=new Map(e.nodes.map(T=>[T.id,T])),i=new Map(e.edges.map(T=>[T.id,T])),o=hn(e.paths.flatMap(T=>T.nodeIds)),s=hn(e.anchors.filter(T=>T.status==="matched").flatMap(T=>T.nodeIds)),a=e.nodes.filter(T=>T.disposition==="emitted"&&T.attributes.upstreamCausalPath===!0).sort((T,G)=>Number(G.attributes.upstreamCausalDistance??0)-Number(T.attributes.upstreamCausalDistance??0)||T.id.localeCompare(G.id)).map(T=>T.id),c=new Set(a),l=Math.max(0,n-s.length),d=jj(e,s,t,l).slice(0,l),m=new Set(d),p=new Set(d),f=new Set([...o,...a,...s]),g=e.edges.filter(T=>T.disposition==="emitted"&&T.kind!=="structural-membership"),h=e.edges.filter(T=>T.disposition!=="excluded"&&T.disposition!=="unsupported"&&T.kind!=="structural-membership"),y=new Set([...e.paths.flatMap(T=>T.edgeIds),...g.filter(T=>c.has(T.fromNodeId)&&c.has(T.toNodeId)).map(T=>T.id)]),S=e.paths.some(T=>T.edgeIds.length>0),I=Nj(e,i,s,d),x=b1(s,h,r,Lj),E=hn(g.filter(T=>T.kind==="call"&&s.includes(T.fromNodeId)).map(T=>T.toNodeId)),b=new Set(hn([...x,...S?[]:E]));for(let T of b)I.add(T);let v=hn(g.flatMap(T=>f.has(T.fromNodeId)||f.has(T.toNodeId)?[T.fromNodeId,T.toNodeId]:[])),C=e.nodes.filter(T=>T.disposition==="emitted"&&T.kind!=="structural-region"&&g.some(G=>G.fromNodeId===T.id||G.toNodeId===T.id)).map(T=>T.id),R=hn([...a,...o,...s,...d,...b,...v,...C]).filter(T=>r.has(T)),P=Aj(R,n,S,f,m,b),w=new Set(P);return{nodeById:r,edgeById:i,knownCausalEdges:h,candidateNodeIds:R,selectedNodeIds:P,selectedNodeIdSet:w,connectorNodeIds:new Set([...o,...a]),expansiveNodeIds:I,supplementalNodeIds:b,completeOutlineNodeIds:p,pathEdgeIds:y}}function Nj(e,t,n,r){let i=new Set(n);for(let o of r)i.add(o);if(x1(e,t,i),e.paths.every(o=>o.nodeIds.length===0))for(let o of e.anchors)for(let s of o.nodeIds)i.add(s);return i}function Aj(e,t,n,r,i,o){let s=[];for(let a of e)n&&!r.has(a)&&!i.has(a)&&!o.has(a)||s.length>=t&&!r.has(a)||s.push(a);return s}function _j(e,t,n,r,i){let{connectorNodeIds:o,selectedNodeIds:s,nodeById:a,knownCausalEdges:c,pathEdgeIds:l,expansiveNodeIds:u,supplementalNodeIds:d,completeOutlineNodeIds:m}=n,p=new Set,f=new Set(t.anchors.flatMap(h=>h.nodeIds));return{steps:s.map((h,y)=>{let S=a.get(h),I=s1(S,r);for(let x of I)p.add(xi(S.location.file,x));return{id:i.get(h),nodeId:h,order:y,role:f.has(h)?"anchor":o.has(h)?"connector":"junction",kind:S.kind,label:S.label,location:S.location,behavior:Hj(e,S,f.has(h),[...new Set([...I,...t1(e,S,c,a,l,u)])],I,u.has(S.id)&&(I.length===0||f.has(S.id)),d.has(S.id),m.has(S.id)&&I.length===0)}}),matchedFocusLocations:p}}function Oj(e,t,n){let{edgeById:r,knownCausalEdges:i,selectedNodeIdSet:o}=t,s=new Map;for(let l of e.paths)for(let u=0;u<l.edgeIds.length;u+=1){let d=r.get(l.edgeIds[u]),m=l.nodeIds[u],p=l.nodeIds[u+1];!d||!m||!p||s.set(d.id,d.fromNodeId===m&&d.toNodeId===p?"forward":"reverse")}return i.filter(l=>o.has(l.fromNodeId)&&o.has(l.toNodeId)).sort((l,u)=>S1(l,u,e)).map((l,u)=>({id:C1(l.id),edgeId:l.id,order:u,kind:l.kind,fromStepId:n.get(l.fromNodeId),toStepId:n.get(l.toNodeId),directed:!0,pathTraversal:s.get(l.id)??"adjacent",evidence:l.evidence}))}function Bj(e,t,n){return e.paths.map(i=>({id:i.id,status:i.status,stepIds:i.nodeIds.flatMap(o=>{let s=t.get(o);return s?[s]:[]}),transitionIds:i.edgeIds.flatMap(o=>{let s=n.get(o);return s?[s]:[]})}))}function $j(e,t,n){return t.length===0?"unavailable":e.anchors.some(r=>r.status==="ambiguous")?"ambiguous":n.some(r=>r.status==="partial")?"partial":"connected"}function jj(e,t,n,r){if(r<=0||n.length===0)return[];let i=new Set(t),o=new Set(n.map(s=>xi(s.file,s.line)));return hn(e.edges.filter(s=>s.disposition!=="excluded"&&s.disposition!=="unsupported"&&["call","runtime-boundary"].includes(s.kind)&&i.has(s.fromNodeId)&&s.evidence.some(a=>!["candidate","unknown"].includes(a.strength)&&a.location&&o.has(xi(a.location.file,a.location.line)))).sort((s,a)=>{let c=s.evidence.find(u=>u.location)?.location,l=a.evidence.find(u=>u.location)?.location;return(c?.file??"").localeCompare(l?.file??"")||(c?.line??Number.MAX_SAFE_INTEGER)-(l?.line??Number.MAX_SAFE_INTEGER)||s.id.localeCompare(a.id)}).map(s=>s.toNodeId)).slice(0,r)}function fC(e){return e.location!=null&&["symbol","source-construct","runtime-boundary-participant"].includes(e.kind)}function Hj(e,t,n,r,i,o,s,a){if(!fC(t))return null;let{sourceLines:c,range:l,inRangeFocusLines:u,outline:d,causalOutline:m,connectorSlice:p}=qj(e,t,r,o),f=c.slice(l.startLine,l.endLine+1).join(`
|
|
36
|
+
`).length,g=Kj(e,t.location.file,l,c),h=x=>Vj(e,t,l.startLine,l.endLine,i.filter(E=>E>=l.startLine&&E<=l.endLine),x),y=zj(t,s,f),S=n&&(u.length===0||y),I=Uj(d,p,a||S,y,g,m?.outlineCharacters??f);return h(I??Wj(e,t.location.file,l,c,t.label))}function Uj(e,t,n,r,i,o){return e&&n?sC(e):!n&&!r&&Gj(t,i,o)?t:e?sC(e):null}function qj(e,t,n,r){let i=t.location.endLine??t.location.line,o=j(e,t.location.file),s=n.length>0?n:[t.location.line],a=t.kind==="runtime-boundary-participant"?Lt(e,t.location.file,0,Math.max(0,o.length-1),[t.location.line]):Lt(e,t.location.file,t.location.line,i,s),c=n.filter(m=>m>=a.startLine&&m<=a.endLine),l=oi(e,t.location.file,a.startLine,a.endLine,c),u=l??(c.length>0?oi(e,t.location.file,a.startLine,a.endLine,c,{requireSavings:!1}):null),d=c.length>0?f1(e,t,a.startLine,a.endLine,c,u,r):null;return{sourceLines:o,range:a,inRangeFocusLines:c,outline:l,causalOutline:u,connectorSlice:d}}function zj(e,t,n){return(t||e.kind==="runtime-boundary-participant"||e.anchorIds.length>0)&&n<=Mj}function Gj(e,t,n){return e!==null&&!t&&e.renderedCharacters<n}function Kj(e,t,n,r){let i=ln(e,t,n.startLine,n.endLine);return r.slice(n.startLine,n.endLine+1).some((o,s)=>o.length>Dj&&(i.get(n.startLine+s)??[]).some(a=>["binding","branch","loop","call","return","throw","mutation"].includes(a)))}function Wj(e,t,n,r,i){let o=r.slice(n.startLine,n.endLine+1),s=o.join(`
|
|
37
|
+
`),a=ln(e,t,n.startLine,n.endLine);return{kind:"source",constructKind:"source construct",signature:o.find(c=>c.trim().length>0)?.trim()??i,lines:o.map((c,l)=>({line:n.startLine+l,endLine:n.startLine+l,depth:0,signals:a.get(n.startLine+l)??[],text:c,copied:!0})),coverage:{sourceStatements:o.length,representedStatements:o.length,copiedStatements:o.length,omittedStatements:0},rawCharacters:s.length,renderedCharacters:s.length}}function Vj(e,t,n,r,i,o){if(!t.location)return o;let s=pu(e,t.location.file,n,r);if(!s.available)return o;let a=Jj(e,t.location.file,n,r,i,s.targets),c=Xj(e,a),l=[...new Map([...a,...c].map(m=>[m.definition.symbol,m])).values()].sort((m,p)=>m.definition.relativePath.localeCompare(p.definition.relativePath)||m.definition.startLine-p.definition.startLine||m.definition.symbol.localeCompare(p.definition.symbol)),u=[],d=[];for(let{definition:m,kind:p}of l){let f=Zj(e,{definition:m,kind:p});"reason"in f?d.push(f):u.push(f)}return{...o,...u.length===0?{}:{supportingDeclarations:u},...d.length===0?{}:{omittedSupportingDeclarations:d}}}function Jj(e,t,n,r,i,o){let s=ln(e,t,n,r),a=new Set(i);for(let c of i){let l=gm(e,t,c,r)[0];l!==void 0&&a.add(l)}return[...new Map(o.flatMap(c=>{let l=Yj(e,t,n,r,i,s,a,c);return l?[[l.definition.symbol,l]]:[]})).values()].sort((c,l)=>c.definition.relativePath.localeCompare(l.definition.relativePath)||c.definition.startLine-l.definition.startLine||c.definition.symbol.localeCompare(l.definition.symbol))}function gC(e,t,n,r){let i=e.relativePath===t&&e.startLine<=r&&e.endLine>=n;return!e.isTypeLike&&!i}function Yj(e,t,n,r,i,o,s,a){let c=a.definition;if(!gC(c,t,n,r))return null;let l=gu(e,c),u=i.length>0&&l&&o.get(a.sourceLine)?.includes("return"),d=l&&s.has(a.sourceLine);return l&&!u&&!d?null:{definition:c,kind:u?"return-value-transformer":d?"focused-causal-target":"compiler-referenced-declaration"}}function Xj(e,t){let n=[],r=t.filter(({kind:a})=>a!=="compiler-referenced-declaration").map(({definition:a})=>({owner:a,depth:1})),i=new Set,o=new Set(t.map(({definition:a})=>a.symbol)),s=(a,c,l,u)=>{for(let d of l){let m=Qj(e,a,d,u);if(!m)continue;let{definition:p}=m;o.has(p.symbol)||(o.add(p.symbol),n.push(m)),m.kind==="focused-causal-target"&&c<2&&r.push({owner:p,depth:c+1})}};for(;r.length>0;){let a=r.shift();if(!a||i.has(a.owner.symbol))continue;i.add(a.owner.symbol);let{owner:c,depth:l}=a,u=pu(e,c.relativePath,c.startLine,c.endLine);if(!u.available)continue;let d=ln(e,c.relativePath,c.startLine,c.endLine);s(c,l,u.targets,d)}return n}function Qj(e,t,n,r){let i=n.definition;if(!gC(i,t.relativePath,t.startLine,t.endLine))return null;let o=gu(e,i),s=o&&gm(e,t.relativePath,n.sourceLine,t.endLine).some(c=>(r.get(c)??[]).some(l=>["branch","return","throw"].includes(l))),a=o&&((r.get(n.sourceLine)??[]).some(c=>["branch","return","throw"].includes(c))||s);return o&&!a?null:{definition:i,kind:o?"focused-causal-target":"compiler-referenced-declaration"}}function Zj(e,{definition:t,kind:n}){let r=n==="compiler-referenced-declaration"?e1(e,t.relativePath,t.startLine,t.endLine):{startLine:t.startLine,endLine:t.endLine},i=j(e,t.relativePath).slice(r.startLine,r.endLine+1).join(`
|
|
38
|
+
`),o=n==="compiler-referenced-declaration"?null:oi(e,t.relativePath,t.startLine,t.endLine,[]),s=o?[o.signature,...o.lines.map(d=>`${d.line+1}${d.signals.length>0?`[${d.signals.join(",")}]`:""} ${d.text}`)].join(" | "):null,a=s&&s.length<i.length?s:i,c={symbol:t.symbol,label:t.leaf,file:t.relativePath,line:r.startLine,endLine:r.endLine},l=n==="compiler-referenced-declaration"?1e3:8e3,u=n==="compiler-referenced-declaration"?12:120;return a.length>l||r.endLine-r.startLine>u?{...c,reason:"source-too-large"}:{kind:n,...c,text:a}}function e1(e,t,n,r){let i=_(e,t);if(!i)return{startLine:n,endLine:r};let o=[];hC(i.rootNode,a=>{Fj.has(a.type)&&a.startPosition.row<=n&&a.endPosition.row>=r&&o.push(a)});let s=o.sort((a,c)=>a.endPosition.row-a.startPosition.row-(c.endPosition.row-c.startPosition.row)||a.endIndex-a.startIndex-(c.endIndex-c.startIndex))[0];return s?{startLine:s.startPosition.row,endLine:s.endPosition.row}:{startLine:n,endLine:r}}function hC(e,t){t(e);for(let n of e.namedChildren)hC(n,t)}function sC(e){return{kind:"outline",constructKind:e.constructKind,signature:e.signature,lines:e.lines,coverage:e.coverage,rawCharacters:e.rawCharacters,renderedCharacters:e.outlineCharacters}}function t1(e,t,n,r,i,o){if(!fC(t))return[];let s=new Set,a=new Set(z(e,t.location.file)?.callSites.map(c=>c.line)??[]);t.kind==="runtime-boundary-participant"&&s.add(t.location.line),o.has(t.id)&&n1(e,t.location).forEach(c=>s.add(c));for(let c of n){if(c.fromNodeId!==t.id&&c.toNodeId!==t.id)continue;let l=r.get(c.fromNodeId===t.id?c.toNodeId:c.fromNodeId);r1(t,c,l,i,o)&&i1(e,t.location,c,l,a).forEach(u=>s.add(u))}return[...s].sort((c,l)=>c-l)}function n1(e,t){return ho(e,{files:[t.file]}).filter(n=>n.source.startLine>=t.line&&n.source.startLine<=(t.endLine??t.line)).map(n=>n.source.startLine)}function r1(e,t,n,r,i){let o=i.has(e.id)&&["call","reference","runtime-boundary"].includes(t.kind)&&t.fromNodeId===e.id;return r.has(t.id)||o||(n?.anchorIds.length??0)>0}function i1(e,t,n,r,i){let o=n.evidence.flatMap(l=>l.location?.file===t.file?[l.location.line]:[]),s=o.filter(l=>i.has(l)),a=s.length>0?s:o,c=o1(e,t,r?.attributes.leaf,i);return c!==void 0&&a.push(c),a}function o1(e,t,n,r){if(typeof n!="string"||n.length===0)return;let i=uo(e,t.file,n).filter(o=>o>=t.line&&o<=(t.endLine??t.line));return i.find(o=>r.has(o))??i[0]}function s1(e,t){if(!e.location)return[];let n=e.location.endLine??e.location.line;return t.filter(r=>r.file===e.location.file&&r.line>=e.location.line&&r.line<=n).map(r=>r.line)}function a1(e){let t=new Map;for(let n of e){if(!n.file||!Number.isSafeInteger(n.line)||n.line<0)throw new RangeError(`Behavior focus locations require a repository file and non-negative line; received ${JSON.stringify(n)}.`);t.set(xi(n.file,n.line),{file:n.file,line:n.line})}return[...t.values()].sort((n,r)=>n.file.localeCompare(r.file)||n.line-r.line)}function xi(e,t){return`${e}\0${t}`}function c1(e,t){let{db:n,file:r,startLine:i,endLine:o,outline:s}=e;return s?[...new Map(t.flatMap(a=>s.lines.filter(c=>c.text.length<=500&&c.signals.some(l=>["branch","loop","catch","finally"].includes(l))&&a>=c.line&&a<=c.endLine).sort((c,l)=>c.endLine-c.line-(l.endLine-l.line)||c.line-l.line).slice(0,2).map(c=>[`${c.line}\0${c.endLine}`,c]))).values()]:Aa(n,r,i,o,t)}function l1(e,t){let{outline:n,endLine:r,sourceLines:i,behaviorSignals:o}=e,s=(n?.lines??[]).find(c=>c.line===t)??{line:t,endLine:Math.min(r,t+40),depth:0,signals:o.get(t)??[],text:(i[t]??"").trim(),copied:!0};return(n?.lines??i.slice(s.line,s.endLine+1).map((c,l)=>{let u=s.line+l;return{line:u,endLine:u,depth:0,signals:o.get(u)??[],text:c.trim(),copied:!0}})).filter(c=>c.line>=s.line&&c.line<=s.endLine&&c.text.length<=500&&c.signals.some(l=>["binding","branch","call","mutation"].includes(l)))}function u1(e,t,n){let{db:r,file:i,endLine:o,behaviorSignals:s}=e,a=[];for(let c of t){let l=gm(r,i,c,o),u=l[0];u!==void 0&&n.add(u);let d=l.find(m=>(s.get(m)??[]).some(p=>p==="branch"||p==="loop"));d!==void 0&&(n.add(d),a.push({focusLine:c,governingUse:d,lines:l1(e,d)}))}for(let c of a.sort((l,u)=>u.governingUse-u.focusLine-(l.governingUse-l.focusLine)||l.focusLine-u.focusLine).slice(0,2))for(let l of c.lines.slice(0,14))n.add(l.line)}function yC(e,t,n,r){for(let i of t)for(let o of e?.lines??[])o.line<i.line||o.line>i.endLine||o.signals.some(s=>r.has(s))&&n.add(o.line)}function d1(e,t,n,r){let{behaviorSignals:i,outline:o,focusLines:s}=e;return g1([...i.get(t)??[],...o?.lines.filter(a=>t>=a.line&&t<=a.endLine).flatMap(a=>a.signals)??[],...n.get(t)??[],...s.includes(t)?["anchor"]:[],...r.has(t)?["call"]:[]])}function m1(e,t,n,r){let{db:i,file:o,startLine:s,endLine:a,outline:c,sourceLines:l}=e,u=z(i,o),d=new Set(u?.callSites.map(h=>h.line)??[]),m=new Map([...c?.lines??[],...n].filter(h=>h.signals.some(y=>["branch","loop","catch","finally"].includes(y))).map(h=>[h.line,h])),p=new Map((c?.lines??[]).filter(h=>h.text.length<=500&&h.signals.includes("shape")&&(h.signals.includes("call")||h.signals.includes("mutation")||h.signals.includes("return"))).sort((h,y)=>h.endLine-h.line-(y.endLine-y.line)||h.line-y.line).map(h=>[h.line,h])),f=new Map((r?.lines??[]).map(h=>[h.line,h.signals.filter(y=>y!=="lifecycle")])),g=[...t].filter(h=>h>=s&&h<=a).sort((h,y)=>h-y).map(h=>{let y=m.get(h)??p.get(h);return{line:h,endLine:y?.endLine??h,depth:y?.depth??0,signals:d1(e,h,f,d),text:y?.text??(l[h]??"").trim(),copied:y?.copied??!0}}).filter(h=>h.text.length>0);return g.length===0?null:p1(e,g,r)}function p1(e,t,n){let{db:r,file:i,label:o,startLine:s,endLine:a,outline:c,sourceLines:l}=e,u=n?.candidateLines??Lu(r,i,s,a,{minimumBodyLines:0})?.candidateLines??0,d=Math.max(c?.coverage.sourceStatements??0,u,t.length),m=c?.signature??(l[s]??o).trim(),p=m.length+t.reduce((g,h)=>g+h.text.length+h.signals.join(",").length+12,0),f=l.slice(s,a+1).join(`
|
|
39
|
+
`).length;return{kind:"connector-slice",constructKind:c?.constructKind??"source construct",signature:m,lines:t,coverage:{sourceStatements:d,representedStatements:t.length,copiedStatements:t.filter(g=>g.copied).length,omittedStatements:Math.max(0,d-t.length)},rawCharacters:f,renderedCharacters:p}}function f1(e,t,n,r,i,o,s){if(!t.location)return null;let a=bC(e,t.location.file);if(!a)return null;let c=j(e,t.location.file),l=ln(e,t.location.file,n,r),u={db:e,file:t.location.file,label:t.label,startLine:n,endLine:r,focusLines:i,outline:o,sourceLines:c,behaviorSignals:l},d=[...l].filter(([,y])=>y.length>0).map(([y])=>y).sort((y,S)=>y-S),m=i.map(y=>(l.get(y)??[]).length>0?y:d.find(S=>S>y&&S-y<=8)??y),p=new Set([...i,...m]),f=s?Lu(e,u.file,n,r,{minimumBodyLines:0}):null,g=c1(u,m);for(let y of f?.lines??[])p.add(y.line);for(let y of g)p.add(y.line);for(let[y,S]of l)S.includes("call")&&S.includes("shape")&&p.add(y);u1(u,m,p);let h=new Set(["binding","branch","loop","call","return","throw","mutation"]);return yC(o,g,p,h),h1(a,p,u,h),m1(u,p,g,f)}function g1(e){let t=["anchor","signature","binding","branch","loop","call","await","return","throw","mutation","shape","spread","catch","finally"],n=new Set(e);return t.filter(r=>n.has(r))}var aC=new WeakMap;function bC(e,t){let n=z(e,t)?.language;if(n!=="typescript"&&n!=="tsx"&&n!=="javascript")return null;let r=j(e,t).join(`
|
|
40
|
+
`),i=aC.get(e);i||(i=new Map,aC.set(e,i));let o=i.get(t);if(o?.source===r)return o.bindings;let s=ot(t,r),a=s.errors.length===0?iC(s):null;return i.set(t,{source:r,bindings:a}),a}function gm(e,t,n,r){return[...new Set((bC(e,t)??[]).filter(i=>i.startLine<=n&&i.endLine>=n).flatMap(i=>i.referenceLines.filter(o=>o>n&&o<=r)))].sort((i,o)=>i-o)}function h1(e,t,n,r){let{behaviorSignals:i,startLine:o,endLine:s,outline:a}=n,c=e.filter(u=>u.startLine>=o&&u.endLine<=s&&(u.startLine!==o||u.endLine!==s)),l=!0;for(;l;){let u=t.size;for(let m of c){if(!(m.referenceLines.some(h=>t.has(h))||[...t].some(h=>h>=m.startLine&&h<=m.endLine)))continue;let f=Array.from({length:m.endLine-m.startLine+1},(h,y)=>m.startLine+y),g=m.referenceLines.filter(h=>h>=o&&h<=s&&(i.get(h)??[]).some(y=>r.has(y)));for(let h of[...f,...g])t.has(h)||t.add(h)}let d=(a?.lines??[]).filter(m=>t.has(m.line)&&m.signals.some(p=>["branch","loop","catch","finally"].includes(p)));yC(a,d,t,r),l=t.size!==u}}function y1(e,t,n){return hn(e.flatMap(r=>{let i=n.get(r),o=t.filter(s=>s.kind==="call"&&s.toNodeId===r).map(s=>({edge:s,node:n.get(s.fromNodeId)})).filter(s=>s.node!==void 0&&["symbol","source-construct","runtime-boundary-participant"].includes(s.node.kind)&&s.node.location!==null).sort((s,a)=>{let c=cC(a.edge)-cC(s.edge);if(c!==0)return c;let l=lC(s.node,i)?0:1,u=lC(a.node,i)?0:1,d=mC(s.node),m=mC(a.node);return l-u||d-m||s.node.label.localeCompare(a.node.label)});return o[0]?[o[0].node.id]:[]}))}function cC(e){let t={exact:4,mixed:3,derived:2,candidate:1,unknown:0};return Math.max(0,...e.evidence.map(n=>t[n.strength]))}function lC(e,t){return!e.location||!t?.location?!1:uC(e.location.file)===uC(t.location.file)}function uC(e){return e.split("/").filter(Boolean).slice(0,2).join("/")}function b1(e,t,n,r){let i=new Set(e),o=new Set,s=[],a=hn(e);for(let c=0;c<r&&a.length>0;c+=1){let l=a.filter(d=>!o.has(d));for(let d of l)o.add(d);let u=y1(l,t,n);a=[];for(let d of u)!i.has(d)&&!s.includes(d)&&s.push(d),o.has(d)||a.push(d)}return s}function S1(e,t,n){let r=new Map(n.paths.flatMap(i=>i.edgeIds).map((i,o)=>[i,o]));return(r.get(e.id)??Number.MAX_SAFE_INTEGER)-(r.get(t.id)??Number.MAX_SAFE_INTEGER)||e.id.localeCompare(t.id)}function v1(e){return`step:${e}`}function C1(e){return`transition:${e}`}function dC(e,t){return e.length===0?null:`scip-query inspect ${e.map(n=>`--at ${O(n)}`).join(" ")} --view ${t}`}function hn(e){return[...new Set(e)]}function x1(e,t,n){for(let r of e.paths){let i=r.nodeIds[0],o=t.get(r.edgeIds[0]??""),s=r.nodeIds[1];i&&s&&o?.fromNodeId===i&&o.toNodeId===s&&n.add(i)}}function mC(e){return(e.location?.endLine??e.location?.line??0)-(e.location?.line??0)}var SC=["call","contract-symbol","import","reference","runtime-boundary"],R1={call:[{family:"control",subtype:"call"}],"contract-symbol":[{family:"contract",subtype:"uses-contract-symbol"}],import:[{family:"identity",subtype:"imports"}],reference:[{family:"identity",subtype:"references"}]},E1={"structural-membership":[{family:"identity",subtype:"contains"}],"boundary-observation":[{family:"identity",subtype:"owns-runtime-observation"}],"external-import":[{family:"identity",subtype:"imports-external"}]};function vC(e){if(e.kind!=="runtime-boundary")return CC(R1[e.kind]);let t=I1(e),n=[{family:"control",subtype:"runtime-handoff",context:t}];return e.evidence==="runtime-boundary:carrier.discriminator"&&(n.push({family:"control",subtype:"discriminator-dispatch",context:{...t},attributes:{joinRule:"carrier.discriminator",...e.fromBoundaryParticipant?.action?{producerAction:e.fromBoundaryParticipant.action}:{},...e.toBoundaryParticipant?.action?{consumerAction:e.toBoundaryParticipant.action}:{}}}),n.push({family:"data",subtype:"serialized-discriminator-transfer",context:{...t},attributes:{joinRule:"carrier.discriminator"}})),e.evidence==="runtime-boundary:queue.address"&&e.fromBoundaryParticipant?.action==="queue.send"&&e.toBoundaryParticipant?.action==="queue.consume"&&n.push({family:"temporal",subtype:"enqueue-before-consume",context:{...t},attributes:{producerAction:e.fromBoundaryParticipant.action,consumerAction:e.toBoundaryParticipant.action,retryPolicy:"unknown"}}),n}function Mc(e){return CC(E1[e])}function CC(e){return e.map(t=>({...t,...t.context?{context:{...t.context}}:{},...t.attributes?{attributes:{...t.attributes}}:{}}))}function I1(e){let t=e.fromBoundaryParticipant?.protocol??e.toBoundaryParticipant?.protocol;return{crossesRuntimeBoundary:!0,...t?{protocol:t}:{},...e.runtimeBoundaryKey?{runtimeKey:e.runtimeBoundaryKey}:{}}}import{join as jC}from"path";import{createRequire as w1}from"module";import{resolve as rs}from"path";var P1=w1(import.meta.url),ts,xC=new Map;function IC(e,t,n){let r=wC();if(!r)return Fc("The TypeScript compiler runtime is unavailable.");let i=L1(r,bm(r,e,t)),o=i.getSourceFile(rs(t))??i.getSourceFile(t);if(!o)return Fc(`The TypeScript compiler did not materialize ${t}.`);let s=i.getSyntacticDiagnostics(o);if(s.length)return Fc(s.map(m=>{let p=o.getLineAndCharacterOfPosition(m.start??0);return`TypeScript syntax error at ${t}:${p.line+1}: ${r.flattenDiagnosticMessageText(m.messageText," ")}`}).join("; "));let a={ts:r,sourceFile:o,checker:i.getTypeChecker(),points:new Map,edges:new Map,unsupported:new Set,nextCfgId:0},c=F1(r,o,n);if(c.length===0)return Fc("No function-like construct intersects the selected source range.");let l=new Map(c.map(m=>[m,N1(o,m)])),u=c.map(m=>_1(a,m,A1(r,m,l),l.get(m)));for(let m of u)V1(a,m),vH(a,m),IH(a,m);LH(a,u);let d=[...a.unsupported].sort();return{points:[...a.points.values()].map(({node:m,...p})=>p).sort(NH),edges:[...a.edges.values()].sort((m,p)=>m.id.localeCompare(p.id)),coverage:{status:d.length===0?"complete":"partial",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:d}}}function os(){return wC()}function wC(){if(ts!==void 0)return ts;try{ts=P1("typescript")}catch{ts=xa()?.ts??null}return ts}var hm=null,Dc=null,ym=null;function PC(e){return hm||(hm={target:e.ScriptTarget.ESNext,module:e.ModuleKind.ESNext,moduleResolution:e.ModuleResolutionKind.Bundler,skipLibCheck:!0,noResolve:!0,libReplacement:!1}),hm}var Rr=new Map,T1=8;function bm(e,t,n){let r=rs(n),i=Rr.get(r);if(i&&i.text===t)return Rr.delete(r),Rr.set(r,i),i.sourceFile;let o=e.createSourceFile(r,t,PC(e).target,!0,D1(e,r));for(Rr.set(r,{text:t,sourceFile:o});Rr.size>T1;){let s=Rr.keys().next().value;if(s===void 0)break;Rr.delete(s)}return o}function L1(e,t){let n=t.fileName,r=t.text,i=PC(e),o=e.createCompilerHost(i,!0),s=o.getSourceFile.bind(o),a=o.readFile.bind(o),c=o.fileExists.bind(o);if(!Dc||!ym){let m=o.getCurrentDirectory(),p=o.getCanonicalFileName.bind(o);Dc=e.createModuleResolutionCache(m,p,i),ym=e.createTypeReferenceDirectiveResolutionCache(m,p,i,Dc.getPackageJsonInfoCache())}let l=Dc,u=ym;i.types===void 0&&(i.types=e.getAutomaticTypeDirectiveNames(i,o)),o.getModuleResolutionCache=()=>l;let d=new Set(i.types??[]);return o.resolveModuleNameLiterals=(m,p,f,g,h)=>m.map(y=>d.has(M1(y.text))?e.resolveModuleName(y.text,p,g,o,l,f,e.getModeForUsageLocation(h,y,g)):{resolvedModule:void 0}),o.resolveTypeReferenceDirectiveReferences=(m,p,f,g)=>m.map(h=>e.resolveTypeReferenceDirective(typeof h=="string"?h:h.fileName,p,g,o,f,u)),o.getSourceFile=(m,p,f,g)=>{if(rs(m)===n)return t;let h=xC.get(m);if(h)return h;let y=s(m,p,f,g);return y&&xC.set(m,y),y},o.readFile=m=>rs(m)===n?r:a(m),o.fileExists=m=>rs(m)===n||c(m),e.createProgram([n],i,o)}function M1(e){if(e.startsWith(".")||e.startsWith("/"))return"";let t=e.split("/");return e.startsWith("@")?t.length>=2?`${t[0].slice(1)}__${t[1]}`:"":t[0]??""}function D1(e,t){return/\.tsx$/iu.test(t)?e.ScriptKind.TSX:/\.[cm]?js$/iu.test(t)?e.ScriptKind.JS:/\.jsx$/iu.test(t)?e.ScriptKind.JSX:e.ScriptKind.TS}function F1(e,t,n){let r=[],i=(o,s=!1)=>{if(TC(e,o)){let a=t.getLineAndCharacterOfPosition(o.getStart(t)).line,c=t.getLineAndCharacterOfPosition(o.getEnd()).line;s||=!n||k1(t,o,a,c,n),s&&r.push(o)}o.forEachChild(a=>i(a,s))};return t.forEachChild(i),r.sort((o,s)=>o.getStart(t)-s.getStart(t))}function k1(e,t,n,r,i){if(i.startColumn===void 0||i.endColumn===void 0)return n<=i.endLine&&r>=i.startLine;let o=e.getPositionOfLineAndCharacter(i.startLine,i.startColumn),s=e.getPositionOfLineAndCharacter(i.endLine,i.endColumn);return(t.name??t).getStart(e)>=o&&t.end<=s}function TC(e,t){return e.isFunctionLike(t)&&"body"in t&&t.body!==void 0}function N1(e,t){return`callable:${encodeURIComponent(e.fileName)}:${t.getStart(e)}:${t.getEnd()}`}function A1(e,t,n){for(let r=t.parent;r;r=r.parent)if(TC(e,r)&&n.has(r))return n.get(r);return null}function _1(e,t,n,r){let i=new Map,o=Ie(e,i,"exit",null),s=t.body,a=o.id;if(s&&e.ts.isBlock(s))a=Ei(e,i,[...s.statements],o.id,{breakTarget:null,continueTarget:null,throwTarget:null,exitId:o.id});else if(s){let l=Ie(e,i,"statement",s);ae(i,l.id,o.id),a=l.id}let c=Ie(e,i,"entry",t);return ae(i,c.id,a),{id:r,node:t,parentId:n,cfg:i,entryId:c.id,exitId:o.id}}function Ei(e,t,n,r,i){let o=r;for(let s=n.length-1;s>=0;s-=1)o=Ii(e,t,n[s],o,i);return o}function Ii(e,t,n,r,i){let o=e.ts;if(o.isBlock(n))return Ei(e,t,[...n.statements],r,i);if(o.isIfStatement(n))return O1(e,t,n,r,i);let s=BH(e,t,n,r,i);return s!==null?s:o.isSwitchStatement(n)?H1(e,t,n,r,i):o.isTryStatement(n)?z1(e,t,n,r,i):o.isExpressionStatement(n)?ns(e,t,n.expression,r):U1(e,t,n,r,i)??q1(e,t,n,r)}function O1(e,t,n,r,i){let o=Ie(e,t,"predicate",n.expression),s=Ii(e,t,n.thenStatement,r,i),a=n.elseStatement?Ii(e,t,n.elseStatement,r,i):r;return ae(t,o.id,s),ae(t,o.id,a),o.id}function B1(e,t,n,r,i){let o=Ie(e,t,"predicate",n.expression),s=Ii(e,t,n.statement,o.id,{...i,breakTarget:r,continueTarget:o.id});return ae(t,o.id,s),ae(t,o.id,r),e.ts.isDoStatement(n)?s:o.id}function $1(e,t,n,r,i){let o=Ie(e,t,"predicate",n.condition??n),s=n.incrementor?Ie(e,t,"statement",n.incrementor):null;s&&ae(t,s.id,o.id);let a=s?.id??o.id,c=Ii(e,t,n.statement,a,{...i,breakTarget:r,continueTarget:a});if(ae(t,o.id,c),n.condition&&ae(t,o.id,r),!n.initializer)return o.id;let l=Ie(e,t,"statement",n.initializer);return ae(t,l.id,o.id),l.id}function j1(e,t,n,r,i){e.unsupported.add("for-in/for-of loop variables are drawn from the iterable as a whole; per-element flow is not modeled.");let o=Ie(e,t,"predicate",n.expression),s=Ie(e,t,"statement",n.initializer),a=Ii(e,t,n.statement,o.id,{...i,breakTarget:r,continueTarget:o.id});return ae(t,o.id,s.id),ae(t,o.id,r),ae(t,s.id,a),o.id}function H1(e,t,n,r,i){e.unsupported.add("switch fallthrough is represented conservatively; discriminant-to-case value refinement is unsupported.");let o=Ie(e,t,"predicate",n.expression),s=r,a=[];for(let c=n.caseBlock.clauses.length-1;c>=0;c-=1){let l=n.caseBlock.clauses[c];s=Ei(e,t,[...l.statements],s,{...i,breakTarget:r}),a.push(s)}for(let c of a)ae(t,o.id,c);return ae(t,o.id,r),o.id}function U1(e,t,n,r,i){let o=e.ts;if(o.isReturnStatement(n)||o.isThrowStatement(n)){let s=Ie(e,t,"statement",n),a=o.isThrowStatement(n)?i.throwTarget??i.exitId:i.exitId;return ae(t,s.id,a),s.id}if(o.isBreakStatement(n)||o.isContinueStatement(n)){let s=o.isBreakStatement(n)?"break":"continue",a=i[`${s}Target`],c=Ie(e,t,"statement",n);return a||e.unsupported.add(`A ${s} statement could not be attached to a structured target.`),ae(t,c.id,a??r),c.id}return null}function q1(e,t,n,r){let i=Ie(e,t,"statement",n);return ae(t,i.id,r),i.id}function ns(e,t,n,r){let i=e.ts;if(i.isParenthesizedExpression(n))return ns(e,t,n.expression,r);if(i.isConditionalExpression(n)){let s=Ie(e,t,"predicate",n.condition);return ae(t,s.id,ns(e,t,n.whenTrue,r)),ae(t,s.id,ns(e,t,n.whenFalse,r)),s.id}if(i.isBinaryExpression(n)&&LC(i,n.operatorToken.kind)){let s=Ie(e,t,"predicate",n.left);return ae(t,s.id,r),ae(t,s.id,ns(e,t,n.right,r)),s.id}let o=Ie(e,t,"statement",n);return ae(t,o.id,r),o.id}function LC(e,t){return t===e.SyntaxKind.AmpersandAmpersandToken||t===e.SyntaxKind.BarBarToken||t===e.SyntaxKind.QuestionQuestionToken}function z1(e,t,n,r,i){let o=e.ts,s=n.finallyBlock?Ei(e,t,[...n.finallyBlock.statements],r,i):null,a=s??r,{catchEntry:c,catchNodes:l}=G1(e,t,n.catchClause,a,s,i),u=c??s??i.throwTarget,d=new Set(t.keys()),m=Ei(e,t,[...n.tryBlock.statements],a,{...i,throwTarget:u}),p=[...t.keys()].filter(g=>!d.has(g)),f=Ie(e,t,"statement",null);return ae(t,f.id,m),u&&(ae(t,f.id,u),RC(e,t,p,u)),s&&c&&RC(e,t,l,s),n.finallyBlock&&W1(o,n.tryBlock,n.catchClause?.block)&&e.unsupported.add("A finally block after return, break, or continue inside its try or catch is not sequenced in the local compiler CFG."),f.id}function G1(e,t,n,r,i,o){let s=null,a=[];if(n){let c=new Set(t.keys()),l={...o,throwTarget:i??o.throwTarget},u=Ei(e,t,[...n.block.statements],r,l);if(s=u,n.variableDeclaration){let d=Ie(e,t,"statement",n.variableDeclaration);ae(t,d.id,u),s=d.id}a=[...t.keys()].filter(d=>!c.has(d))}return{catchEntry:s,catchNodes:a}}function RC(e,t,n,r){for(let i of n)K1(e,t.get(i))&&ae(t,i,r)}function K1(e,t){let n=t.ast;if(!n||t.kind==="exit"||t.kind==="entry")return!1;let r=e.ts;return!(r.isReturnStatement(n)||r.isThrowStatement(n)||r.isBreakOrContinueStatement(n))}function W1(e,...t){let n=!1,r=i=>{if(!(n||e.isFunctionLike(i))){if(e.isReturnStatement(i)||e.isBreakOrContinueStatement(i)){n=!0;return}i.forEachChild(r)}};for(let i of t)i&&r(i);return n}function Ie(e,t,n,r){let i={id:`cfg:${e.nextCfgId++}`,kind:n,ast:r,successors:new Set,predecessors:new Set,definitions:[],uses:[],displayPoint:null,invalidatesAllDefinitions:!1};return t.set(i.id,i),i}function ae(e,t,n){e.get(t).successors.add(n),e.get(n).predecessors.add(t)}function V1(e,t){let n=t.cfg.get(t.entryId);AH(e,t,n);for(let r of t.cfg.values())!r.ast||r.kind==="entry"||r.kind==="exit"||(r.kind==="predicate"&&(r.displayPoint=is(e,r.ast,"predicate",null,"predicate",t.id)),Q1(e,t,r,r.ast),J1(e,r,r.ast),!r.displayPoint&&r.definitions.length===0&&r.uses.length===0&&(r.displayPoint=is(e,r.ast,"statement",null,FH(e,r.ast),t.id)))}function J1(e,t,n){let r=e.ts,i=o=>{if(!r.isFunctionLike(o)){if(r.isClassDeclaration(o)||r.isClassExpression(o)){Y1(r,o)&&(e.unsupported.add("Class initialization, static blocks, and computed members can execute effects outside the local control-flow model."),t.invalidatesAllDefinitions=!0);return}X1(e,o)&&(e.unsupported.add("Direct eval can read and write lexical bindings; its dynamically parsed source is not modeled."),t.invalidatesAllDefinitions=!0),o.forEachChild(i)}};i(n)}function Y1(e,t){return!!t.heritageClauses?.length||t.members.some(n=>e.isClassStaticBlockDeclaration(n)||e.isPropertyDeclaration(n)&&!!n.initializer||!!n.name&&e.isComputedPropertyName(n.name))}function X1(e,t){let n=e.ts;return!n.isCallExpression(t)||!n.isIdentifier(t.expression)||t.expression.text!=="eval"?!1:(e.checker.getSymbolAtLocation(t.expression)?.declarations??[]).every(i=>i.getSourceFile().isDeclarationFile)}function Q1(e,t,n,r){let i=e.ts,o=s=>{if(!(s!==r&&i.isFunctionLike(s))&&!Z1(e,t,n,s)&&!(i.isFunctionDeclaration(s)||i.isClassDeclaration(s)||i.isInterfaceDeclaration(s))){if(FC(e,s)){let a=kC(e,t.id,s);a&&n.uses.push(a),i.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}};o(r),n.uses=$C(n.uses)}function Z1(e,t,n,r){let i=e.ts;if(i.isVariableDeclaration(r))tH(e,t,n,r);else if(eH(i,r))n.uses.push(...Jt(e,t.id,r,n));else if(i.isBinaryExpression(r)&&BC(i,r.operatorToken.kind))nH(e,t,n,r);else if(MC(i,r))rH(e,t,n,r);else if(i.isDeleteExpression(r))DC(e,n);else return!1;return!0}function eH(e,t){return e.isConditionalExpression(t)||e.isBinaryExpression(t)&&LC(e,t.operatorToken.kind)}function tH(e,t,n,r){let i=e.ts,o=r.initializer??hH(i,r);vm(e,r.initializer);let s=o?Jt(e,t.id,o,n):[],a=Cm(e,r.name,c=>s.push(...Jt(e,t.id,c,n)));if(n.uses.push(...s),a.length===0&&i.isIdentifier(r.name)){n.invalidatesAllDefinitions=!0,e.unsupported.add("A variable declaration could not be resolved to a compiler symbol.");return}Sm(e,t.id,n,a,s)}function nH(e,t,n,r){let i=e.ts;r.operatorToken.kind===i.SyntaxKind.EqualsToken&&vm(e,r.right);let o=Jt(e,t.id,r.right,n);r.operatorToken.kind!==i.SyntaxKind.EqualsToken&&o.push(...Jt(e,t.id,r.left,n));let s=Bn(e,t.id,r.left,n,o);if(n.uses.push(...o),!s){n.invalidatesAllDefinitions=!0,e.unsupported.add("Dynamic assignment targets are not included in reaching definitions.");return}Sm(e,t.id,n,s,o)}function rH(e,t,n,r){let i=Jt(e,t.id,r.operand,n),o=Bn(e,t.id,r.operand,n,i)??[];n.uses.push(...i),Sm(e,t.id,n,o,i)}function Sm(e,t,n,r,i){let o=i.map(s=>s.point.id);for(let s of r)n.definitions.push({point:is(e,s.node,"definition",s.symbolKey,s.name,t),rhsUseIds:o,partial:s.partial??!1})}function Jt(e,t,n,r){let i=[],o=s=>{if(!e.ts.isFunctionLike(s)){if(e.ts.isDeleteExpression(s)){DC(e,r);return}if(MC(e.ts,s)){r.invalidatesAllDefinitions=!0;let a=e.sourceFile.getLineAndCharacterOfPosition(s.getStart(e.sourceFile));e.unsupported.add(`Nested increment/decrement at ${e.sourceFile.fileName}:${a.line+1} is not included in ordered local definition-use flow.`),o(s.operand);return}if(e.ts.isBinaryExpression(s)&&BC(e.ts,s.operatorToken.kind)){r.invalidatesAllDefinitions=!0,e.unsupported.add("Nested assignment expressions are not included in ordered local definition-use flow."),s.operatorToken.kind!==e.ts.SyntaxKind.EqualsToken&&o(s.left),o(s.right);return}if(FC(e,s)){let a=kC(e,t,s);a&&i.push(a),e.ts.isPropertyAccessExpression(s)&&o(s.expression);return}s.forEachChild(o)}};return o(n),$C(i)}function MC(e,t){return(e.isPrefixUnaryExpression(t)||e.isPostfixUnaryExpression(t))&&(t.operator===e.SyntaxKind.PlusPlusToken||t.operator===e.SyntaxKind.MinusMinusToken)}function vm(e,t){if(!t)return;let n=iH(e.ts,t);if(n){for(let i of n)vm(e,i);return}if(!kc(e,t)||!aH(e,t))return;let r=e.sourceFile.getLineAndCharacterOfPosition(t.getStart(e.sourceFile));e.unsupported.add(`Object alias at ${e.sourceFile.fileName}:${r.line+1} is not included in local points-to flow.`)}function iH(e,t){if(e.isObjectLiteralExpression(t))return t.properties.map(r=>oH(e,r));if(e.isArrayLiteralExpression(t))return t.elements.map(r=>e.isSpreadElement(r)?r.expression:r);if(e.isConditionalExpression(t))return[t.whenTrue,t.whenFalse];let n=sH(e,t);return n?[n]:void 0}function oH(e,t){if(e.isPropertyAssignment(t))return t.initializer;if(e.isShorthandPropertyAssignment(t))return t.name;if(e.isSpreadAssignment(t))return t.expression}function sH(e,t){if(e.isParenthesizedExpression(t)||e.isAsExpression(t)||e.isSatisfiesExpression(t)||e.isNonNullExpression(t)||e.isTypeAssertionExpression(t))return t.expression}function DC(e,t){t.invalidatesAllDefinitions=!0,e.unsupported.add("Property deletion is not included in local mutation flow; prior reaching definitions are invalidated.")}function aH(e,t){let n=e.ts,r=e.checker.getTypeAtLocation(t);return(r.isUnionOrIntersection()?r.types:[r]).some(o=>(o.flags&(n.TypeFlags.Object|n.TypeFlags.Any|n.TypeFlags.Unknown|n.TypeFlags.TypeParameter|n.TypeFlags.NonPrimitive))!==0)}function FC(e,t){if(e.ts.isPropertyAccessExpression(t))return!0;if(!e.ts.isIdentifier(t))return!1;let n=t.parent;return!(cH(e.ts,t)||e.ts.isLabeledStatement(n)||e.ts.isBreakOrContinueStatement(n)||uH(e.ts,t))}function cH(e,t){let n=t.parent;return!!(e.isPropertyAccessExpression(n)&&n.name===t||"name"in n&&n.name===t&&lH(e,n)||e.isPropertyAssignment(n)&&n.name===t||e.isBindingElement(n)&&n.propertyName===t)}function lH(e,t){return e.isVariableDeclaration(t)||e.isParameter(t)||e.isFunctionDeclaration(t)||e.isFunctionExpression(t)||e.isClassDeclaration(t)||e.isMethodDeclaration(t)||e.isPropertyDeclaration(t)||e.isInterfaceDeclaration(t)||e.isTypeAliasDeclaration(t)||_H(e,t)}function uH(e,t){for(let n=t.parent;n;n=n.parent){if(e.isExpression(n)||e.isStatement(n)||e.isSourceFile(n))return!1;if(e.isTypeNode(n))return!0}return!1}function kC(e,t,n){let r=Pi(e,n);return r?{point:is(e,r.node,"use",r.symbolKey,r.name,t),property:e.ts.isPropertyAccessExpression(n)}:null}function Cm(e,t,n){let r=e.ts;if(r.isIdentifier(t)){let o=Pi(e,t);return o?[o]:[]}let i=[];for(let o of t.elements)r.isOmittedExpression(o)||(o.initializer&&n&&n(o.initializer),i.push(...Cm(e,o.name,n)));return i}function Bn(e,t,n,r,i){let o=e.ts,s=dH(o,n);if(s)return Bn(e,t,s,r,i);if(o.isIdentifier(n)||o.isPropertyAccessExpression(n)){let a=Pi(e,n);return a?[{...a,partial:!1}]:null}return o.isElementAccessExpression(n)?mH(e,t,n,r,i):o.isObjectLiteralExpression(n)?pH(e,t,n,r,i):o.isArrayLiteralExpression(n)?gH(e,t,n,r,i):null}function dH(e,t){return e.isParenthesizedExpression(t)||e.isAsExpression(t)||e.isTypeAssertionExpression(t)||e.isNonNullExpression(t)?t.expression:null}function mH(e,t,n,r,i){let o=Pi(e,n.expression);return o?(i.push(...Jt(e,t,n.expression,r)),i.push(...Jt(e,t,n.argumentExpression,r)),[{node:n,symbolKey:o.symbolKey,name:`${o.name}[\u2026]`,partial:!0}]):null}function pH(e,t,n,r,i){let o=[];for(let s of n.properties){let a=fH(e,t,s,r,i);if(!a)return null;o.push(...a)}return o}function fH(e,t,n,r,i){let o=e.ts;if(o.isShorthandPropertyAssignment(n)){let s=e.checker.getShorthandAssignmentValueSymbol(n),a=s?NC(e,s):null,c=a?[{node:n.name,symbolKey:a,name:n.name.text,partial:!1}]:null;return n.objectAssignmentInitializer&&i.push(...Jt(e,t,n.objectAssignmentInitializer,r)),c}return o.isPropertyAssignment(n)?Bn(e,t,n.initializer,r,i):o.isSpreadAssignment(n)?Bn(e,t,n.expression,r,i):null}function gH(e,t,n,r,i){let o=e.ts,s=[];for(let a of n.elements){if(o.isOmittedExpression(a))continue;let c;if(o.isSpreadElement(a)?c=Bn(e,t,a.expression,r,i):o.isBinaryExpression(a)&&a.operatorToken.kind===o.SyntaxKind.EqualsToken?(i.push(...Jt(e,t,a.right,r)),c=Bn(e,t,a.left,r,i)):c=Bn(e,t,a,r,i),!c)return null;s.push(...c)}return s}function hH(e,t){let n=t.parent;if(!n||!e.isVariableDeclarationList(n))return null;let r=n.parent;return r&&(e.isForOfStatement(r)||e.isForInStatement(r))&&r.initializer===n?r.expression:null}function Pi(e,t){let n=e.ts;if(n.isIdentifier(t)){let r=bH(e,t);return r?{node:t,symbolKey:r,name:t.text}:null}if(n.isPropertyAccessExpression(t)){let r=kc(e,t.expression);return r?{node:t,symbolKey:`${r.symbolKey}.${t.name.text}`,name:t.getText(e.sourceFile)}:null}return t.kind===n.SyntaxKind.ThisKeyword?{node:t,symbolKey:yH(e,t),name:"this"}:OH(n,t)?Pi(e,t.expression):((n.isArrayLiteralExpression(t)||n.isObjectLiteralExpression(t))&&e.unsupported.add("Heap aggregate identity and destructured assignment are not included in local points-to flow."),null)}function kc(e,t){let n=e.ts;return n.isIdentifier(t)||n.isPropertyAccessExpression(t)||t.kind===n.SyntaxKind.ThisKeyword?Pi(e,t):n.isParenthesizedExpression(t)||n.isNonNullExpression(t)||n.isAsExpression(t)||n.isTypeAssertionExpression(t)||n.isSatisfiesExpression(t)?kc(e,t.expression):null}function yH(e,t){let n=e.ts,r=encodeURIComponent(e.sourceFile.fileName);for(let i=t.parent;i;i=i.parent)if(!n.isArrowFunction(i)){if(n.isClassLike(i))return`symbol:${r}:${i.getStart(e.sourceFile)}:this`;if(n.isFunctionLike(i)){let o=i.parent;return o&&(n.isClassLike(o)||n.isObjectLiteralExpression(o))?`symbol:${r}:${o.getStart(e.sourceFile)}:this`:`symbol:${r}:${i.getStart(e.sourceFile)}:this`}}return`symbol:${r}:0:this`}function bH(e,t){let n=t.parent,r=n&&e.ts.isShorthandPropertyAssignment(n)&&n.name===t?e.checker.getShorthandAssignmentValueSymbol(n)??e.checker.getSymbolAtLocation(t):e.checker.getSymbolAtLocation(t);return r?NC(e,r):null}function NC(e,t){let n=t;if((n.flags&e.ts.SymbolFlags.Alias)!==0)try{n=e.checker.getAliasedSymbol(n)}catch{}let r=n.valueDeclaration??n.declarations?.[0];return r?`symbol:${encodeURIComponent(r.getSourceFile().fileName)}:${r.getStart()}:${n.getName()}`:`symbol:${n.getName()}`}function is(e,t,n,r,i,o){let s=t.getStart(e.sourceFile),a=t.getEnd(),c=e.sourceFile.getLineAndCharacterOfPosition(s),l=`flow-point:${encodeURIComponent(e.sourceFile.fileName)}:${s}:${a}:${n}:${encodeURIComponent(r??i)}`,u=e.points.get(l);if(u)return u;let d={id:l,kind:n,name:i,symbolKey:r,callableId:o,start:s,end:a,line:c.line,column:c.character,node:t};return e.points.set(l,d),d}function Ri(e){return new Uint32Array(e+31>>>5)}function AC(e,t){return(e[t>>>5]&1<<(t&31))!==0}function Nc(e,t){e[t>>>5]|=1<<(t&31)}function SH(e,t){for(let n=0;n<e.length;n+=1){let r=e[n];for(;r!==0;){let i=r&-r;t((n<<5)+(31-Math.clz32(i))),r^=i}}}function _C(e,t,n){let r=new Set,i=[],o=[],s=c=>{r.add(c),o.push({id:c,successors:[...n(e.get(c))],cursor:0})};for(s(t);o.length>0;){let c=o[o.length-1];if(c.cursor<c.successors.length){let l=c.successors[c.cursor];c.cursor+=1,r.has(l)||s(l)}else i.push(c.id),o.pop()}let a=i.reverse();for(let c of e.keys())r.has(c)||a.push(c);return a}function vH(e,t){let n=[...t.cfg.values()].flatMap(y=>y.definitions),r=new Map;n.forEach((y,S)=>r.set(y.point.id,S));let i=RH(n),o=new Map;for(let[y,S]of i)o.set(y,S.map(I=>r.get(I.point.id)));let s=_C(t.cfg,t.entryId,y=>y.successors),a=new Map;s.forEach((y,S)=>a.set(y,S));let c=s.map(y=>t.cfg.get(y)),l=n.length,u=c.map(()=>Ri(l)),d=c.map(()=>Ri(l));c.forEach((y,S)=>{for(let I of EH(y.definitions)){if(!I.partial)for(let x of o.get(I.point.symbolKey)??[])Nc(d[S],x);Nc(u[S],r.get(I.point.id))}});let m=c.map(()=>Ri(l)),p=c.map(()=>Ri(l)),f=new Uint8Array(c.length).fill(1),g=c.map((y,S)=>S),h=0;for(;h<g.length;){let y=g[h];h+=1,f[y]=0;let S=c[y],I=m[y];I.fill(0),CH(S,a,p,I),xH(S,I,p[y],u[y],d[y])&&OC(S.successors,a,f,g)}c.forEach((y,S)=>{let I=m[S];for(let x of y.uses){let E=y.definitions.filter(v=>v.point.symbolKey===x.point.symbolKey&&v.point.start<x.point.start&&!v.rhsUseIds.includes(x.point.id)).sort((v,C)=>C.point.start-v.point.start)[0],b=E?[E]:(o.get(x.point.symbolKey??"")??[]).filter(v=>AC(I,v)).map(v=>n[v]);for(let v of b)wi(e,"reaching-definition",v.point.id,x.point.id,"exact","A CFG path reaches this use without an intervening definition.")}for(let x of y.definitions)for(let E of x.rhsUseIds)wi(e,"value-source",E,x.point.id,"exact","This right-hand-side use supplies the new definition.")})}function CH(e,t,n,r){for(let i of e.predecessors){let o=n[t.get(i)];for(let s=0;s<o.length;s+=1)r[s]|=o[s]}}function xH(e,t,n,r,i){let o=!1;for(let s=0;s<n.length;s+=1){let a=(e.invalidatesAllDefinitions?r[s]:t[s]&~i[s]|r[s])>>>0;a!==n[s]&&(n[s]=a,o=!0)}return o}function OC(e,t,n,r){for(let i of e){let o=t.get(i);n[o]===0&&(n[o]=1,r.push(o))}}function RH(e){let t=new Map;for(let n of e){if(!n.point.symbolKey)continue;let r=t.get(n.point.symbolKey)??[];r.push(n),t.set(n.point.symbolKey,r)}return t}function EH(e){let t=new Map;for(let n of e)n.point.symbolKey&&t.set(n.point.symbolKey,n);return[...t.values()]}function IH(e,t){let{order:n,sets:r}=wH(t),i=new Map;n.forEach((s,a)=>i.set(s,a));let o=i.get(t.exitId);for(let s of t.cfg.values()){if(s.kind!=="predicate"||!s.displayPoint)continue;for(let c of s.uses)wi(e,"value-source",c.point.id,s.displayPoint.id,"exact","The predicate evaluates this variable occurrence to choose its control-flow successor.");if(s.successors.size<2)continue;let a=r[i.get(s.id)];for(let c of s.successors)SH(r[i.get(c)],l=>{if(l===o||AC(a,l))return;let u=t.cfg.get(n[l]),d=[...u.definitions.map(m=>m.point),...u.uses.map(m=>m.point),...u.displayPoint?[u.displayPoint]:[]];for(let m of kH(d))wi(e,"control-dependence",s.displayPoint.id,m.id,"exact","The target postdominates a branch successor but does not postdominate the predicate.")})}}function wH(e){let t=_C(e.cfg,e.exitId,d=>d.predecessors),n=new Map;t.forEach((d,m)=>n.set(d,m));let r=t.length,i=n.get(e.exitId),o=t.map((d,m)=>{let p=Ri(r);if(m===i)Nc(p,m);else{p.fill(4294967295);let f=p.length*32-r;f>0&&(p[p.length-1]=4294967295>>>f)}return p}),s=t.map(d=>e.cfg.get(d)),a=new Uint8Array(r).fill(1),c=s.map((d,m)=>m),l=0,u=Ri(r);for(;l<c.length;){let d=c[l];if(l+=1,a[d]=0,d===i)continue;let m=s[d];m.successors.size===0||(u.fill(4294967295),PH(m,n,o,u),Nc(u,d),!TH(o[d],u))||OC(m.predecessors,n,a,c)}return{order:t,sets:o}}function PH(e,t,n,r){for(let i of e.successors){let o=n[t.get(i)];for(let s=0;s<r.length;s+=1)r[s]&=o[s]}}function TH(e,t){let n=!1;for(let r=0;r<e.length;r+=1)t[r]!==e[r]&&(e[r]=t[r],n=!0);return n}function LH(e,t){let n=new Map(t.map(i=>[i.id,i.parentId])),r=MH(t);for(let i of t)for(let o of[...i.cfg.values()].flatMap(s=>s.uses))o.point.symbolKey&&DH(e,o,r.get(o.point.symbolKey)??[],n);[...e.edges.values()].some(i=>i.kind==="closure-capture")&&e.unsupported.add("Closure capture identity is known, but invocation order and intervening writes remain candidate flow."),[...e.edges.values()].some(i=>i.kind==="field-definition-to-use")&&e.unsupported.add("Cross-callable field flow lacks receiver points-to and invocation-order analysis.")}function MH(e){let t=e.flatMap(r=>[...r.cfg.values()].flatMap(i=>i.definitions.map(o=>o.point))),n=new Map;for(let r of t){if(!r.symbolKey)continue;let i=n.get(r.symbolKey)??[];i.push(r),n.set(r.symbolKey,i)}return n}function DH(e,t,n,r){for(let i of n)EC(i.callableId,t.point.callableId,r)||EC(t.point.callableId,i.callableId,r)?wi(e,"closure-capture",i.id,t.point.id,"candidate","Compiler identity proves a shared lexical binding, but closure invocation and intervening writes remain unresolved."):t.property&&i.callableId!==t.point.callableId&&wi(e,"field-definition-to-use",i.id,t.point.id,"candidate","Compiler identity matches the field; cross-callable receiver and execution order remain unresolved.")}function EC(e,t,n){for(let r=n.get(t)??null;r;r=n.get(r)??null)if(r===e)return!0;return!1}function wi(e,t,n,r,i,o){let s=`local-flow-edge:${t}:${encodeURIComponent(n)}:${encodeURIComponent(r)}`;e.edges.set(s,{id:s,kind:t,fromPointId:n,toPointId:r,strength:i,reason:o})}function BC(e,t){return t>=e.SyntaxKind.FirstAssignment&&t<=e.SyntaxKind.LastAssignment}function FH(e,t){let n=t.getText(e.sourceFile).replace(/\s+/gu," ").trim();return n.length>80?`${n.slice(0,77)}...`:n||e.ts.SyntaxKind[t.kind]||"statement"}function $C(e){return[...new Map(e.map(t=>[t.point.id,t])).values()]}function kH(e){return[...new Map(e.map(t=>[t.id,t])).values()]}function NH(e,t){return e.start-t.start||e.kind.localeCompare(t.kind)||e.id.localeCompare(t.id)}function Fc(e){return{points:[],edges:[],coverage:{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:[e]}}}function AH(e,t,n){for(let r of t.node.parameters){let i=Cm(e,r.name);if(i.length===0&&e.ts.isIdentifier(r.name)){e.unsupported.add("A parameter binding could not be resolved to a compiler symbol.");continue}for(let o of i)n.definitions.push({point:is(e,o.node,"parameter-definition",o.symbolKey,o.name,t.id),rhsUseIds:[],partial:!1})}}function _H(e,t){return e.isImportSpecifier(t)||e.isImportClause(t)||e.isNamespaceImport(t)}function OH(e,t){return e.isParenthesizedExpression(t)||e.isAsExpression(t)||e.isTypeAssertionExpression(t)||e.isNonNullExpression(t)}function BH(e,t,n,r,i){let o=e.ts;return o.isWhileStatement(n)||o.isDoStatement(n)?B1(e,t,n,r,i):o.isForStatement(n)?$1(e,t,n,r,i):o.isForInStatement(n)||o.isForOfStatement(n)?j1(e,t,n,r,i):null}var $H=zf("typescript-local-flow",{clearGroups:["whole-project","source-file","semantic-provider"]});function Er(e,t,n,r,i={}){if(t=t.replace(/\\/g,"/"),!xt(t))return null;let o=`${t}\0${n}\0${r}\0${i.startColumn??""}\0${i.endColumn??""}`;return $H.get(e,o,()=>{let s=H(e,t);return s?IC(s,jC(e.config.projectRoot,t),{startLine:n,endLine:r,...i}):{points:[],edges:[],coverage:{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:[`Current source is unavailable for ${t}.`]}}})}function HC(e,t){let n=os(),r=n?H(e,t):null;return!n||!r?null:bm(n,r,jC(e.config.projectRoot,t))}function jH(e,t=new Map){let n=new Map,r=new Map,i=[];for(let o of e.transfers){if(!e.caller)continue;let s=Ac(e.caller,o.callerPosition),a=Ac(e.callee,o.calleePosition);ss(n,s),ss(n,a),Rm(r,e.caller,s),Rm(r,e.callee,a);let c=Le("edge","data-transfer",Ti(e),o.proof.file,String(o.proof.startLine),String(o.callerPosition),String(o.calleePosition));r.set(c,{id:c,kind:"data-transfer",fromNodeId:s.id,toNodeId:a.id,directed:!0,disposition:"folded",semantics:[{family:"data",subtype:"argument-to-parameter",attributes:{argumentText:o.argumentText,callerPosition:o.callerPosition,calleePosition:o.calleePosition}}],evidence:[{method:"compiler-callsite-direct-parameter-transfer",strength:"exact",identity:`${e.caller.symbol}:${o.callerPosition} -> ${e.callee.symbol}:${o.calleePosition}`,location:{file:o.proof.file,line:o.proof.startLine,endLine:o.proof.endLine}}]})}return e.unknown.forEach((o,s)=>{let a=!["callee-parameter-unavailable","argument-without-parameter","callee-parameter-transform"].includes(o.reason),c=a?Ac(e.callee,o.calleePosition):{...UC(e,o.calleePosition,o.argumentText),id:Le("argument-mapping",Ti(e),String(o.calleePosition)),kind:"unresolved-argument-mapping",label:`Unresolved argument ${o.calleePosition+1}: ${o.reason}`,attributes:{calleeSymbol:e.callee.symbol,argumentPosition:o.calleePosition,reason:o.reason}};ss(n,c),a&&Rm(r,e.callee,c);let l=t.get(o.calleePosition);if(a&&l&&eU(l)){ZH(r,n,e,o.calleePosition,o.argumentText,l);return}let u=UC(e,o.calleePosition,o.argumentText);ss(n,u),KC(r,e,u);let d=Le("edge","data-transfer-unsupported",Ti(e),o.proof.file,String(o.proof.startLine),String(o.calleePosition),String(s));r.set(d,{id:d,kind:"data-transfer",fromNodeId:u.id,toNodeId:c.id,directed:!0,disposition:"unsupported",semantics:[{family:"data",subtype:"argument-to-parameter",attributes:{argumentText:o.argumentText,calleePosition:o.calleePosition}}],evidence:[{method:"compiler-callsite-argument-expression",strength:"exact",identity:o.argumentText,location:{file:o.proof.file,line:o.proof.startLine,endLine:o.proof.endLine}}]}),i.push({id:Le("frontier","data-transfer",d),kind:"data-transfer",direction:"unresolved",fromNodeIds:[u.id,...e.caller?[Li(e.caller.symbol)]:[]],edgeIds:[d],memberNodeIds:[c.id,Li(e.callee.symbol)],memberCount:2,disposition:"unsupported",reason:l?.derivation.rule??o.reason,expansion:null})}),{nodes:[...n.values()],edges:[...r.values()],frontiers:i,blindSpots:[]}}function qC(e,t,n=[]){let r=zC(),i=new Map,o=new Set;for(let s of t)UH(e,s,i,o,r);for(let s of n)zH(e,s,r);return r.blindSpots=[...new Set(r.blindSpots)].sort(),r}function HH(e,t,n,r){if(t.kind!=="call"||!t.fromSymbol||!t.toSymbol||t.line===null)return[];let i=XH(n,e,t.toFile,t.toSymbol);if(!i)return[];let o=Xg(e,i),s=o.sites.filter(a=>a.file===t.fromFile&&a.startLine<=t.line&&a.endLine>=t.line&&a.caller?.symbol===t.fromSymbol);if(s.length===0){let a=o.unresolved.find(c=>c.file===t.fromFile&&c.line===t.line);return a&&r.blindSpots.push(`Parameter flow unresolved at ${t.fromFile}:${t.line+1}: ${a.reason}.`),[]}return s.map(a=>({site:a,callee:i}))}function UH(e,t,n,r,i){let o=HH(e,t,n,i);for(let{site:s,callee:a}of o){let c=`${s.file}\0${s.callNode.startIndex}\0${s.callNode.endIndex}\0${a.symbol}`;if(r.has(c))continue;r.add(c);let l=Qg(e,s),u=qH(e,s,l);GC(i,jH(l,u)),l.caller&&JH(s.callNode)&&YH(i,l,s.callNode)}}function qH(e,t,n){let r=_(e,t.file)?.rootNode,i=new Map;if(r)for(let o of n.unknown){let s=Yg({db:e,file:t.file,root:r},t.arguments[o.calleePosition]);s&&i.set(o.calleePosition,s)}return i}function zH(e,t,n){if(!t.location||!["source-construct","symbol"].includes(t.kind))return;let r=t.location.endLine??t.location.line,i=Er(e,t.location.file,t.location.line,r,t.location);if(i){GC(n,GH(t,i.points,i.edges));for(let o of i.coverage.unsupported)n.blindSpots.push(`TypeScript local flow is partial for ${t.location.file}:${t.location.line+1}-${r+1}: ${o} Recover with: scip-query inspect --at '${t.location.file}:${t.location.line+1}-${r+1}' --view behavior.`)}}function GH(e,t,n){let r=zC(),i=new Map,o=new Map,s=new Map,a=e.location.file;for(let c of t){let l=KH(e,a,c);s.set(c.id,l.id),i.set(l.id,l),WH(o,e,l)}for(let c of n){let l=s.get(c.fromPointId),u=s.get(c.toPointId);if(!l||!u)continue;let d=VH(c),m=Le("edge","typescript-local-flow",a,c.id);o.set(m,{id:m,kind:c.kind==="control-dependence"?"control-dependence":"data-transfer",fromNodeId:l,toNodeId:u,directed:!0,disposition:"folded",semantics:[d],evidence:[{method:"typescript-compiler-cfg-reaching-definitions",strength:c.strength,identity:c.reason,location:i.get(l)?.location??e.location}]})}return r.nodes=[...i.values()],r.edges=[...o.values()],r}function KH(e,t,n){return{id:Le("local-flow-point",t,String(n.start),String(n.end),n.kind,n.symbolKey??n.name),kind:n.kind==="parameter-definition"||n.kind==="definition"?"local-definition":n.kind==="use"?"local-use":n.kind==="predicate"?"control-predicate":"local-statement",label:n.name,disposition:"folded",location:{file:t,line:n.line,endLine:n.line},anchorIds:[],attributes:{ownerNodeId:e.id,pointKind:n.kind,callableId:n.callableId,symbolKey:n.symbolKey,column:n.column}}}function WH(e,t,n){let r=Le("edge","local-flow-owner",t.id,n.id);e.has(r)||e.set(r,{id:r,kind:"local-flow-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains"}],evidence:[{method:"typescript-compiler-local-flow-owner",strength:"exact",identity:t.id,location:n.location}]})}function VH(e){switch(e.kind){case"reaching-definition":return{family:"data",subtype:"definition-to-use"};case"value-source":return{family:"data",subtype:"value-to-definition"};case"closure-capture":return{family:"data",subtype:"closure-capture"};case"field-definition-to-use":return{family:"data",subtype:"field-definition-to-use"};case"control-dependence":return{family:"control",subtype:"control-dependence"}}}function JH(e){let t=e;for(;t.parent&&["await_expression","yield_expression","parenthesized_expression","as_expression","type_assertion"].includes(t.parent.type);)t=t.parent;return t.parent!==null&&t.parent.type!=="expression_statement"}function YH(e,t,n){if(!t.caller)return;let r={id:Le("call-result",t.call.file,String(n.startIndex),String(n.endIndex),t.callee.symbol),kind:"call-result",label:`result of ${t.callee.leaf}`,disposition:"folded",location:{file:t.call.file,line:t.call.startLine,endLine:t.call.endLine},anchorIds:[],attributes:{calleeSymbol:t.callee.symbol,callerSymbol:t.caller.symbol}},i=Le("edge","return-to-call-result",t.callee.symbol,r.id),o=Le("edge","call-result-owner",t.caller.symbol,r.id);e.nodes.push(r),e.edges.push({id:i,kind:"data-transfer",fromNodeId:Li(t.callee.symbol),toNodeId:r.id,directed:!0,disposition:"folded",semantics:[{family:"data",subtype:"return-to-call-result"}],evidence:[{method:"compiler-callsite-used-result",strength:"exact",identity:`${t.callee.symbol} -> ${t.caller.symbol}`,location:r.location}]},{id:o,kind:"call-result-owner",fromNodeId:Li(t.caller.symbol),toNodeId:r.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains-call-result"}],evidence:[{method:"compiler-call-result-owner",strength:"exact",identity:t.caller.symbol,location:r.location}]})}function zC(){return{nodes:[],edges:[],frontiers:[],blindSpots:[]}}function GC(e,t){xm(e.nodes,t.nodes),xm(e.edges,t.edges),xm(e.frontiers,t.frontiers),e.blindSpots.push(...t.blindSpots)}function xm(e,t){let n=new Set(e.map(r=>r.id));for(let r of t)n.has(r.id)||(n.add(r.id),e.push(r))}function XH(e,t,n,r){let i=`${n}\0${r}`,o=e.get(i);if(o!==void 0)return o;let s=D(t,n).find(a=>a.symbol===r)??null;return e.set(i,s),s}function Ac(e,t){return{id:rU(e.symbol,t),kind:"parameter",label:`${e.leaf} parameter ${t}`,disposition:"folded",location:{file:e.relativePath,line:e.startLine,endLine:e.endLine},anchorIds:[],attributes:{ownerSymbol:e.symbol,position:t}}}function UC(e,t,n){return{id:Le("argument-expression",Ti(e),e.call.file,String(e.call.startLine),String(e.call.endLine),String(t)),kind:"argument-expression",label:n,disposition:"unsupported",location:{file:e.call.file,line:e.call.startLine,endLine:e.call.endLine},anchorIds:[],attributes:{calleeSymbol:e.callee.symbol,position:t}}}function QH(e,t,n){return{id:Le("static-value",Ti(e),e.call.file,String(e.call.startLine),String(e.call.endLine),String(t)),kind:"static-value",label:n.value,disposition:"folded",location:{file:e.call.file,line:e.call.startLine,endLine:e.call.endLine},anchorIds:[],attributes:{value:n.value,precision:n.precision,evidence:n.evidence,termKind:n.term.kind,derivationRule:n.derivation.rule}}}function ZH(e,t,n,r,i,o){let s=QH(n,r,o),a=Ac(n.callee,r);ss(t,s),KC(e,n,s);let c=Le("edge","static-value-transfer",Ti(n),n.call.file,String(n.call.startLine),String(r));e.set(c,{id:c,kind:"data-transfer",fromNodeId:s.id,toNodeId:a.id,directed:!0,disposition:"folded",semantics:[{family:"data",subtype:tU(o),attributes:{argumentText:i,calleePosition:r,value:o.value,precision:o.precision,derivationRule:o.derivation.rule}}],evidence:nU(o,n)})}function eU(e){return e.derivation.kind!=="heuristic"&&e.precision!=="symbolic"&&e.precision!=="unknown"}function tU(e){return e.derivation.rule==="bounded-call-return"?"return-to-parameter":e.derivation.rule==="member-constant"||e.term.kind==="property"?"property-to-parameter":"constant-to-parameter"}function nU(e,t){return(e.derivation.sourceSpans.length>0?e.derivation.sourceSpans:[t.call]).map(r=>({method:`static-value:${e.derivation.rule}`,strength:e.derivation.kind==="direct"?"exact":"derived",identity:e.derivation.inputFactIds.join(",")||e.value,location:{file:r.file,line:r.startLine,endLine:r.endLine}}))}function ss(e,t){e.has(t.id)||e.set(t.id,t)}function KC(e,t,n){if(!t.caller)return;let r=Le("edge","argument-owner",t.caller.symbol,n.id);e.set(r,{id:r,kind:"argument-owner",fromNodeId:Li(t.caller.symbol),toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains"}],evidence:[{method:"compiler-callsite-argument-owner",strength:"exact",identity:t.caller.symbol,location:n.location}]})}function Rm(e,t,n){let r=Le("edge","parameter-owner",t.symbol,n.id);e.has(r)||e.set(r,{id:r,kind:"parameter-owner",fromNodeId:Li(t.symbol),toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains"}],evidence:[{method:"compiler-parameter-owner",strength:"exact",identity:t.symbol,location:{file:t.relativePath,line:t.startLine,endLine:t.endLine}}]})}function rU(e,t){return Le("parameter",e,String(t))}function Li(e){return Le("symbol",e)}function Ti(e){return Le(e.callee.symbol,e.call.file,String(e.call.startLine),String(e.call.startColumn??""),String(e.call.endLine),String(e.call.endColumn??""))}function Le(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function WC(e,t){let n={nodes:[],edges:[],frontiers:[],blindSpots:[]};for(let r of t)for(let{call:i,external:o,declarations:s,implementationReason:a}of iU(e,r))aU(n,r,i,o,s,a);return n}function iU(e,t){let n=t.location;if(!n||!["symbol","source-construct","file"].includes(t.kind))return[];let r=z(e,n.file);if(!r)return[];let i=wn(e,n.file,n.line,t.kind==="file"?Number.MAX_SAFE_INTEGER:n.endLine??n.line),o=po(e,n.file);return r.callSites.filter(s=>oU(s,t)&&!i.targets.some(a=>a.implementationStatus!=="unresolved"&&In(a.sourceRange,s.targetRange))).map(s=>({call:s,external:sU(s,o)&&!kg(e,n.file,s),declarations:(i.declarations??[]).filter(a=>In(a.sourceRange,s.targetRange)).map(a=>a.definition.symbol),implementationReason:i.targets.find(a=>In(a.sourceRange,s.targetRange))?.implementationReason}))}function oU(e,t){if(!e.targetRange)return!1;if(t.kind==="file")return e.owner===null;let n=t.location;return e.owner?.startLine===n.line&&e.owner.endLine===n.endLine&&e.owner.startColumn===n.startColumn&&e.owner.endColumn===n.endColumn}function sU(e,t){return!t?.locals?.some(r=>In({startLine:r.line,startColumn:r.startChar,endLine:r.endLine,endColumn:r.endChar},e.targetRange))&&!!t?.externalRanges?.some(r=>In(r,e.targetRange))}function aU(e,t,n,r,i,o){let s=t.location;if(!n.targetRange)return;let a=o??(i.length?"observed-or-possible-write; execution-order-not-established":"missing-or-indirect-binding"),c=i.length?`Invocation ${n.calleeText} has no established repository implementation target at ${s.file}:${n.targetRange.startLine+1}:${n.targetRange.startColumn+1}. Compiler declaration reference for ${n.calleeText}: ${i.join(", ")}. Runtime implementation remains unresolved (${a}); the declaration reference is preserved and does not establish executable reachability.`:r?`Compiler reference for ${n.calleeText} has no indexed repository body; external behavior is unavailable.`:`Invocation ${n.calleeText} has no established repository implementation target; indirect, mutated, or missing bindings cannot establish reachability.`,l=`execution-unresolved:${t.id}:${n.targetRange.startLine}:${n.targetRange.startColumn}:${n.targetRange.endColumn}`,u=`edge:${l}`,d={file:s.file,line:n.targetRange.startLine,endLine:n.targetRange.endLine,startColumn:n.targetRange.startColumn,endColumn:n.targetRange.endColumn};e.nodes.push({id:l,kind:"unresolved-invocation",label:n.calleeText??n.calleeLeaf,disposition:"unsupported",location:d,anchorIds:[],attributes:{ownerNodeId:t.id,targetResolution:r&&!i.length?"external":"unresolved",referencedDeclaration:i.length===1?i[0]:null,declarationCount:i.length,implementationReason:a}}),e.edges.push({id:u,kind:"control-dependence",fromNodeId:t.id,toNodeId:l,directed:!0,disposition:"unsupported",semantics:[{family:"control",subtype:"unresolved-call-target",attributes:{referencedDeclaration:i.length===1?i[0]:null,declarationCount:i.length,implementationReason:a}}],evidence:[{method:"parser-invocation-without-repository-target",strength:"exact",identity:c,location:d}]}),e.frontiers.push({id:`frontier:${l}`,kind:"control-dependence",direction:"unresolved",fromNodeIds:[t.id],edgeIds:[u],memberNodeIds:[l],memberCount:1,disposition:"unsupported",reason:c,expansion:null})}function VC(e,t){let n=new Map,r=new Map,i=new Map,o=new Set;for(let s of t){if(!s.location||!["source-construct","symbol"].includes(s.kind))continue;let a=s.location.endLine??s.location.line,c=Ch(e,s.location.file,s.location.line,a,s.location);if(!c){o.add(`Control dependence unavailable for ${s.location.file}:${s.location.line+1}-${a+1}: no supported syntax tree or covering construct.`);continue}for(let l of c.facts){let u=Em(s,l.controller),d=Em(s,l.outcome);n.set(u.id,u),n.set(d.id,d),cU(r,s,u);let m=Ir("edge","control-dependence",u.id,d.id,l.subtype);r.set(m,{id:m,kind:"control-dependence",fromNodeId:u.id,toNodeId:d.id,directed:!0,disposition:"folded",semantics:[{family:"control",subtype:l.subtype,attributes:{...l.attributes}}],evidence:[{method:"parser-control-dependence",strength:"exact",identity:`${s.location.file}:${l.controller.startLine+1}-${l.outcome.startLine+1}`,location:{file:s.location.file,line:l.controller.startLine,endLine:l.controller.endLine}}]})}lU(s,c.terminals,n,r);for(let l of c.unsupported){let u=Ir("control-unsupported",s.location.file,String(l.startLine),String(l.endLine),l.reason);n.set(u,{id:u,kind:"control-unsupported",label:l.reason,disposition:"unsupported",location:{file:s.location.file,line:l.startLine,endLine:l.endLine},anchorIds:[],attributes:{ownerNodeId:s.id}});let d=Ir("edge","control-unsupported",s.id,u);r.set(d,{id:d,kind:"control-dependence",fromNodeId:s.id,toNodeId:u,directed:!0,disposition:"unsupported",semantics:[{family:"control",subtype:"unresolved-control-construct"}],evidence:[{method:"parser-control-construct",strength:"exact",identity:l.reason,location:{file:s.location.file,line:l.startLine,endLine:l.endLine}}]});let m=Ir("frontier","control-dependence",u);i.set(m,{id:m,kind:"control-dependence",direction:"unresolved",fromNodeIds:[s.id],edgeIds:[d],memberNodeIds:[u],memberCount:1,disposition:"unsupported",reason:l.reason,expansion:null})}}return{nodes:[...n.values()],edges:[...r.values()],frontiers:[...i.values()],blindSpots:[...o].sort()}}function Em(e,t){let n=e.location.file;return{id:Ir(`control-${t.kind}`,n,String(t.startLine),String(t.endLine),t.label,e.id,String(t.startColumn??""),String(t.endColumn??"")),kind:`control-${t.kind}`,label:t.label,disposition:"folded",location:{file:n,line:t.startLine,endLine:t.endLine,startColumn:t.startColumn,endColumn:t.endColumn},anchorIds:[],attributes:{ownerNodeId:e.id,constructKind:t.kind,implicit:t.implicit}}}function cU(e,t,n){let r=Ir("edge","control-owner",t.id,n.id);e.has(r)||e.set(r,{id:r,kind:"control-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:"contains-control"}],evidence:[{method:"parser-control-owner",strength:"exact",identity:t.id,location:t.location}]})}function Ir(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function lU(e,t,n,r){for(let i of t){let o=Em(e,i);n.set(o.id,o);let s=i.label.startsWith("throw")||i.label.startsWith("raise")?"throw":"return",a=Ir("edge","control-terminal",e.id,o.id,s);r.set(a,{id:a,kind:"control-terminal",fromNodeId:e.id,toNodeId:o.id,directed:!0,disposition:"folded",semantics:[{family:"control",subtype:s==="throw"?"throws":"returns"}],evidence:[{method:"parser-terminal-statement",strength:"exact",identity:i.label,location:{file:e.location.file,line:i.startLine,endLine:i.endLine}}]})}}var cs=new Set(["block","body","compound_statement","declaration_list","statement_block"]),uU=new Set(["assignment","assignment_expression","augmented_assignment_expression"]),Im=new Set(["update_expression"]),JC=new Set(["array_access","element_access_expression","subscript_expression"]),YC=new Set(["attribute","field_access","field_expression","member_access_expression","member_expression","selector_expression"]),dU=new Set(["false","null","null_literal","number","number_literal","string","string_literal","template_string","true"]),mU=new Set(["call_expression","method_invocation","object_creation_expression"]),pU=new Set(["comment","else_clause","formal_parameters","parameters","type_parameters"]);function XC(e,t,n,r,i={}){let o=_(e,t);if(!o)return null;let s=nr(o.rootNode,n,r,we,i);if(!s)return null;let a=[],c=[],l=[],u=ga(t,o.rootNode);return ls(s,d=>{if(uU.has(d.type)||Im.has(d.type)||QC(d)){let m=fU(d,u);m?a.push(m):l.push({family:"state",startLine:d.startPosition.row,endLine:d.endPosition.row,reason:`Mutation target ${Yt(d.text)} could not be resolved to an exact source resource.`})}}),ls(s,d=>{if(!cs.has(d.type))return;let m=CU(d);for(let p=0;p<m.length-1;p+=1)c.push({from:as(m[p]),to:as(m[p+1]),subtype:"lexical-successor",synchronizationScope:null,attributes:{sameScope:!0,executionConditional:!0}});for(let p=0;p<m.length;p+=1){let f=m[p],g=EU(f).filter(h=>h.type==="await_expression");for(let h of g){let y=Mi("event",`await ${Yt(h.text.replace(/^await\s+/u,""))}`,h);c.push({from:as(f),to:y,subtype:"awaits-completion",synchronizationScope:null,attributes:{completionRequired:!0,executionConditional:!0}});let S=m[p+1];S&&SU(h,f)&&c.push({from:y,to:as(S),subtype:"await-completion-before",synchronizationScope:null,attributes:{continuationOnly:!0}})}}}),ls(s,d=>{if(d.type!=="synchronized_statement")return;let m=d.childForFieldName("object")??d.childForFieldName("condition")??d.namedChildren.find(y=>!cs.has(y.type)),p=d.childForFieldName("body")??d.namedChildren.find(y=>cs.has(y.type));if(!m||!p){l.push({family:"temporal",startLine:d.startPosition.row,endLine:d.endPosition.row,reason:"Synchronized scope has no structurally resolved monitor or body."});return}let f=Yt(m.text).replace(/^\(|\)$/gu,""),g=Mi("lock",f,m),h=RU(p).filter(y=>y.parent!==null&&ZC(y));for(let y of xU(h))c.push({from:g,to:as(y),subtype:"inside-lock-scope",synchronizationScope:f,attributes:{syntaxNative:!0}})}),{mutations:a,temporal:c,unsupported:l}}function fU(e,t){let n=QC(e),r=gU(e,n);if(!r)return null;let i=yU(r);if(!i)return null;let o=hU(e,r,n),s=n||Im.has(e.type)?null:e.childForFieldName("right");return{event:Mi("event",Yt(e.text),e),resource:{...Mi("resource",i.name,r),...t.resource(r)},operation:o,durabilityClass:"in-memory",recordIdentity:i.recordIdentity,value:s?Mi("value",Yt(s.text),s):null,dataSubtype:s?bU(s,t):null}}function gU(e,t){return e.childForFieldName("left")??e.childForFieldName("argument")??(t?e.namedChildren.at(-1)??null:e.namedChildren[0]??null)}function hU(e,t,n){return n?"delete":Im.has(e.type)||!vU(e,t).startsWith("=")?"update":"assign"}function yU(e){return JC.has(e.type)?IU(e):YC.has(e.type)?{name:Yt(e.text),recordIdentity:null}:/^(?:identifier|property_identifier|field_identifier)$/u.test(e.type)?{name:Yt(e.text),recordIdentity:null}:null}function bU(e,t){return e.type==="template_string"&&e.namedChildren.some(n=>n.type==="template_substitution")?"expression-to-state":dU.has(e.type)||/(?:integer|float|decimal|boolean|character)_literal$/u.test(e.type)?"constant-to-state":mU.has(e.type)?"return-to-state":YC.has(e.type)||JC.has(e.type)?"property-to-state":/identifier$/u.test(e.type)?t.isCaptured(e)?"captured-value-to-state":"value-to-state":"expression-to-state"}function SU(e,t){if(!["expression_statement","lexical_declaration","variable_declaration","local_variable_declaration"].includes(t.type))return!1;for(let n=e.parent;n&&(n.startIndex!==t.startIndex||n.endIndex!==t.endIndex||n.type!==t.type);n=n.parent)if(cs.has(n.type)||/(?:statement|clause)$/u.test(n.type))return!1;return!0}function vU(e,t){let n=e.childForFieldName("right"),r=Math.max(0,t.endIndex-e.startIndex),i=n?Math.max(r,n.startIndex-e.startIndex):e.text.length;return e.text.slice(r,i).trim()}function QC(e){return(e.type==="delete_expression"||e.type==="unary_expression")&&/^delete\b/u.test(e.text.trim())}function CU(e){return e.namedChildren.filter(t=>ZC(t))}function ZC(e){return pU.has(e.type)||cs.has(e.type)?!1:/(?:statement|declaration)$/u.test(e.type)||e.type==="expression_statement"||e.type==="local_variable_declaration"}function xU(e){let t=new Set(e);return e.filter(n=>{let r=n.parent;for(;r;){if(t.has(r))return!1;r=r.parent}return!0})}function as(e){return Mi("event",Yt(e.text),e)}function Mi(e,t,n){return{kind:e,label:t,startLine:n.startPosition.row,endLine:n.endPosition.row,startColumn:n.startPosition.column,endColumn:n.endPosition.column}}function RU(e){let t=[];return ls(e,n=>t.push(n)),t}function EU(e){let t=[],n=r=>{t.push(r);for(let i of r.namedChildren)i!==e&&we.has(i.type)||n(i)};return n(e),t}function ls(e,t){t(e);for(let n of e.namedChildren)we.has(n.type)||ls(n,t)}function Yt(e){return e.trim().replace(/\s+/gu," ")}function IU(e){let t=e.childForFieldName("object")??e.childForFieldName("array")??e.namedChildren[0]??null,n=e.childForFieldName("index")??e.childForFieldName("subscript")??e.namedChildren[1]??null;return!t||!n?null:{name:`${Yt(t.text)}[]`,recordIdentity:Yt(n.text)}}function nx(e,t,n=[]){let r=new Map,i=new Map,o=new Map,s=new Set,a=(m,p)=>{let f=Oc(m,p.event),g=DU(m,p.resource,p.durabilityClass);if(r.set(f.id,f),r.set(g.id,g),Bc(i,m,f,"contains-state-effect"),$c(i,{kind:"state-resource",from:f,to:g,semantics:[{family:"state",subtype:p.operation==="delete"?"deletes-resource":"writes-resource",attributes:{operation:p.operation,durabilityClass:p.durabilityClass,resource:p.resource.label,recordIdentity:p.recordIdentity,transactionMembership:"unknown"}}],method:"parser-state-mutation",identity:p.event.label}),p.value&&p.dataSubtype){let h=Oc(m,p.value);r.set(h.id,h),$c(i,{kind:"data-to-state",from:h,to:g,semantics:[{family:"data",subtype:p.dataSubtype,attributes:{operation:p.operation,resource:p.resource.label,recordIdentity:p.recordIdentity,value:p.value.label}}],method:"parser-assignment-value",identity:`${p.value.label} -> ${p.resource.label}`})}},c=(m,p)=>{let f=Oc(m,p.from),g=Oc(m,p.to);r.set(f.id,f),r.set(g.id,g),Bc(i,m,f,p.from.kind==="lock"?"contains-lock-scope":"contains-event"),Bc(i,m,g,"contains-event"),$c(i,{kind:"temporal-order",from:f,to:g,semantics:[{family:"temporal",subtype:p.subtype,context:p.synchronizationScope?{synchronizationScope:p.synchronizationScope}:void 0,attributes:{...p.attributes}}],method:p.subtype==="inside-lock-scope"?"parser-synchronized-scope":"parser-program-order",identity:`${p.from.label} -> ${p.to.label}`})},l=(m,p,f)=>{let g=yn(`${p.family}-unsupported`,f.file,String(p.startLine),String(p.endLine),p.reason);r.set(g,{id:g,kind:`${p.family}-unsupported`,label:p.reason,disposition:"unsupported",location:{file:f.file,line:p.startLine,endLine:p.endLine},anchorIds:[],attributes:{ownerNodeId:m.id}});let h=yn("edge",`${p.family}-unsupported`,m.id,g);i.set(h,{id:h,kind:`${p.family}-unsupported`,fromNodeId:m.id,toNodeId:g,directed:!0,disposition:"unsupported",semantics:[{family:p.family,subtype:`unresolved-${p.family}-construct`}],evidence:[{method:`parser-${p.family}-construct`,strength:"exact",identity:p.reason,location:{file:f.file,line:p.startLine,endLine:p.endLine}}]});let y=yn("frontier",p.family,g);o.set(y,{id:y,kind:p.family,direction:"unresolved",fromNodeIds:[m.id],edgeIds:[h],memberNodeIds:[g],memberCount:1,disposition:"unsupported",reason:p.reason,expansion:null})},u=()=>{for(let m of t.filter(p=>p.kind==="runtime-boundary-participant")){let p=_c(m,"protocol"),f=_c(m,"action"),g=_c(m,"address")??m.label;!p||!f||!tx(p,f)||ex(r,i,m,{observationId:m.id,action:f,strength:"exact",file:m.location?.file??"",line:m.location?.line??0,address:g,protocol:p,role:_c(m,"role")??void 0,resolution:"locally-linked"})}},d=()=>{for(let m of n){if(!m.protocol||!tx(m.protocol,m.action))continue;let p=LU(t,m.file,m.line,m.ownerShortName??null);if(!p){s.add(`State observation ${m.observationId} at ${m.file}:${m.line+1} has no materialized owner node.`);continue}ex(r,i,p,m)}};for(let m of t){if(!m.location||!["source-construct","symbol"].includes(m.kind))continue;let p=m.location.endLine??m.location.line,f=XC(e,m.location.file,m.location.line,p,m.location);if(!f){s.add(`State and temporal analysis unavailable for ${m.location.file}:${m.location.line+1}-${p+1}: no supported syntax tree or covering construct.`);continue}for(let g of f.mutations)a(m,g);for(let g of f.temporal)c(m,g);for(let g of f.unsupported)l(m,g,m.location)}return u(),d(),{nodes:[...r.values()],edges:[...i.values()],frontiers:[...o.values()],blindSpots:[...s].sort()}}function ex(e,t,n,r){let i=PU(r),s={id:yn("runtime-state-event",r.observationId),kind:"runtime-state-event",label:`${r.action} ${i}`,disposition:"folded",location:{file:r.file,line:r.line},anchorIds:[],attributes:{action:r.action,protocol:r.protocol??null,modality:r.modality??null,resolution:r.resolution??null}},a=r.protocol==="database"?"external-durable-intent":"external",c={id:yn("runtime-state-resource",r.protocol??"unknown",i),kind:"runtime-state-resource",label:i,disposition:"folded",location:{file:r.file,line:r.line},anchorIds:[],attributes:{protocol:r.protocol??null,durabilityClass:a}};e.set(s.id,s),e.set(c.id,c),Bc(t,n,s,"contains-runtime-state-effect");let l=wU(r.action);$c(t,{kind:"runtime-state-resource",from:s,to:c,semantics:[{family:"state",subtype:l,context:{crossesRuntimeBoundary:!0,protocol:r.protocol},attributes:{operation:r.action,durabilityClass:a,resource:i,recordIdentity:TU(r),modality:r.modality??null,resolution:r.resolution??null,transactionMembership:"unknown",commitState:r.protocol==="database"?"unknown":null}}],method:`runtime-boundary-${r.strength}`,identity:r.observationId})}function wU(e){return e==="database.read"?"reads-resource":e==="queue.send"?"enqueues-resource":e==="queue.consume"?"consumes-resource":"writes-resource"}function PU(e){return(e.keyParts?.find(n=>["address","resource"].includes(n.name))?.value??e.address)||e.observationId}function TU(e){return e.keyParts?.find(n=>/^(?:id|key|record)$/u.test(n.name))?.value??null}function tx(e,t){return e==="database"&&["database.read","database.write"].includes(t)||e==="queue"&&["queue.consume","queue.send"].includes(t)}function _c(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function LU(e,t,n,r){let i=e.filter(s=>s.location?.file===t&&["source-construct","symbol"].includes(s.kind)),o=i.filter(s=>s.location.line<=n&&(s.location.endLine??s.location.line)>=n).sort(MU)[0];if(o)return o;if(r){let s=i.find(a=>a.label===r||a.label.endsWith(`.${r}`)||a.label.includes(r));if(s)return s}return i.length===1?i[0]:null}function MU(e,t){let n=(e.location?.endLine??e.location?.line??0)-(e.location?.line??0),r=(t.location?.endLine??t.location?.line??0)-(t.location?.line??0);return n-r}function Oc(e,t){let n=e.location.file;return{id:yn(`program-${t.kind}`,n,String(t.startLine),String(t.endLine),t.label,e.id,String(t.startColumn??""),String(t.endColumn??"")),kind:`program-${t.kind}`,label:t.label,disposition:"folded",location:{file:n,line:t.startLine,endLine:t.endLine,startColumn:t.startColumn,endColumn:t.endColumn},anchorIds:[],attributes:{ownerNodeId:e.id,constructKind:t.kind}}}function DU(e,t,n){let r=e.location.file;return{id:yn("program-resource",r,e.id,t.resourceKey??t.label,n),kind:"program-resource",label:t.label,disposition:"folded",location:{file:r,line:t.startLine,endLine:t.endLine},anchorIds:[],attributes:{ownerNodeId:e.id,durabilityClass:n,identityBasis:t.identityBasis??"runtime-observation",heapIdentity:"unknown"}}}function Bc(e,t,n,r){let i=yn("edge","program-owner",t.id,n.id,r);e.has(i)||e.set(i,{id:i,kind:"program-owner",fromNodeId:t.id,toNodeId:n.id,directed:!0,disposition:"folded",semantics:[{family:"identity",subtype:r}],evidence:[{method:"parser-program-owner",strength:"exact",identity:t.id,location:n.location}]})}function $c(e,t){let n=yn("edge",t.kind,t.from.id,t.to.id,t.semantics[0].subtype);e.set(n,{id:n,kind:t.kind,fromNodeId:t.from.id,toNodeId:t.to.id,directed:!0,disposition:"folded",semantics:t.semantics,evidence:[{method:t.method,strength:"exact",identity:t.identity,location:t.from.location}]})}function yn(...e){return e.map(t=>encodeURIComponent(t)).join(":")}var FU=new Set(["control","data","state","temporal"]),jc=new Set(["contains-control","contains-event","contains-lock-scope","contains-state-effect","contains-runtime-state-effect","contains","owns-parameter","owns-runtime-observation"]),sx=new Set(["discriminator-dispatch","result-callback","returns","runtime-handoff","throws"]);function ax(e,t={}){let n=new Map(e.nodes.map(C=>[C.id,C])),r=VU(e.nodes,t.focusLocations),i=JU(e.edges,t.focusLocations),o=YU(e.edges,i),s=new Set(e.paths.flatMap(C=>C.edgeIds)),a=bn(e.anchors.filter(C=>C.status==="matched").flatMap(C=>C.nodeIds)),l=e.edges.filter(ox).filter(C=>kU(C,r,i,s)),u=l.filter(C=>KU(C,r,i,o,n,s)),d=rx(a,u,"forward"),m=UU(d,u),p=rx(m,u,"backward"),f=new Set([...d].filter(C=>p.has(C)));for(let C of a)f.add(C);let g=new Set(u.filter(C=>f.has(C.fromNodeId)&&f.has(C.toNodeId)).map(C=>C.id)),h=new Set(f),y=new Set(g);AU(l,h,y,r,i);let S=e.frontiers.filter(C=>QU(C,h)),I=bn(S.filter(C=>C.disposition==="unsupported").map(C=>C.id)),x=bn(e.edges.filter(C=>!ox(C)&&lx(C)&&XU(C,h)).map(C=>C.id)),E=bn(S.map(C=>C.id)),b=[];a.length===0&&b.push("No matched anchor node starts the corridor."),m.length===0&&b.push("No proved mechanical outcome is reachable from a matched anchor."),I.length>0&&b.push(`${I.length} unsupported frontier(s) touch the protected corridor.`),x.length>0&&b.push(`${x.length} candidate or unknown edge(s) touch the protected corridor.`);let v=b.length===0?"complete":"incomplete";return{schemaVersion:1,status:v,startNodeIds:a,outcomeNodeIds:m,baseNodeIds:bn([...f]),baseEdgeIds:bn([...g]),nodeIds:bn([...h]),edgeIds:bn([...y]),accountedFrontierIds:E,unresolvedFrontierIds:I,unresolvedEdgeIds:x,coverage:{protectedNodes:h.size,protectedEdges:y.size,baseNodes:f.size,baseEdges:g.size,accountedFrontiers:E.length,unresolvedFrontiers:I.length,unresolvedEdges:x.length},explanation:v==="complete"?"Every proved anchor-to-outcome path is closed over its material causal facts within reported coverage.":b.join(" ")}}function kU(e,t,n,r){return t===null||e.disposition==="emitted"||r.has(e.id)||n?.has(e.id)===!0?!0:(e.semantics??[]).some(i=>i.family==="identity"&&jc.has(i.subtype)?t.has(e.toNodeId):i.family==="contract"?t.has(e.fromNodeId)&&t.has(e.toNodeId):i.family==="state"?t.has(e.fromNodeId):i.family==="data"||i.family==="temporal"?t.has(e.fromNodeId)||t.has(e.toNodeId):i.family==="control"?NU(e,i,t):!1)}function NU(e,t,n){return ux(t)?n.has(e.fromNodeId):["returns","throws"].includes(t.subtype)?n.has(e.toNodeId):t.subtype==="completion-callback"?n.has(e.fromNodeId)||n.has(e.toNodeId):!1}function AU(e,t,n,r,i){let o=!0;for(;o;){o=!1;for(let s of e)HU(s,t,r,i)&&(n.has(s.id)||(n.add(s.id),o=!0),t.has(s.fromNodeId)||(t.add(s.fromNodeId),o=!0),t.has(s.toNodeId)||(t.add(s.toNodeId),o=!0))}}function _U(e,t){return cx(e)||["returns","throws"].includes(e.subtype)&&!t.toProtected&&!t.toFocused?!1:sx.has(e.subtype)||ux(e)||e.subtype==="completion-callback"}function OU(e,t){return e.subtype!=="lexical-successor"||t.fromProtected&&t.toProtected}function BU(e,t){return jc.has(e.subtype)&&(t.toProtected||t.toFocused)}function $U(e,t){switch(e.family){case"identity":return BU(e,t);case"contract":return!0;case"state":return t.fromProtected&&t.fromFocused;case"temporal":return OU(e,t);case"data":return jU(t);case"control":return _U(e,t);default:return!1}}function jU(e){return e.toProtected&&(e.fromProtected||e.fromFocused||e.edgeFocused)}function HU(e,t,n,r){let i=t.has(e.fromNodeId),o=t.has(e.toNodeId);if(!i&&!o)return!1;let s={fromProtected:i,toProtected:o,fromFocused:n===null||n.has(e.fromNodeId),toFocused:n===null||n.has(e.toNodeId),edgeFocused:r?.has(e.id)===!0};return(e.semantics??[]).some(a=>$U(a,s))}function UU(e,t){let n=new Set,r=new Map,i=new Map;for(let o of t)!e.has(o.fromNodeId)||!e.has(o.toNodeId)||(r.set(o.fromNodeId,(r.get(o.fromNodeId)??0)+1),i.set(o.toNodeId,(i.get(o.toNodeId)??0)+1),(o.semantics??[]).some(s=>s.family==="state"||s.family==="control"&&sx.has(s.subtype))&&n.add(o.toNodeId));return ZU(e,i,r,n),bn([...n])}function rx(e,t,n){let r=new Map;for(let s of t){let a=n==="forward"?s.fromNodeId:s.toNodeId,c=n==="forward"?s.toNodeId:s.fromNodeId,l=r.get(a)??[];l.push(c),r.set(a,l)}let i=new Set(e),o=[...e];for(;o.length>0;){let s=o.shift();for(let a of r.get(s)??[])i.has(a)||(i.add(a),o.push(a))}return i}function qU(e,t,n){return e.subtype==="lexical-successor"?t&&n:t||n}function zU(e,t,n,r,i){let o=n.has(t.fromNodeId),s=n.has(t.toNodeId);switch(e.family){case"state":return o;case"data":return o||s||r?.has(t.id)===!0;case"temporal":return qU(e,o,s);case"control":return WU(t,i)&&(o||s);default:return!1}}function GU(e,t,n,r,i,o){return e.family==="identity"&&jc.has(e.subtype)?n===null||n.has(t.toNodeId)||i?.has(t.toNodeId)===!0:!FU.has(e.family)||cx(e)?!1:n===null?!0:e.family==="control"&&["returns","throws"].includes(e.subtype)?n.has(t.toNodeId):zU(e,t,n,r,o)}function KU(e,t,n,r,i,o){return(e.semantics??[]).some(s=>e.disposition==="emitted"||o.has(e.id)?!0:GU(s,e,t,n,r,i))}function cx(e){return e.family==="control"&&["call","discriminator-dispatch","result-callback","runtime-handoff"].includes(e.subtype)}function WU(e,t){let n=t.get(e.fromNodeId),r=t.get(e.toNodeId);if(!n||!r)return!1;let i=ix(n,"ownerNodeId")??(n.kind==="symbol"?n.id:null),o=ix(r,"ownerNodeId")??(r.kind==="symbol"?r.id:null);return i!==null&&i===o}function VU(e,t){if(!t)return null;let n=new Map;for(let r of t){let i=n.get(r.file)??[];i.push(r.line),n.set(r.file,i)}return new Set(e.filter(r=>{if(!r.location||r.kind==="parameter")return!1;let i=n.get(r.location.file)??[],o=r.location.endLine??r.location.line;return i.some(s=>s>=r.location.line&&s<=o)}).map(r=>r.id))}function JU(e,t){if(!t)return null;let n=new Map;for(let r of t){let i=n.get(r.file)??[];i.push(r.line),n.set(r.file,i)}return new Set(e.filter(r=>r.evidence.some(i=>{if(!i.location)return!1;let o=n.get(i.location.file)??[],s=i.location.endLine??i.location.line;return o.some(a=>a>=i.location.line&&a<=s)})).map(r=>r.id))}function YU(e,t){return t===null?null:new Set(e.filter(n=>t.has(n.id)).flatMap(n=>[n.fromNodeId,n.toNodeId]))}function ix(e,t){let n=e.attributes[t];return typeof n=="string"?n:null}function ox(e){return e.disposition==="excluded"||e.disposition==="unsupported"||!lx(e)?!1:e.evidence.some(t=>t.strength==="exact"||t.strength==="derived")}function lx(e){return(e.semantics??[]).some(t=>t.family!=="identity"||jc.has(t.subtype))}function ux(e){return e.subtype.startsWith("predicate-")||e.subtype.startsWith("loop-")||e.subtype.startsWith("exception-")||e.subtype.startsWith("finally-")||e.subtype.startsWith("handler-")}function XU(e,t){return t.has(e.fromNodeId)||t.has(e.toNodeId)}function QU(e,t){return[...e.fromNodeIds,...e.memberNodeIds].some(n=>t.has(n))}function bn(e){return[...new Set(e)].sort()}function ZU(e,t,n,r){for(let i of e)(t.get(i)??0)>0&&(n.get(i)??0)===0&&r.add(i)}import{createHash as eq}from"crypto";var Hc=["identity","contract","control","data","state","temporal"],tq=new Set(Hc);function qc(e){let t=Fi(e.anchors,"anchor"),n=Fi(e.nodes,"node"),r=Fi(e.edges,"edge"),i=Fi(e.paths??[],"path"),o=Fi(e.frontiers??[],"frontier"),s=new Set(t.map(p=>p.id)),a=new Set(n.map(p=>p.id)),c=new Set(r.map(p=>p.id)),l=e.routeCatalog?{...e.routeCatalog,routes:Fi(e.routeCatalog.routes,"route"),selectedRouteIds:Ze(e.routeCatalog.selectedRouteIds)}:void 0;nq(t,n,r,i,s,a,c),rq(o,l,a,c);let u=Ze(e.incompleteReasons??[]),d=u.length===0?"accounted":"incomplete",m=t.reduce((p,f)=>p+f.omittedCandidates,0);return{schemaVersion:1,anchors:t,nodes:n,edges:r,paths:i,frontiers:o,coverage:{status:d,scope:e.scope,nodes:hx(n),edges:hx(r),matchedAnchors:t.filter(p=>p.status==="matched").length,ambiguousAnchors:t.filter(p=>p.status==="ambiguous").length,missingAnchors:t.filter(p=>p.status==="missing").length,omittedCandidates:m,frontierGroups:o.length,programEdges:oq(r),blindSpots:Ze(e.blindSpots??[]),explanation:d==="accounted"?"Every node and edge discovered within the declared query scope is emitted, folded with recoverable identity, explicitly excluded, or reported unsupported.":`The declared query scope is not fully accounted for: ${u.join("; ")}`},completion:lq(d,i,e.scope),...l?{routeCatalog:l}:{}}}function nq(e,t,n,r,i,o,s){for(let a of e)ct(`anchor ${a.id}`,[...a.nodeIds,...a.candidateNodeIds],o,"node");for(let a of t)ct(`node ${a.id}`,a.anchorIds,i,"anchor");for(let a of n){if(ct(`edge ${a.id}`,[a.fromNodeId,a.toNodeId],o,"node"),a.evidence.length===0)throw new Error(`Exploration edge ${a.id} has no evidence source.`);sq(a)}for(let a of r)ct(`path ${a.id}`,[a.fromAnchorId,a.toAnchorId],i,"anchor"),ct(`path ${a.id}`,a.nodeIds,o,"node"),ct(`path ${a.id}`,a.edgeIds,s,"edge")}function rq(e,t,n,r){for(let i of e)if(ct(`frontier ${i.id}`,i.fromNodeIds,n,"node"),ct(`frontier ${i.id}`,i.edgeIds,r,"edge"),ct(`frontier ${i.id}`,i.memberNodeIds,n,"node"),i.memberCount!==i.memberNodeIds.length)throw new Error(`Exploration frontier ${i.id} reports ${i.memberCount} member(s) but identifies ${i.memberNodeIds.length}.`);for(let i of t?.routes??[])ct(`route ${i.id}`,i.nodeIds,n,"node"),ct(`route ${i.id}`,i.edgeIds,r,"edge"),ct(`route ${i.id}`,[i.anchorNodeId,i.endpointNodeId],n,"node");t&&ct("route catalog selection",t.selectedRouteIds,new Set(t.routes.map(i=>i.id)),"route")}function iq(e){return e.flatMap(t=>aq(t.semantics??[]).map(n=>({id:cq(t.id,n),sourceEdgeId:t.id,sourceKind:t.kind,fromNodeId:t.fromNodeId,toNodeId:t.toNodeId,directed:!0,disposition:t.disposition,evidence:[...t.evidence],family:n.family,subtype:n.subtype,...n.context?{context:{...n.context}}:{},...n.attributes?{attributes:{...n.attributes}}:{}}))).sort((t,n)=>t.id.localeCompare(n.id))}function oq(e){let t=iq(e),n=new Set(t.map(s=>s.sourceEdgeId)),r=new Map(Hc.map(s=>[s,new Set])),i=new Map(Hc.map(s=>[s,new Set])),o=new Map(Hc.map(s=>[s,0]));for(let s of t)r.get(s.family).add(s.sourceEdgeId),i.get(s.family).add(s.subtype),o.set(s.family,o.get(s.family)+1);return{sourceEdges:e.length,mappedSourceEdges:n.size,projectedEdges:t.length,unmappedSourceEdges:e.length-n.size,unsupportedSourceEdges:e.filter(s=>s.disposition==="unsupported").length,unmappedKinds:Ze(e.filter(s=>!n.has(s.id)).map(s=>s.kind)),families:{identity:Di("identity",r,o,i),contract:Di("contract",r,o,i),control:Di("control",r,o,i),data:Di("data",r,o,i),state:Di("state",r,o,i),temporal:Di("temporal",r,o,i)}}}function Di(e,t,n,r){return{sourceEdges:t.get(e)?.size??0,projectedEdges:n.get(e)??0,subtypes:[...r.get(e)??[]].sort()}}function sq(e){let t=new Set;for(let n of e.semantics??[]){if(!tq.has(n.family))throw new Error(`Exploration edge ${e.id} has unknown program edge family: ${n.family}.`);if(n.subtype.trim().length===0)throw new Error(`Exploration edge ${e.id} has an empty program edge subtype.`);let r=wm(n);if(t.has(r))throw new Error(`Exploration edge ${e.id} repeats program edge semantic ${r}.`);t.add(r)}}function aq(e){return[...e].sort((t,n)=>wm(t).localeCompare(wm(n)))}function wm(e){return`${e.family}:${e.subtype}`}function cq(e,t){return`program:${encodeURIComponent(e)}:${t.family}:${encodeURIComponent(t.subtype)}`}function lq(e,t,n){return e==="incomplete"||t.some(r=>r.status!=="connected")?{status:"coverage-incomplete",scope:n,explanation:"The declared graph query has an ambiguous, missing, candidate-only, or disconnected anchor relationship."}:t.length>0?{status:"connector-complete",scope:n,explanation:"Every requested anchor pair has a selected path supported by proved repository relationships."}:{status:"frontier-accounted",scope:n,explanation:"Every discovered direction in the declared graph query is emitted or represented by an exact frontier."}}function yx(e,t={}){let n=t.maxSelectedNodes??24;if(!Number.isSafeInteger(n)||n<=0)throw new RangeError(`maxSelectedNodes must be a positive safe integer; received ${n}`);let r=new Set(e.anchors.flatMap(p=>[...p.nodeIds,...p.candidateNodeIds])),i=pq(e,r),o=Ze(t.routeIds??[]),s=yq(e,o),c=uq(s,o).map(p=>({anchorNodeId:p.anchorNodeId,endpointNodeId:p.endpointNodeId,endpointKind:p.endpointKind,endpointPriority:2,nodeIds:[...p.nodeIds].reverse(),edgeIds:[...p.edgeIds].reverse()}));for(let p of c)p.nodeIds.forEach(f=>r.add(f));let l=i.length===0||i.some(p=>p.edgeIds.length>0);l&&gx(e,r,n),gq(e,r,t.expandedFrontierIds),l&&gx(e,r,n);let u=hq(e,c,r),d=dq(e,i,c,r),m=qc({anchors:e.anchors,nodes:u,edges:d,paths:i,frontiers:[...e.frontiers.filter(p=>p.disposition!=="folded"),...vx({...e,nodes:u,edges:d},r)],scope:e.coverage.scope,blindSpots:e.coverage.blindSpots,incompleteReasons:e.coverage.status==="incomplete"?[e.coverage.explanation]:[],routeCatalog:s});return mq(m),m}function uq(e,t){let n=new Set(e.routes.map(o=>o.id)),r=t.filter(o=>!n.has(o));if(r.length>0)throw new Error(`Unknown exploration route id(s): ${r.join(", ")}`);return e.routes.filter(o=>t.includes(o.id))}function dq(e,t,n,r){let i=new Set([...t.flatMap(s=>s.edgeIds),...n.flatMap(s=>s.edgeIds)]);return e.edges.map(s=>({...s,disposition:s.disposition==="excluded"||s.disposition==="unsupported"?s.disposition:i.has(s.id)||r.has(s.fromNodeId)&&r.has(s.toNodeId)?"emitted":"folded"}))}function mq(e){let t=new Set(e.frontiers.flatMap(r=>r.edgeIds)),n=e.edges.filter(r=>r.disposition==="folded"&&!t.has(r.id)).map(r=>r.id);if(n.length>0)throw new Error(`Folded exploration edge(s) are not frontier-accounted: ${n.sort().join(", ")}`)}function pq(e,t){let n=[],r=e.anchors.filter(i=>i.status!=="missing"&&i.nodeIds.length+i.candidateNodeIds.length>0);for(let i=0;i<r.length;i+=1)for(let o=i+1;o<r.length;o+=1){let s=r[i],a=r[o],c=fq(e,s,a);c.nodeIds.forEach(l=>t.add(l)),n.push(c)}return n}function fq(e,t,n){let r=px(e,t,n,!1),o=r??px(e,t,n,!0);return o?{id:Uc("path",t.id,n.id),fromAnchorId:t.id,toAnchorId:n.id,status:!r||t.status==="ambiguous"||n.status==="ambiguous"?"candidate":"connected",nodeIds:o.nodeIds,edgeIds:o.edgeIds}:{id:Uc("path",t.id,n.id),fromAnchorId:t.id,toAnchorId:n.id,status:"partial",nodeIds:[],edgeIds:[]}}function gq(e,t,n){let r=vx(e,t),i=new Set(n??[]),o=new Set(r.map(a=>a.id)),s=[...i].filter(a=>!o.has(a)).sort();if(s.length>0)throw new Error(`Unknown exploration frontier id(s): ${s.join(", ")}`);for(let a of r)i.has(a.id)&&a.memberNodeIds.forEach(c=>t.add(c))}function hq(e,t,n){let r=new Map(t.map(a=>[a.endpointNodeId,a.endpointKind])),i=new Set(t.flatMap(a=>a.nodeIds)),o=new Map;for(let a of t)for(let c=0;c<a.nodeIds.length;c+=1){let l=a.nodeIds[c],u=c;o.set(l,Math.max(o.get(l)??0,u))}return e.nodes.map(a=>{let c=r.get(a.id),l=i.has(a.id)?{upstreamCausalPath:!0,upstreamCausalDistance:o.get(a.id)??0,...c?{upstreamCausalEndpoint:c}:{}}:{};return{...a,attributes:{...a.attributes,...l},disposition:a.disposition==="excluded"||a.disposition==="unsupported"?a.disposition:n.has(a.id)?"emitted":"folded"}})}var bx=10;function yq(e,t=[]){let n=new Map(e.nodes.map(h=>[h.id,h])),r=new Map(e.edges.map(h=>[h.id,h])),i=Sq(e),o=Ze(e.anchors.filter(h=>h.status==="matched").flatMap(h=>h.nodeIds)),s=new Map,a=new Set,c=(h,y,S)=>{bq(e,n,r,s,h,y,S)};for(let h of o)vq(h,n,i,c,a);let l=[...s.values()].sort(Sx),u=new Set(l.map(h=>h.id)),d=Ze(t.filter(h=>u.has(h))),m=Ze(l.map(h=>h.anchorNodeId)),p=o.filter(h=>!m.includes(h)),f=[...a].sort(),g=e.coverage.status==="accounted"&&f.length===0?"accounted":"incomplete";return{schemaVersion:1,routes:l,selectedRouteIds:d,coverage:{status:g,scope:"Distinct proved public-entry and runtime-boundary endpoints reachable upstream in the supplied topology.",enumeration:"one-shortest-proved-path-per-endpoint",maximumDepth:bx,anchorNodeIds:o,anchorsWithRoutes:m,anchorsWithoutRoutes:p,depthLimitedAnchorNodeIds:f,routeCount:l.length,explanation:g==="accounted"?"Every distinct proved upstream public/runtime endpoint in the supplied topology has one stable shortest route.":"Route enumeration is incomplete because the supplied topology has incomplete coverage or a traversal reached the route-depth bound."}}}function bq(e,t,n,r,i,o,s){let a=o.nodeIds[o.nodeIds.length-1],c=t.get(a),l=t.get(i);if(!c?.location||!l)return;let u=[...o.nodeIds].reverse(),d=[...o.edgeIds].reverse(),m=new Set(u),p=d.flatMap(S=>{let I=n.get(S);return I?[I]:[]}),f=e.edges.filter(S=>S.disposition!=="excluded"&&S.disposition!=="unsupported"&&(m.has(S.fromNodeId)||m.has(S.toNodeId))),g={id:Uc("route",i,a,s,...d),status:"proved",anchorNodeId:i,anchorLabel:l.label,endpointNodeId:a,endpointLabel:c.label,endpointLocation:{...c.location},endpointKind:s,nodeIds:u,edgeIds:d,evidenceStrengths:Ze(p.flatMap(S=>S.evidence.map(I=>I.strength))),spineEdgeFamilies:dx(p,!0),relatedEdgeFamilies:dx(f,!1),crossesRuntimeBoundary:p.some(us)},h=`${i}\0${a}\0${s}`,y=r.get(h);(!y||Sx(g,y)<0)&&r.set(h,g)}function Sq(e){let t=new Map;for(let n of e.edges){if(!xq(n))continue;let r=t.get(n.toNodeId)??[];r.push(n),t.set(n.toNodeId,r)}for(let n of t.values())n.sort((r,i)=>Number(us(i))-Number(us(r))||mx(i)-mx(r)||r.fromNodeId.localeCompare(i.fromNodeId)||r.id.localeCompare(i.id));return t}function vq(e,t,n,r,i){t.get(e)?.attributes.publicEntry===!0&&r(e,{nodeIds:[e],edgeIds:[]},"public-entry");let o=[{nodeIds:[e],edgeIds:[]}],s=new Map([[e,0]]);for(let a=0;a<o.length;a+=1){let c=o[a],l=c.nodeIds[c.nodeIds.length-1];c.edgeIds.length>0&&t.get(l)?.location&&t.get(l)?.attributes.publicEntry===!0&&r(e,c,"public-entry");let u=n.get(l)??[];if(c.edgeIds.length>=bx){u.some(d=>!c.nodeIds.includes(d.fromNodeId))&&i.add(e);continue}Cq(e,c,u,s,t,r,o)}}function Cq(e,t,n,r,i,o,s){for(let a of n){if(t.nodeIds.includes(a.fromNodeId))continue;let c=t.edgeIds.length+1,l=r.get(a.fromNodeId);if(l!==void 0&&l<=c)continue;let u={nodeIds:[...t.nodeIds,a.fromNodeId],edgeIds:[...t.edgeIds,a.id]};if(r.set(a.fromNodeId,c),us(a)&&i.get(a.fromNodeId)?.location){o(e,u,"runtime-boundary");continue}s.push(u)}}function dx(e,t){let n=e.flatMap(r=>r.semantics?.map(i=>i.family)??[]);return t&&e.length>0&&n.length===0&&n.push("control"),Ze(n)}function Sx(e,t){return e.anchorNodeId.localeCompare(t.anchorNodeId)||e.edgeIds.length-t.edgeIds.length||e.endpointKind.localeCompare(t.endpointKind)||e.endpointNodeId.localeCompare(t.endpointNodeId)||e.id.localeCompare(t.id)}function xq(e){return e.disposition!=="excluded"&&e.disposition!=="unsupported"&&Rq(e)&&e.evidence.some(t=>["exact","derived","mixed"].includes(t.strength))}function Rq(e){return us(e)||e.kind==="boundary-observation"||e.kind==="call"||e.kind==="compiler:call"}function us(e){return e.kind==="runtime-boundary"||e.kind.startsWith("runtime:")}function mx(e){let t={exact:5,derived:4,mixed:3,candidate:1,unknown:0};return Math.max(0,...e.evidence.map(n=>t[n.strength]))}function px(e,t,n,r){return fx(e,t,n,r)??fx(e,n,t,r)}function fx(e,t,n,r){let i=[...t.nodeIds,...t.candidateNodeIds].sort(),o=new Set([...n.nodeIds,...n.candidateNodeIds]);if(i.some(a=>o.has(a)))return{nodeIds:[i.find(c=>o.has(c))],edgeIds:[]};let s=Eq(e,r);return Iq(i,o,s)}function Eq(e,t){let n=new Set(e.nodes.filter(i=>i.kind==="structural-region").map(i=>i.id)),r=new Map;for(let i of e.edges)i.disposition==="excluded"||i.disposition==="unsupported"||i.kind==="structural-membership"||n.has(i.fromNodeId)||n.has(i.toNodeId)||i.evidence.every(s=>["candidate","unknown"].includes(s.strength))&&!t||wq(r,i.fromNodeId,i.toNodeId,i.id);for(let i of r.values())i.sort((o,s)=>o.nodeId.localeCompare(s.nodeId)||o.edgeId.localeCompare(s.edgeId));return r}function Iq(e,t,n){let r=e.map(o=>({nodeId:o,nodeIds:[o],edgeIds:[]})),i=new Set(e);for(let o=0;o<r.length;o+=1){let s=r[o];for(let a of n.get(s.nodeId)??[]){if(i.has(a.nodeId))continue;let c={nodeId:a.nodeId,nodeIds:[...s.nodeIds,a.nodeId],edgeIds:[...s.edgeIds,a.edgeId]};if(t.has(a.nodeId))return c;i.add(a.nodeId),r.push(c)}}return null}function wq(e,t,n,r){let i=e.get(t)??[];i.push({nodeId:n,edgeId:r}),e.set(t,i)}function Pq(e,t,n){let r=Tq(e),{boundaryCandidates:i,selectedNeighborsByCandidate:o}=Lq(e,t),s=[...o].filter(([a,c])=>{if(i.has(a))return!0;let l=r.get(a)??{incoming:0,outgoing:0};return(l.incoming>1||l.outgoing>1)&&c.size>1}).sort(([a,c],[l,u])=>Number(i.has(l))-Number(i.has(a))||u.size-c.size||a.localeCompare(l)).map(([a])=>a);for(let a of s){if(t.size>=n)break;t.add(a)}}function Tq(e){let t=new Map;for(let n of e.edges){let r=t.get(n.fromNodeId)??{incoming:0,outgoing:0},i=t.get(n.toNodeId)??{incoming:0,outgoing:0};r.outgoing+=1,i.incoming+=1,t.set(n.fromNodeId,r),t.set(n.toNodeId,i)}return t}function Lq(e,t){let n=new Set,r=new Map;for(let i of e.edges){let o=t.has(i.fromNodeId),s=t.has(i.toNodeId);if(o===s)continue;let a=o?i.toNodeId:i.fromNodeId,c=o?i.fromNodeId:i.toNodeId,l=e.nodes.find(m=>m.id===a);if(l?.kind==="structural-region")continue;let u=r.get(a)??new Set;u.add(c),r.set(a,u),(/(?:runtime-boundary|external)/u.test(i.kind)||l&&/(?:frontier|external)/u.test(l.kind))&&n.add(a)}return{boundaryCandidates:n,selectedNeighborsByCandidate:r}}function gx(e,t,n){let r=-1;for(;t.size!==r&&t.size<n;)r=t.size,Pq(e,t,n)}function vx(e,t){let n=new Set(e.nodes.filter(s=>!t.has(s.id)&&s.disposition!=="excluded"&&s.disposition!=="unsupported").map(s=>s.id)),r=Mq(e,n),i=[],o=new Set;for(let s of[...n].sort()){if(o.has(s))continue;let a=[],c=[s];o.add(s);for(let l=0;l<c.length;l+=1){let u=c[l];a.push(u);for(let d of[...r.get(u)??[]].sort())o.has(d)||(o.add(d),c.push(d))}i.push(a.sort())}return i.map(s=>{let a=new Set(s),c=e.edges.filter(f=>a.has(f.fromNodeId)||a.has(f.toNodeId)),l=c.filter(f=>a.has(f.fromNodeId)!==a.has(f.toNodeId)),u=Ze(l.map(f=>a.has(f.fromNodeId)?f.toNodeId:f.fromNodeId)),d=new Set(l.map(f=>a.has(f.toNodeId)?"outgoing":"incoming")),m=Ze(c.map(f=>f.id)),p=Ze(l.map(f=>f.kind));return{id:Uc("frontier",...s,...m),kind:p.join("+")||"disconnected",direction:d.size===1?[...d][0]:"undirected",fromNodeIds:u,edgeIds:m,memberNodeIds:s,memberCount:s.length,disposition:"folded",reason:l.length>0?"Connected evidence is folded beyond the first edge leaving the selected connector graph.":"Discovered evidence is disconnected from every selected anchor connector under the declared relation scope.",expansion:null}})}function Uc(e,...t){let n=eq("sha256").update(t.join("\0")).digest("hex").slice(0,16);return`${e}:${n}`}function Fi(e,t){let n=[...e].sort((r,i)=>r.id.localeCompare(i.id));for(let r=1;r<n.length;r+=1)if(n[r-1].id===n[r].id)throw new Error(`Duplicate exploration ${t} id: ${n[r].id}`);return n}function ct(e,t,n,r){let i=Ze(t.filter(o=>!n.has(o)));if(i.length>0)throw new Error(`Exploration ${e} references missing ${r}(s): ${i.join(", ")}`)}function hx(e){return{total:e.length,emitted:e.filter(t=>t.disposition==="emitted").length,folded:e.filter(t=>t.disposition==="folded").length,excluded:e.filter(t=>t.disposition==="excluded").length,unsupported:e.filter(t=>t.disposition==="unsupported").length}}function Ze(e){return[...new Set(e)].sort()}function Mq(e,t){let n=new Map;for(let r of e.edges){if(!t.has(r.fromNodeId)||!t.has(r.toNodeId))continue;let i=n.get(r.fromNodeId)??new Set,o=n.get(r.toNodeId)??new Set;i.add(r.toNodeId),o.add(r.fromNodeId),n.set(r.fromNodeId,i),n.set(r.toNodeId,o)}return n}var Dq=5,Fq=12,kq=8,Nq=3,Cx=8,Aq=6,_q=12,xx=12,Oq=12,Bq=2,$q=new Set(["branch","loop","call","await","return","throw","mutation","catch","finally"]),jq=9e3,Rx=SC,Ex=new WeakMap;function kx(e,t){return Cz(e,t,"topology")}function Hq(e,t,n,r,i,o=!1){let s=e.get(t);if(s)return s.depth=Math.min(s.depth,n),s.primary||=i,s.promoteBoundaryImports||=o,s.origins.add(r),s;let a={file:t,depth:n,primary:i,promoteBoundaryImports:o,origins:new Set([r]),processed:!1};return e.set(t,a),a}function Uq(e,t,n,r,i,o,s="none",a=!1){let c=e.get(n.symbol);if(c)return c.depth=Math.min(c.depth,r),c.origins.add(i),o&&c.anchorQueries.add(o),c.referenceScope=MG(c.referenceScope,s),t(n.relativePath,r,i,!0,a),c;let l={definition:n,depth:r,origins:new Set([i]),anchorQueries:new Set(o?[o]:[]),referenceScope:s,processed:!1};return e.set(n.symbol,l),t(n.relativePath,r,i,!0,a),l}function qq(e,t,n,r,i,o,s=!1,a=!0){let c=Xt(n),l=e.get(c);if(l)return l.depth=Math.min(l.depth,r),l.origins.add(i),o&&l.anchorQueries.add(o),l.reverseCallExpansion||=s,l.traversalEligible||=a,t(n.file,r,i,l.traversalEligible,!0),l;let u={...n,depth:r,origins:new Set([i]),anchorQueries:new Set(o?[o]:[]),reverseCallExpansion:s,traversalEligible:a};return e.set(c,u),t(n.file,r,i,a,!0),u}function zq(e){let{db:t,index:n,pendingRelations:r,addFile:i,addSymbol:o,addSourceConstruct:s,observation:a,depth:c,origin:l}=e;i(a.source.file,c,l,!0,!0),a.owner.file!==a.source.file&&i(a.owner.file,c,`${l}:owner`,!0,!0);let u=D(t,a.owner.file),d=a.owner.symbol?wr(t,n,a.owner.symbol).matches.find(f=>f.relativePath===a.owner.file):null,m=(d&&!he(d.symbol)?d:null)??ir(u,a.source.startLine);if(m&&!he(m.symbol))return o(m,c,l,void 0,"none",!0),m.symbol;a.owner.name&&s({file:a.owner.file,name:a.owner.name,startLine:a.owner.startLine,endLine:a.owner.endLine},c,`${l}:source-owner`,void 0,!0);let p=e.index.definitionsForFile(a.source.file).filter(f=>!!f.leaf&&uo(t,a.source.file,f.leaf).some(g=>g>=a.source.startLine&&g<=a.source.endLine));if(p.length===1){let f=p[0];o(f,c,`${l}:handler-identifier`,void 0,"none",!0),lt(r,{kind:"runtime-boundary",evidence:"runtime-boundary:handler-identifier",fromFile:a.source.file,fromSymbol:null,toFile:f.relativePath,toSymbol:f.symbol,fromBoundaryParticipant:Kc(a),line:a.source.startLine,strength:"derived"})}return null}function Gq(e){let t=0,n=0;for(let i of e.searches){let o=Kq(e,i);for(let s of o.materializedMatches)Wq(e,i,s,o.activeTraversalSeeds.has(ms(s)));e.anchors.push(Vq(i,o)),o.broad&&(t+=1,n+=o.matches.length)}let r=0;for(let i of e.symbolQueries)r+=Jq(e,i);return{omittedSymbolCandidates:r,broadLiteralAnchors:t,withheldLiteralMatches:n}}function Kq(e,t){let n=lG(e.db,e.index,t,e.boundaryObservationLocations),r=n.filter(a=>vG(a,e.sourceAllowed)),i=!e.opts.fullLiteralTraversal&&(n.length>Fq||r.length>kq),o=i?[]:n,s=new Set((i?[]:e.opts.fullLiteralTraversal?r:[...r].sort(fG).slice(0,Nq)).map(ms));return{matches:n,traversalEligible:r,broad:i,materializedMatches:o,activeTraversalSeeds:s}}function Wq(e,t,n,r){let i=r&&!n.ownerSymbol&&n.ownerStartLine!==null&&n.ownerEndLine!==null;e.addFile(n.relativePath,0,`${r?"literal-anchor":"literal-match"}:${t}`,i,i),i&&e.addSourceConstruct({file:n.relativePath,name:n.ownerShortName??`${n.relativePath}:${n.ownerStartLine+1}`,startLine:n.ownerStartLine,endLine:n.ownerEndLine},0,`literal-source-owner:${t}`,t,!0),r&&n.ownerSymbol&&GG(e,t,n.ownerSymbol),e.literalHits.push({query:t,file:n.relativePath,line:n.line,ownerSymbol:n.ownerSymbol,ownerShortName:n.ownerShortName,ownerStartLine:n.ownerStartLine,ownerEndLine:n.ownerEndLine,ownerStartColumn:n.ownerStartColumn,ownerEndColumn:n.ownerEndColumn,sourceLine:n.sourceLine.trim(),matchKind:n.matchKind,traversalSeed:r})}function Vq(e,t){let{matches:n,traversalEligible:r,broad:i,materializedMatches:o,activeTraversalSeeds:s}=t;return{kind:"literal",query:e,status:n.length>0?"matched":"missing",matchedRegionIds:[],matchingLines:ki(n),seedMatchingLines:i?0:ki(n.filter(a=>s.has(ms(a)))),matchOnlyLines:ki(n.filter(a=>!s.has(ms(a)))),eligibleSeedMatchingLines:ki(r),materializedMatchingLines:ki(o),withheldMatchingLines:i?ki(n):0,literalTraversal:i?"withheld-broad":"materialized",representativeMatches:i?CG(e,n):void 0,narrowingCommands:i?RG(e,n):void 0,exhaustiveTraversalCommand:i||s.size<r.length?`scip-query system-map --search ${O(e)} --full-literal-traversal`:void 0,seedRegionIds:[],matchOnlyRegionIds:[]}}function Jq(e,t){let n=wr(e.db,e.index,t),r=yG(e.db,t),i=n.matches.filter(l=>!he(l.symbol)),o=r!==null&&i.length===0;o&&e.addSourceConstruct(r,0,"source-construct-anchor",t,!0);let s=o?i:n.matches;for(let l of s)e.addSymbol(l,0,"symbol-anchor",t,"all",!0);let a=o?bG(r):null,c=o?1:n.total;return e.anchors.push({kind:"symbol",query:t,status:c===0?"missing":c===1?"matched":"ambiguous",matchedRegionIds:[],symbolCandidates:[...a?[a]:[],...s.map(PG)],totalSymbolCandidates:c,omittedSymbolCandidates:n.omitted}),n.omitted}function Yq(e){let{db:t,opts:n,mode:r,searches:i,symbolQueries:o,maxDepth:s,maxTopologyCharacters:a,requestedRelationKinds:c,evidenceFloor:l,includedSourceScopes:u,workspaces:d,runtimeBoundaries:m,boundaryObservations:p,representedBoundaryLinkIds:f,files:g,symbols:h,sourceConstructs:y,literalHits:S,pendingRelations:I,externalImports:x,anchors:E,omittedSymbolCandidates:b,broadLiteralAnchors:v,withheldLiteralMatches:C,filteredUnverifiedCallEdges:R,memberCallCandidateEdges:P,unresolvedMemberCallsites:w,sourceAllowed:T}=e,G=new Set(c),K=new Map;for(let B of g.keys())K.set(B,ps(B,d));let ue=[...I.values()].filter(B=>K.has(B.fromFile)&&K.has(B.toFile)).map(B=>({...B,fromRegionId:K.get(B.fromFile).id,toRegionId:K.get(B.toFile).id})).sort(zx),ce=$G(ue),Ce=new Set(n.expand??[]),pe=AG(g,h,S,ue,ce,K,Ce),Je=new Set([...g.values()].filter(B=>[...B.origins].some(qe=>qe.startsWith("literal-anchor:")||qe==="literal-owner"||qe==="symbol-anchor")).map(B=>K.get(B.file).id)),$=sG(pe),U=new Set(pe.map(B=>B.id)),pt=[...Ce].filter(B=>!U.has(B)).sort();for(let B of E)if(B.matchedRegionIds=HG(B,S,h,K),B.kind==="literal"){let qe=S.filter(Me=>Me.query===B.query);B.seedRegionIds=re(qe.filter(Me=>Me.traversalSeed).map(Me=>K.get(Me.file).id)),B.matchOnlyRegionIds=re(qe.filter(Me=>!Me.traversalSeed).map(Me=>K.get(Me.file).id))}let Or=[...h.values()].filter(B=>!B.processed).length,qs=[...g.values()].filter(B=>B.primary&&!B.processed).length,Wn=[...g.values()].filter(B=>!B.primary&&!B.processed).length,ne=[...h.values()].filter(B=>B.processed),ft=()=>{let B=W=>!W.source||!W.action||!W.strength?[]:!G.has("runtime-boundary")||!T(W.source.file)||l==="exact"||!g.has(W.source.file)?[]:[{observationId:W.observationId,action:W.action,strength:W.strength,file:W.source.file,line:W.source.startLine,ownerShortName:W.ownerShortName??null,address:W.address??W.missingKeyParts.join(", "),reason:W.reason}],qe=(m?.frontiers??[]).flatMap(W=>{let me=p.get(W.observationId);return me?!G.has("runtime-boundary")||!T(me.source.file)||l==="exact"&&me.strength!=="exact"||!g.has(me.source.file)?[]:[{observationId:me.id,action:me.action,strength:me.strength,file:me.source.file,line:me.source.startLine,ownerShortName:me.owner.name,address:qx(me),reason:W.reason,protocol:me.protocol,role:me.role,modality:me.modality,resolution:me.resolution,sourceScope:me.sourceScope,keyParts:me.keyParts.map(Xn=>({name:Xn.name,value:Xn.value,evidence:Xn.evidence}))}]:B(W)}).sort((W,me)=>W.file.localeCompare(me.file)||W.line-me.line),Me=(m?.links??[]).filter(W=>{if(!G.has("runtime-boundary")||l==="exact"&&W.strength!=="exact")return!1;let me=p.get(W.from),Xn=p.get(W.to);return!!(me&&Xn&&T(me.source.file)&&T(Xn.source.file)&&(g.has(me.source.file)||g.has(Xn.source.file)))}),Yn=Me.filter(W=>W.strength==="exact").length,De=Me.filter(W=>W.strength==="derived").length,bT=Me.filter(W=>W.strength==="candidate").length,ST=m?.links.filter(W=>W.strength==="exact").length??0,vT=m?.links.filter(W=>W.strength==="derived").length??0,CT=m?.links.filter(W=>W.strength==="candidate").length??0;return{boundaryFrontiers:qe,exactBoundaryLinks:Yn,derivedBoundaryLinks:De,candidateBoundaryLinks:bT,repositoryExactBoundaryLinks:ST,repositoryDerivedBoundaryLinks:vT,repositoryCandidateBoundaryLinks:CT}},{boundaryFrontiers:Ue,exactBoundaryLinks:Vn,derivedBoundaryLinks:Jn,candidateBoundaryLinks:Qi,repositoryExactBoundaryLinks:gT,repositoryDerivedBoundaryLinks:hT,repositoryCandidateBoundaryLinks:yT}=ft(),Vl=jG(x,K),Rf=_x(E,b),Jl=Rf.length===0?"accounted":"incomplete",Ef=[...v>0?[`${v} broad literal anchor(s) withheld ${C} exact match(es) before graph traversal; representative identities and scoped search commands preserve recovery without treating every textual occurrence as relevant.`]:[],`Literal matches outside the included source scopes (${u.join(", ")}) remain visible as match-only evidence and do not seed traversal.`,m?"Runtime observations retain their own proof strength; possible peers remain candidate links when deployment, broker, receiver, or dataflow identity is unproved. Unsupported frameworks, reflection, generated names, and unresolved dependency wiring remain coverage limits.":"Runtime-boundary evidence is unavailable for this index; run scip-query reindex with this build to extract supported HTTP, event, registry, and persistence observations.","Reverse references do not recursively expand from discovered callers or callees.","Member calls use compiler occurrences, exact constructor-assigned fields, bounded unique service providers, direct factory-return members, and compiler-resolved object-literal callbacks when available. Ambiguous providers remain candidate frontiers; callback values routed through mutation, reflection, or unsupported dependency containers remain unrepresented.","Literal traversal is bounded to the smallest parser-delimited source construct; parser gaps may reduce an owner to one source line and leave its continuation untraversed.","Schema consumers stay within forward-flow regions; cross-workspace contracts may discover consumers in other workspaces. Add an explicit symbol anchor to widen either scope.",`Traversal stops after depth ${s}; nonzero frontier counts identify evidence that was discovered but not traversed.`,"Region labels are structural path groupings, not inferred runtime or architectural boundaries."],gt=Jz({db:t,anchors:E,regions:pe,symbolStates:h,sourceConstructStates:y,literalHits:S,relations:ue,externalBoundaries:Vl,boundaryFrontiers:Ue,regionForFile:K,closureStatus:Jl,omittedSymbolCandidates:b,maxDepth:s,requestedRelationKinds:c,evidenceFloor:l,includedSourceScopes:u,blindSpots:Ef,topologyFrontiers:n.topologyFrontiers??[],routeIds:n.routeIds??[],expandedRegionIds:[...Ce],maxTopologyCharacters:a,fullLiteralTraversal:n.fullLiteralTraversal??!1});if(r==="topology")return gt;let If=(()=>{let B=(n.behaviorFocusLocations?.length??0)>0?new Set([...gt.anchors.flatMap(Yn=>Yn.nodeIds),...gt.paths.flatMap(Yn=>Yn.nodeIds)]).size:void 0,qe=pC(t,gt,{focusLocations:n.behaviorFocusLocations,...B?{maxSteps:B}:{}});Ov(t,gt,qe);let Me=wz(t,gt,qe,n.behaviorFocusLocations??[]);return gt.corridor=ax(gt,{focusLocations:Me}),qe})();return(()=>{let B=Av(t,gt,If,{sourceAllowed:T,selectionTerms:n.selectionTerms}),qe=tG(gt),Me=iG(i,o,s,c,l,u,n.fullLiteralTraversal??!1,a,pe,ce,Je,Ce,qe),Yn=rG(i,o,s,pe.filter(De=>qe.has(De.id)),Je,c,l,u,n.fullLiteralTraversal??!1,a);return{anchors:E,regions:pe,regionRelations:ce,externalBoundaries:Vl,boundaryFrontiers:Ue,unmatchedExpansions:pt,expansion:Yn,drilldown:$,presentation:Me,topology:gt,behavior:If,nextAnchors:B,closure:{status:Jl,emitted:{regions:pe.length,relations:ue.length,runtimeLinks:f.size},withheld:{symbols:Or,files:qs+Wn,regions:gt.nodes.filter(De=>De.kind==="structural-region"&&De.disposition==="folded").length,drillAnchors:($?.omittedAnchors??0)+B.omittedAnchors,literalMatches:C},ambiguous:{anchors:E.filter(De=>De.status==="ambiguous").length,omittedSymbolCandidates:b},external:Vl.length,unresolved:Ue.length,explanation:Jl==="accounted"?"Every fact reached under the declared anchors, relations, depth, evidence floor, source scopes, and installed analyzers is accounted for as emitted, withheld, ambiguous, external, or unresolved.":Rf.join("; ")},coverage:{explicitAnchorCount:E.length,requestedRelationKinds:c,evidenceFloor:l,includedSourceScopes:u,matchedAnchorCount:E.filter(De=>De.status!=="missing").length,literalSearchesComplete:!0,broadLiteralAnchors:v,withheldLiteralMatches:C,symbolCandidateSetsComplete:b===0,omittedSymbolCandidates:b,maxTraversalDepth:s,frontierSymbols:Or,frontierFiles:qs,supportFilesNotTraversed:Wn,filteredUnverifiedCallEdges:R,memberCallCandidateEdges:P,unresolvedMemberCallsites:w,runtimeBoundaryEvidenceAvailable:m!==null,runtimeBoundaryObservations:m?.observations.length??0,runtimeBoundaryExactLinks:Vn,runtimeBoundaryDerivedLinks:Jn,runtimeBoundaryCandidateLinks:Qi,repositoryRuntimeBoundaryExactLinks:gT,repositoryRuntimeBoundaryDerivedLinks:hT,repositoryRuntimeBoundaryCandidateLinks:yT,runtimeBoundaryTraversedLinks:f.size,runtimeBoundaryFrontiers:Ue.length,referenceExpansionEligibleSymbols:ne.filter(De=>De.referenceScope!=="none").length,referenceExpansionSkippedSymbols:ne.filter(De=>De.referenceScope==="none").length,dynamicDispatchRepresented:m?.links.some(De=>De.joinRule==="carrier.discriminator"&&f.has(De.id))??!1,runtimeGeneratedLinksRepresented:m!==null,regionBoundariesAreStructural:!0,relationFamilies:{"literal-anchor":{evidence:"exact-source",scope:"all indexed documents for each explicit literal",completeWithinScope:!0},reference:{evidence:"compiler-graph",scope:"all cross-file indexed/source-attributed sites for explicit anchors and promoted non-module boundary symbols",completeWithinScope:!0},call:{evidence:"mixed",scope:"static callees plus exact SCIP call occurrences in traversed source ranges, exact constructor-assigned member receivers, and uniquely attributed direct-import member candidates",completeWithinScope:!0},"contract-symbol":{evidence:"compiler-graph",scope:"explicit compiler references to type declarations; behavioral conformance is not inferred",completeWithinScope:!0},import:{evidence:"compiler-graph",scope:"all indexed or source-resolved imports of traversed primary files",completeWithinScope:!0},"runtime-boundary":{evidence:"exact-source",scope:"direct and mechanically derived links produced by grounded runtime adapters and factorized relation groups",completeWithinScope:!0}},blindSpots:Ef}}})()}function Xq(e,t){return e.startLine<=t.endLine&&e.endLine>=t.startLine}function Nx(e,t,n,r,i,o){let{db:s,addSymbol:a,addSourceConstruct:c}=e,l=$x(s,n,r);if(o==="local"&&l&&Xt(l)===Xt(ds(s,t)))return null;let u=l&&l.startColumn!==void 0&&l.endColumn!==void 0?Qr(s,n,D(s,n)).get(Xr({...l,startColumn:l.startColumn,endColumn:l.endColumn})):void 0;if(u&&!he(u.symbol))return a(u,i,`reverse-${o}-call-owner`,void 0,o==="local"?"forward-regions":"cross-workspace-or-forward",!0),{fromSymbol:u.symbol,fromSourceConstruct:void 0};if(!l)return null;let d=c(l,i,`reverse-${o}-call-source-owner`,void 0,!0);return d?{fromSymbol:null,fromSourceConstruct:Dt(d)}:null}function Qq(e,t,n){let{db:r,pendingRelations:i}=e,o=z(r,t.file);if((o?.callables??[]).filter(a=>a.name===t.name&&Xq(a,t)).length===1){let a=(o?.callSites??[]).filter(c=>c.calleeLeaf===t.name&&!c.memberAccess);for(let c of a){let l=Nx(e,t,t.file,c.line,n+1,"local");l&<(i,{kind:"call",evidence:"ast-callsite",fromFile:t.file,...l,toFile:t.file,toSymbol:null,toSourceConstruct:Dt(t),line:c.line,strength:"candidate"})}}}function Zq(e,t,n){let{db:r,reverseFileGraph:i,serviceCallerFilesBySourceConstruct:o,sourceAllowed:s,memberCallTargetsForWholeFile:a,pendingRelations:c}=e,l=new Set([...i.get(t.file)??[],...o.get(Xt(t))??[],...Rv(r,t.file).flatMap(u=>[...i.get(u)??[]])]);for(let u of l){if(!s(u))continue;let m=a(u).targets.filter(p=>p.targetFile===t.file&&p.targetStartLine<=t.endLine&&p.targetEndLine>=t.startLine);for(let p of m){let f=Nx(e,t,u,p.line,n+1,"member");f&<(c,{kind:"call",...Ax(p),fromFile:u,...f,toFile:t.file,toSymbol:null,toSourceConstruct:Dt(t),line:p.line})}}}function ez(e,t){let{relationPolicy:n,sourceConstructs:r,reverseExpandedSourceConstructs:i}=e;if(!n.has("call"))return;let o=[...r.values()].filter(s=>s.traversalEligible&&s.reverseCallExpansion&&s.depth<=t&&!i.has(Xt(s)));for(let s of o)i.add(Xt(s)),Qq(e,s,t),Zq(e,s,t)}function tz(e,t){let{db:n,index:r,sourceAllowed:i,files:o,workspaces:s,relationPolicy:a}=e;return Hx(n,r,t.definition).filter(c=>i(c.file)&&Ux(t,c.file,o,s)).flatMap(c=>{let l=c.enclosingSymbol?wr(n,r,c.enclosingSymbol).matches[0]:void 0,u={site:c,callEvidence:null,owner:l&&!he(l.symbol)?l:void 0},m=(c.compilerBound?po(n,c.file):null)?.targets.filter(f=>f.sourceLine===c.line&&f.definition.symbol===t.definition.symbol);return(m?m.map(f=>{let g=Ag(n,c.file,f);return{...u,sourceRange:g.sourceRange,owner:g.sourceDefinition??void 0,sourceOwner:g.sourceOwner??null}}):[u]).flatMap(f=>a.has("call")?nz(e,f,t.definition):[f])})}function nz(e,t,n){let{db:r,index:i,referenceCallFiles:o}=e,{site:s}=t;if(s.line===null)return[t];let a=o.get(s.file);a||(a={calls:wn(r,s.file,0,Number.MAX_SAFE_INTEGER),owners:Qr(r,s.file,i.definitionsForFile(s.file))},o.set(s.file,a));let{calls:c,owners:l}=a;if(c.available){let d=c.targets.filter(m=>m.sourceLine===s.line&&m.definition.symbol===n.symbol&&(!t.sourceRange||In(m.sourceRange,t.sourceRange)));return d.length>0?d.map(m=>Ix(t,"scip-occurrence-callsite",m.sourceOwner,l,m.implementationStatus)):[t]}if(s.compilerBound)return[t];let u=(z(r,s.file)?.callSites??[]).filter(d=>d.line===s.line&&Mz(r,s.file,d,n));return u.length>0?u.map(d=>Ix(t,"ast-callsite",d.owner,l)):[t]}function Ix(e,t,n,r,i){return{...e,callEvidence:{evidence:t,strength:t==="scip-occurrence-callsite"&&n!==void 0&&i!=="unresolved"?"exact":"candidate"},sourceOwner:n,owner:n===void 0?e.owner:r.get(Xr(n))}}function rz(e,t,n){let{db:r,workspaces:i}=e,o=vn(t.relativePath,i).relativeDir,s=n.flatMap(({callEvidence:l,owner:u})=>{if(!l||!u)return[];let d=vn(u.relativePath,i).relativeDir;return[{symbol:u.symbol,workspace:d,local:d===o,priority:Dz(r,u),span:u.endLine-u.startLine}]}).sort((l,u)=>Number(u.local)-Number(l.local)||u.priority-l.priority||l.span-u.span||l.symbol.localeCompare(u.symbol)),a=new Set,c=new Set;for(let l of s){if(a.size>=Bq)break;a.has(l.symbol)||c.has(l.workspace)||(a.add(l.symbol),c.add(l.workspace))}return a}function iz(e,t,n,r,i){let{db:o,addSymbol:s,addSourceConstruct:a}=e,{site:c,owner:l,callEvidence:u,sourceOwner:d}=n;if(l)return s(l,i+1,"reference-owner",void 0,u&&r.has(l.symbol)?t.referenceScope:"none"),{fromSymbol:l.symbol,fromSourceConstruct:void 0};let m=d===void 0?c.line===null?null:$x(o,c.file,c.line):d?{file:c.file,name:d.name??"<anonymous>",startLine:d.startLine,endLine:d.endLine,startColumn:d.startColumn,endColumn:d.endColumn}:null,p=m?a(m,i+1,"reference-source-owner",void 0,u!==null):null;return{fromSymbol:null,fromSourceConstruct:p?Dt(p):void 0}}function oz(e,t,n){let{relationPolicy:r,addFile:i,pendingRelations:o}=e;if(t.referenceScope==="none"||!r.has("call")&&!r.has("reference")&&!r.has("contract-symbol"))return;let s=tz(e,t),a=rz(e,t.definition,s);for(let c of s){let{site:l,callEvidence:u}=c;i(l.file,n+1,`reference:${L(t.definition.symbol)}`,!0);let d={fromFile:l.file,...iz(e,t,c,a,n),toFile:t.definition.relativePath,toSymbol:t.definition.symbol,line:l.line};r.has("reference")&<(o,{...d,kind:"reference",evidence:"indexed-or-source-reference",strength:"mixed"}),u&<(o,{...d,kind:"call",...u})}}function sz(e,t,n){if(t.referenceScope==="none"||!t.definition.isTypeLike||!e.relationPolicy.has("contract-symbol"))return;let{db:r,index:i,sourceAllowed:o,files:s,workspaces:a,addSymbol:c,addFile:l,pendingRelations:u}=e,d=Hx(r,i,t.definition).filter(m=>o(m.file)&&Ux(t,m.file,s,a));for(let m of new Set(d.map(p=>p.file))){let p=Qr(r,m,i.definitionsForFile(m)),f=fu(r,m,0,Number.MAX_SAFE_INTEGER);for(let g of f.targets){if(g.definition.symbol!==t.definition.symbol)continue;let h=g.sourceOwner?p.get(Xr(g.sourceOwner)):g.sourceDefinition??void 0;h&&c(h,n+1,"type-reference-owner",void 0,"none",!0),l(m,n+1,"type-reference",!0),lt(u,{kind:"contract-symbol",evidence:"scip-occurrence-type-reference",strength:"exact",fromFile:m,fromSymbol:h?.symbol??null,toFile:t.definition.relativePath,toSymbol:t.definition.symbol,line:g.sourceLine})}}}function az(e,t,n,r){let{db:i,index:o,sourceAllowed:s,fileGraph:a,traversalMetrics:c,addSymbol:l,pendingRelations:u}=e;for(let d of n){let m=wr(i,o,d.symbol).matches.find(f=>f.relativePath===d.file);if(!m||!s(m.relativePath))continue;if(!(m.relativePath===t.relativePath||(a.get(t.relativePath)??new Set).has(m.relativePath))){c.filteredUnverifiedCallEdges+=1;continue}l(m,r+1,`call:${L(t.symbol)}`,void 0,"none",!0),lt(u,{kind:"call",evidence:d.source,fromFile:t.relativePath,fromSymbol:t.symbol,toFile:m.relativePath,toSymbol:m.symbol,line:null,strength:ye(d.source)})}}function cz(e,t){let{index:n,relationPolicy:r,symbols:i}=e,o=[...i.values()].filter(a=>!a.processed&&a.depth<=t),s=r.has("call")?n.calleeMap(o.map(a=>a.definition),{additive:!1,semantic:!1}):new Map;for(let a of o)a.processed=!0,oz(e,a,t),sz(e,a,t),az(e,a.definition,s.get(a.definition.symbolId)??[],t)}function lz(e,t,n){let{db:r,sourceConstructs:i,symbols:o,boundaryObservations:s,boundaryObservationDepths:a}=e,c=[...i.values()].filter(y=>y.traversalEligible&&y.file===t.file&&y.depth<=n),l=[...o.values()].filter(y=>y.definition.relativePath===t.file&&y.depth<=n).map(y=>{let S=si(r,t.file,y.definition.startLine);return{startLine:S?.startLine??y.definition.startLine,endLine:S?.endLine??y.definition.endLine}}),u=y=>[...o.values()].filter(S=>S.definition.relativePath===t.file&&S.definition.startLine<=y&&S.definition.endLine>=y).sort((S,I)=>S.definition.endLine-S.definition.startLine-(I.definition.endLine-I.definition.startLine)||S.definition.startLine-I.definition.startLine)[0],d=Qr(r,t.file,[...o.values()].filter(y=>y.definition.relativePath===t.file).map(y=>y.definition)),m=[...s.values()].filter(y=>y.source.file===t.file&&a.has(y.id)),p=[...c.map(y=>({startLine:y.startLine,endLine:y.endLine})),...m.map(y=>({...Lx(r,y)}))],f=[...l,...p],g=(z(r,t.file)?.callSites??[]).filter(y=>f.some(S=>y.line>=S.startLine&&y.line<=S.endLine));return{state:t,traversalRanges:f,sourceOwnedCallsites:g,sourceRelationAtLine:(y,S)=>{let I=S===void 0?void 0:d.get(Xr(S)),x=S===void 0?u(y):I?o.get(I.symbol):void 0,E=c.find(v=>v.startLine<=y&&v.endLine>=y&&(S===void 0||S!==null&&v.startLine===S.startLine&&v.endLine===S.endLine&&v.startColumn===S.startColumn&&v.endColumn===S.endColumn)),b=m.find(v=>{let C=Lx(r,v);return C.startLine<=y&&C.endLine>=y});return{fromFile:t.file,fromSymbol:x?.definition.symbol??null,fromBoundaryParticipant:b?Kc(b):void 0,fromSourceConstruct:E?Dt(E):void 0}},compilerResolvedCallsiteKeys:new Set}}function Pm(e,t,n,r){let{db:i,relationPolicy:o}=e;if(!o.has(r))return;let{state:s,traversalRanges:a}=t;for(let c of a){let l=r==="call"?wn(i,s.file,c.startLine,c.endLine):r==="contract-symbol"?fu(i,s.file,c.startLine,c.endLine):Ng(i,s.file,c.startLine,c.endLine);for(let u of l.targets)uz(e,t,n,r,u)}}function uz(e,t,n,r,i){let{sourceAllowed:o,addSymbol:s,pendingRelations:a}=e,{state:c,sourceRelationAtLine:l,compilerResolvedCallsiteKeys:u}=t;if(!o(i.definition.relativePath))return;let d=`${i.sourceLine}\0${i.calleeLeaf}`;if(r==="reference"&&u.has(d))return;let m=l(i.sourceLine,i.sourceOwner);if(i.sourceDefinition!==void 0){if(i.sourceDefinition&&!e.symbols.has(i.sourceDefinition.symbol)&&!m.fromSourceConstruct)return;m.fromSymbol=i.sourceDefinition?.symbol??null}r==="reference"&&m.fromSymbol===i.definition.symbol||(s(i.definition,n+1,`scip-occurrence-${r}:${c.file}:${i.sourceLine+1}`,void 0,"none",!0),lt(a,{kind:r,evidence:r==="call"?"scip-occurrence-callsite":r==="contract-symbol"?"scip-occurrence-type-reference":"scip-occurrence-reference",...m,toFile:i.definition.relativePath,toSymbol:i.definition.symbol,line:i.sourceLine,strength:r==="call"&&(i.sourceOwner===void 0||i.implementationStatus==="unresolved")?"candidate":"exact"}),r==="call"&&u.add(d))}function dz(e,t,n){let{db:r,relationPolicy:i,traversalMetrics:o,pendingRelations:s}=e,{state:a,traversalRanges:c,compilerResolvedCallsiteKeys:l,sourceRelationAtLine:u}=t,d=i.has("call")?Qo(r,a.file,{ranges:c,excludeIndexedTargets:!1}):{targets:[],unresolvedCallsites:0};o.unresolvedMemberCallsites+=d.unresolvedCallsites;let m=d.targets.filter(p=>!l.has(`${p.line}\0${p.calleeLeaf}`));o.memberCallCandidateEdges+=m.filter(p=>p.strength!=="exact"&&(p.resolution!=="imported-service-object-member"||(p.resolutionAlternativeCount??0)>1)).length;for(let p of m){let{targetDefinition:f,targetConstruct:g}=mz(e,a.file,n,p);lt(s,{kind:"call",...Ax(p),...u(p.line),toFile:p.targetFile,toSymbol:f?.symbol??null,toSourceConstruct:g?Dt(g):void 0,line:p.line})}}function Ax(e){return{evidence:e.resolution==="constructed-member-receiver"?"ast-constructed-member-callsite":e.resolution==="factory-callback-member"?"ast-factory-callback-callsite":e.resolution==="imported-service-object-member"?"ast-service-member-callsite":"ast-member-import-candidate",strength:e.resolution==="imported-service-object-member"?(e.resolutionAlternativeCount??0)===1?"derived":"candidate":e.strength??"candidate"}}function mz(e,t,n,r){let{db:i,addSourceConstruct:o,serviceCallerFilesBySourceConstruct:s,reverseFileGraph:a,addSymbol:c}=e,l=(r.resolutionAlternativeCount??1)===1,u=r.targetSymbol?D(i,r.targetFile).find(m=>m.symbol===r.targetSymbol):void 0;if(u)return c(u,n+1,`member-call:${t}`,void 0,"none",!0),{targetDefinition:u,targetConstruct:null};let d=o({file:r.targetFile,name:r.calleeLeaf,startLine:r.targetStartLine,endLine:r.targetEndLine},n+1,`member-call:${t}`,void 0,r.resolution==="imported-service-object-member"&&l,l);if(d&&r.serviceFile){let m=Xt(d),p=s.get(m)??new Set;for(let f of a.get(r.serviceFile)??[])p.add(f);s.set(m,p)}return{targetDefinition:u,targetConstruct:d}}function pz(e,t,n){let{db:r,relationPolicy:i,externalImports:o,sourceAllowed:s,addFile:a,pendingRelations:c}=e,{state:l}=t;if(i.has("import"))for(let u of e.reverseFileGraph.get(l.file)??[])!s(u)||!Px(r,u).some(d=>d.fromFile===l.file)||(a(u,n+1,`reverse-import:${l.file}`,!1),lt(c,{kind:"import",evidence:"indexed-or-source-import",fromFile:u,fromSymbol:null,toFile:l.file,toSymbol:null,line:null,strength:"mixed"}));for(let u of i.has("import")||i.has("call")?Px(r,l.file):[]){if(!u.fromFile){if(i.has("import")){let m=o.get(u.shortName)??{name:u.shortName,fromFiles:new Set,unresolved:u.resolution==="unresolved"};m.fromFiles.add(l.file),o.set(u.shortName,m)}continue}if(!s(u.fromFile))continue;i.has("import")&&(a(u.fromFile,n+1,`import:${l.file}`,!1),lt(c,{kind:"import",evidence:"indexed-or-source-import",fromFile:l.file,fromSymbol:null,toFile:u.fromFile,toSymbol:u.symbol,line:null,strength:"mixed"}));let d={...u,fromFile:u.fromFile};fz(e,t,n,d),gz(e,t,n,d)}}function fz(e,t,n,r){let{db:i,index:o,relationPolicy:s,addSymbol:a,pendingRelations:c}=e,{state:l,sourceOwnedCallsites:u,sourceRelationAtLine:d}=t;if(po(i,l.file)===null&&s.has("call")&&u.length>0){let m=(r.source==="compiler"?wr(i,o,r.symbol).matches:En(i,r.fromFile,r.importedName)).filter(p=>!he(p.symbol));for(let p of m){let f=u.filter(g=>g.calleeLeaf===r.localName).map(g=>g.line);if(f.length!==0){a(p,n+1,`source-call:${l.file}`,void 0,"none",!0);for(let g of f)lt(c,{kind:"call",evidence:"ast-callsite",...d(g),toFile:p.relativePath,toSymbol:p.symbol,line:g,strength:"candidate"})}}}}function gz(e,t,n,r){let{db:i,index:o,addSymbol:s,workspaces:a}=e,{state:c}=t;if(!c.promoteBoundaryImports||!TG(c.file,r.fromFile,a))return;let l=r.source==="compiler"?wr(i,o,r.symbol).matches:En(i,r.fromFile,r.importedName);for(let u of l)if(LG(u.relativePath,r.fromFile,a)&&!he(u.symbol)){let d=vn(c.file,a).relativeDir!==vn(u.relativePath,a).relativeDir;s(u,n+1,`boundary-import:${c.file}`,void 0,d?"cross-workspace-or-forward":"forward-regions")}}function hz(e,t){let n=[...e.files.values()].filter(r=>!r.processed&&r.primary&&r.depth<=t);for(let r of n){r.processed=!0;let i=lz(e,r,t);Pm(e,i,t,"call"),Pm(e,i,t,"reference"),Pm(e,i,t,"contract-symbol"),dz(e,i,t),pz(e,i,t)}}function yz(e,t){let{relationPolicy:n,runtimeBoundaries:r}=e;for(let i of n.has("runtime-boundary")?r?.links??[]:[])bz(e,i,t)}function bz(e,t,n){let{boundaryObservations:r,sourceAllowed:i,boundaryObservationDepths:o,symbols:s,sourceConstructs:a}=e;if(!Sz(e,t))return;let c=r.get(t.from),l=r.get(t.to);if(!c||!l||!i(c.source.file)||!i(l.source.file))return;let u=Dx(c,n,o,s,a),d=Dx(l,n,o,s,a);u===null&&d===null||vz(e,t,c,l,u,d,n+1)}function Sz(e,t){return!(e.evidenceFloor==="exact"&&t.strength!=="exact")&&!e.representedBoundaryLinkIds.has(t.id)}function vz(e,t,n,r,i,o,s){let{addBoundaryObservation:a,sourceConstructs:c,boundaryObservationDepths:l,pendingRelations:u,representedBoundaryLinkIds:d}=e,m=a(n,i??s,`runtime-boundary:${t.joinRule}`),p=a(r,o??s,`runtime-boundary:${t.joinRule}`),f=m?null:Mx(c,n),g=p?null:Mx(c,r);l.set(n.id,i??s),l.set(r.id,o??s),lt(u,{kind:"runtime-boundary",evidence:`runtime-boundary:${t.joinRule}`,fromFile:n.source.file,fromSymbol:m,toFile:r.source.file,toSymbol:p,fromBoundaryParticipant:Kc(n),toBoundaryParticipant:Kc(r),fromSourceConstruct:f?Dt(f):void 0,toSourceConstruct:g?Dt(g):void 0,runtimeBoundaryKey:t.matchedKeyParts.map(h=>`${h.name}=${h.value}`).join(" "),line:n.source.startLine,strength:t.strength}),d.add(t.id)}function Cz(e,t,n){let r=Ee(t.searches??[]),i=Ee(t.symbols??[]),o=xz(t.relations),s=new Set(o),a=Rz(t.evidenceFloor),c=Ez(t.sourceScopes),l=new Set(c),u=ne=>l.has(vu(ne));if(r.length===0&&i.length===0)throw new Error("system-map requires at least one --search or --symbol anchor.");let{maxDepth:d,maxTopologyCharacters:m}=Iz(t),p=new N(e),{fileGraph:f,reverseFileGraph:g,workspaces:h,runtimeBoundaries:y}=DG(e,p),S=new Map((y?.observations??[]).map(ne=>[ne.id,ne])),I=new Set((y?.observations??[]).map(ne=>`${ne.source.file}\0${ne.source.startLine}`)),x=new Set,E=new Map,b=new Map,v=new Map,C=new Map,R=[],P=new Map,w=new Map,T=[],G={filteredUnverifiedCallEdges:0,memberCallCandidateEdges:0,unresolvedMemberCallsites:0},K=new Set,ue=new Map,ce=new Map,Ce=ne=>{let ft=ce.get(ne);if(ft)return ft;let Ue=Qo(e,ne,{excludeIndexedTargets:!1});return ce.set(ne,Ue),Ue},pe=(ne,ft,Ue,Vn,Jn=!1)=>Hq(b,ne,ft,Ue,Vn,Jn),Je=(ne,ft,Ue,Vn,Jn="none",Qi=!1)=>Uq(v,pe,ne,ft,Ue,Vn,Jn,Qi),$=(ne,ft,Ue,Vn,Jn=!1,Qi=!0)=>qq(C,pe,ne,ft,Ue,Vn,Jn,Qi),U=(ne,ft,Ue)=>zq({db:e,index:p,pendingRelations:P,addFile:pe,addSymbol:Je,addSourceConstruct:$,observation:ne,depth:ft,origin:Ue}),{omittedSymbolCandidates:pt,broadLiteralAnchors:Or,withheldLiteralMatches:qs}=Gq({db:e,index:p,searches:r,symbolQueries:i,opts:t,boundaryObservationLocations:I,sourceAllowed:u,addFile:pe,addSymbol:Je,addSourceConstruct:$,literalHits:R,anchors:T}),Wn={db:e,index:p,relationPolicy:s,evidenceFloor:a,sourceAllowed:u,fileGraph:f,reverseFileGraph:g,workspaces:h,runtimeBoundaries:y,boundaryObservations:S,boundaryObservationDepths:E,representedBoundaryLinkIds:x,files:b,symbols:v,sourceConstructs:C,pendingRelations:P,externalImports:w,reverseExpandedSourceConstructs:K,serviceCallerFilesBySourceConstruct:ue,referenceCallFiles:new Map,traversalMetrics:G,memberCallTargetsForWholeFile:Ce,addFile:pe,addSymbol:Je,addSourceConstruct:$,addBoundaryObservation:U};for(let ne=0;ne<d;ne+=1)ez(Wn,ne),cz(Wn,ne),hz(Wn,ne),yz(Wn,ne);return Yq({db:e,opts:t,mode:n,searches:r,symbolQueries:i,maxDepth:d,maxTopologyCharacters:m,requestedRelationKinds:o,evidenceFloor:a,includedSourceScopes:c,workspaces:h,runtimeBoundaries:y,boundaryObservations:S,representedBoundaryLinkIds:x,files:b,symbols:v,sourceConstructs:C,literalHits:R,pendingRelations:P,externalImports:w,anchors:T,omittedSymbolCandidates:pt,broadLiteralAnchors:Or,withheldLiteralMatches:qs,filteredUnverifiedCallEdges:G.filteredUnverifiedCallEdges,memberCallCandidateEdges:G.memberCallCandidateEdges,unresolvedMemberCallsites:G.unresolvedMemberCallsites,sourceAllowed:u})}function xz(e){let t=Ee(e&&e.length>0?e:Rx),n=t.filter(r=>!Rx.includes(r));if(n.length>0)throw new Error(`Unsupported system-map relation kind(s): ${n.join(", ")}`);return t}function Rz(e){let t=e??"derived";if(t!=="exact"&&t!=="derived")throw new Error(`Unsupported system-map evidence floor: ${t}`);return t}function Ez(e){let t=Ee(e&&e.length>0?e:["production"]),n=["production","test","fixture","example","generated","script","unknown"],r=t.filter(i=>!n.includes(i));if(r.length>0)throw new Error(`Unsupported system-map source scope(s): ${r.join(", ")}`);return t}function Iz(e){let t=e.maxDepth??Dq;if(!Number.isSafeInteger(t)||t<0)throw new RangeError(`maxDepth must be a non-negative safe integer; received ${t}`);let n=e.maxTopologyCharacters??jq;if(!Number.isSafeInteger(n)||n<=0)throw new RangeError(`maxTopologyCharacters must be a positive safe integer; received ${n}`);return{maxDepth:t,maxTopologyCharacters:n}}function wz(e,t,n,r){let i=new Map,o=c=>{i.set(`${c.file}\0${c.line}`,c)};for(let c of r)o(c);let s=new Set(t.anchors.filter(c=>c.status==="matched").flatMap(c=>c.nodeIds));Pz(n,s,o);let a=t.edges.filter(c=>c.disposition==="emitted").flatMap(c=>c.evidence.flatMap(l=>l.location?[l.location]:[]));for(let c of a)o(c),Tz(e,t,c,o);return[...i.values()].sort((c,l)=>c.file.localeCompare(l.file)||c.line-l.line)}function Pz(e,t,n){for(let r of e.steps)if(!(!r.location||!t.has(r.nodeId)||(r.behavior?.rawCharacters??1/0)>3e3))for(let i of r.behavior?.lines??[])i.signals.some(o=>$q.has(o))&&n({file:r.location.file,line:i.line,endLine:i.endLine})}function Tz(e,t,n,r){let i=t.nodes.filter(s=>s.location?.file===n.file&&["symbol","source-construct","runtime-boundary-participant"].includes(s.kind)&&s.location.line<=n.line&&(s.location.endLine??s.location.line)>=n.line).sort((s,a)=>(s.location.endLine??s.location.line)-s.location.line-((a.location.endLine??a.location.line)-a.location.line)||s.id.localeCompare(a.id))[0];if(!i?.location)return;let o=Aa(e,n.file,i.location.line,i.location.endLine??i.location.line,[n.line]);for(let s of o)r({file:n.file,line:s.line,endLine:s.endLine})}function Lz(e){if(e.ownerStartLine===null||e.ownerStartLine===void 0)throw new Error(`Literal hit ${e.file}:${e.line+1} has no source-owner start line.`);if(e.ownerEndLine===null||e.ownerEndLine===void 0)throw new Error(`Literal hit ${e.file}:${e.line+1} has no source-owner end line.`);return{file:e.file,name:e.ownerShortName??`${e.file}:${e.ownerStartLine+1}`,startLine:e.ownerStartLine,endLine:e.ownerEndLine,startColumn:e.ownerStartColumn,endColumn:e.ownerEndColumn}}function Xt(e){return`${e.file}\0${e.startLine}\0${e.endLine}\0${e.name}\0${e.startColumn??""}\0${e.endColumn??""}`}function Dt(e){return{file:e.file,name:e.name,startLine:e.startLine,endLine:e.endLine,...e.startColumn===void 0?{}:{startColumn:e.startColumn,endColumn:e.endColumn}}}function Mz(e,t,n,r){if(n.calleeLeaf===r.leaf)return!0;let i=dg(e,t,n.calleeLeaf);return i!==null&&i.importedName===r.leaf&&i.sourcePath!==null&&ze(i.sourcePath,r.relativePath)}function ds(e,t){if(t.startColumn!==void 0&&t.endColumn!==void 0)return Dt(t);let n=(z(e,t.file)?.callables??[]).filter(a=>a.startLine<=t.startLine&&a.endLine>=t.endLine),r=n.filter(a=>a.name===t.name),i=r.length>0?r:n;if(i.length>1)return Dt(t);let o=i.length===1?i[0]:void 0;if(o&&o.endLine>=t.endLine)return{file:t.file,name:/^source@\d+$/u.test(o.name)&&!/^source@\d+$/u.test(t.name)?t.name:o.name,startLine:o.startLine,endLine:o.endLine,startColumn:o.startColumn,endColumn:o.endColumn};let s=jx(e,t.file,t.startLine);return s&&s.endLine>=t.endLine?{file:t.file,name:s.name,startLine:s.startLine,endLine:s.endLine}:Dt(t)}function Ai(e){return Be("source-construct",e.file,String(e.startLine),String(e.endLine),e.name,...e.startColumn===void 0?[]:[String(e.startColumn),String(e.endColumn)])}function zc(e,t){let n=bi(e,t.symbol,t.relativePath),r=new Set(["package-surface-file","transitive-package-surface"]),i=n.filter(s=>!r.has(s)||Pt(e,t)),o=i.some(s=>!r.has(s));return{evidence:i,priority:o||zS(e,t.symbol,t.relativePath)?2:1}}function Dz(e,t){let n=zc(e,t);return n.evidence.length>0?n.priority:0}function Fz(e,t){let n=D(e,t.file),r=n.filter(i=>i.startLine<=t.startLine&&i.endLine>=t.startLine).sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine)||i.startLine-o.startLine);for(let i of r){let o=zc(e,i);if(o.evidence.length>0)return o}for(let i of Nz(e,t.file,t.startLine)){let o=n.filter(s=>s.leaf===i.name).sort((s,a)=>Math.abs(s.startLine-i.startLine)-Math.abs(a.startLine-i.startLine)||s.symbol.localeCompare(a.symbol));for(let s of o){let a=zc(e,s);if(a.evidence.length>0)return a}return{evidence:[],priority:0}}return{evidence:[],priority:0}}var kz=new Set(["variable_declarator","function_declaration","generator_function_declaration","class_declaration"]);function Nz(e,t,n){let r=_(e,t)?.rootNode;if(!r||r.startPosition.row>n||r.endPosition.row<n)return[];let i=[],o=(z(e,t)?.callables??[]).filter(a=>a.startLine<=n&&a.endLine>=n);if(o.length>0&&!co(o,n))return[];let s=Dm(r,n);for(;s;){if(kz.has(s.type)){let a=s.childForFieldName("name")??s.namedChild(0);(a?.type==="identifier"||a?.type==="type_identifier")&&i.push({name:a.text,startLine:s.startPosition.row})}s=s.parent}return i}function Az(e){return[...new Map([...e.sourceConstructStates.values()].map(t=>ds(e.db,t)).map(t=>[Xt(t),t])).values()].sort((t,n)=>t.file.localeCompare(n.file)||t.startLine-n.startLine||t.endLine-n.endLine)}function _z(e,t){return e.anchors.map((n,r)=>{let i=Be("anchor",String(r),n.kind,n.query),o=[...e.symbolStates.values()].filter(u=>u.anchorQueries.has(n.query)).flatMap(u=>{if(!he(u.definition.symbol))return[Sn(u.definition.symbol)];let d=t.filter(m=>m.file===u.definition.relativePath).map(m=>Ai(m));return[Sn(u.definition.symbol),...d]}),s=[...e.sourceConstructStates.values()].filter(u=>u.anchorQueries.has(n.query)).map(u=>Ai(ds(e.db,u))),a=e.literalHits.filter(u=>u.query===n.query&&u.traversalSeed===!0&&u.ownerSymbol&&e.symbolStates.has(u.ownerSymbol)).map(u=>Sn(u.ownerSymbol)),c=e.literalHits.filter(u=>u.query===n.query&&u.traversalSeed===!0&&!u.ownerSymbol&&u.ownerStartLine!==null&&u.ownerStartLine!==void 0&&u.ownerEndLine!==null&&u.ownerEndLine!==void 0).map(u=>Ai(ds(e.db,Lz(u)))),l=re(n.kind==="symbol"?[...o,...s]:a.length+c.length>0?[...a,...c]:n.seedRegionIds??[]);return{id:i,kind:n.kind,query:n.query,status:n.status,nodeIds:n.status==="ambiguous"?[]:l,candidateNodeIds:n.status==="ambiguous"?l:[],omittedCandidates:n.omittedSymbolCandidates??0}})}function Oz(e){let t=new Map;for(let n of e)for(let r of[...n.nodeIds,...n.candidateNodeIds]){let i=t.get(r)??[];i.push(n.id),t.set(r,i)}return t}function Bz(e,t,n){let r=e.relations.flatMap(a=>[a.fromBoundaryParticipant,a.toBoundaryParticipant].flatMap(c=>c?.ownerName?[c]:[])),i=e.regions.map(a=>({id:a.id,kind:"structural-region",label:a.label,disposition:"folded",location:null,anchorIds:re(n.get(a.id)??[]),attributes:{workspace:a.workspace,structuralPath:a.structuralPath,minimumDepth:a.minDepth,files:a.fileCount,symbols:a.symbolCount,expanded:a.expanded}}));for(let a of e.symbolStates.values())i.push(jz(e,a,n));for(let a of t)i.push(Hz(e,a,n,r));let o=new Set(i.map(a=>a.id));for(let a of $z(e)){let c=Ni(e,a);o.has(c)||i.push({id:c,kind:"file",label:a,disposition:"folded",location:{file:a,line:0},anchorIds:[],attributes:{regionId:e.regionForFile.get(a)?.id??""}})}let s=new Map;for(let a of e.relations)a.fromBoundaryParticipant&&s.set(a.fromBoundaryParticipant.observationId,a.fromBoundaryParticipant),a.toBoundaryParticipant&&s.set(a.toBoundaryParticipant.observationId,a.toBoundaryParticipant);for(let a of[...s.values()].sort((c,l)=>c.observationId.localeCompare(l.observationId)))i.push(Uz(e,a));return i}function $z(e){return re([...e.relations.filter(t=>t.kind==="import").flatMap(t=>[t.fromFile,t.toFile]),...e.externalBoundaries.flatMap(t=>t.fromFiles)])}function Ni(e,t){let n=D(e.db,t).filter(r=>he(r.symbol));return n.length===1?Sn(n[0].symbol):Be("file",t)}function jz(e,t,n){let r=e.regionForFile.get(t.definition.relativePath)?.id;if(!r)throw new Error(`System-map symbol ${t.definition.symbol} has no structural region.`);let i=Sn(t.definition.symbol),o=zc(e.db,t.definition),s=bg(e.db,t.definition.relativePath,t.definition);return{id:i,kind:"symbol",label:L(t.definition.symbol),disposition:(n.get(i)?.length??0)>0?"emitted":"folded",location:{file:t.definition.relativePath,line:s?.startLine??t.definition.startLine,endLine:s?.endLine??t.definition.endLine,...s?.startColumn===void 0?{}:{startColumn:s.startColumn,endColumn:s.endColumn}},anchorIds:re(n.get(i)??[]),attributes:{regionId:r,depth:t.depth,leaf:t.definition.leaf??L(t.definition.symbol),referenceScope:t.referenceScope,...o.evidence.length>0?{publicEntry:!0,publicEntryPriority:o.priority,publicEntryEvidence:o.evidence.join(",")}:{}}}}function Hz(e,t,n,r){let i=e.regionForFile.get(t.file)?.id;if(!i)throw new Error(`Source construct ${t.name} has no structural region.`);let o=Ai(t),a=r.find(l=>l.file===t.file&&l.line>=t.startLine&&l.line<=t.endLine)?.ownerName??t.name,c=Fz(e.db,t);return{id:o,kind:"source-construct",label:a,disposition:(n.get(o)?.length??0)>0?"emitted":"folded",location:{file:t.file,line:t.startLine,endLine:t.endLine,...t.startColumn===void 0?{}:{startColumn:t.startColumn,endColumn:t.endColumn}},anchorIds:re(n.get(o)??[]),attributes:{regionId:i,leaf:a,sourceOwned:!0,...c.evidence.length>0?{publicEntry:!0,publicEntryPriority:c.priority,publicEntryEvidence:c.evidence.join(",")}:{}}}}function Uz(e,t){let n=e.regionForFile.get(t.file)?.id;if(!n)throw new Error(`Runtime-boundary participant ${t.observationId} has no structural region.`);return{id:Fm(t.observationId),kind:"runtime-boundary-participant",label:t.address||t.ownerName||`${t.role} ${t.action}`,disposition:"folded",location:{file:t.file,line:t.line,endLine:t.endLine},anchorIds:[],attributes:{regionId:n,action:t.action,protocol:t.protocol,role:t.role,...t.address?{address:t.address}:{},ownerSymbol:t.ownerSymbol}}}function qz(e,t,n,r,i,o,s,a,c,l=!1){let u=Tm(t,r?Sn(r):null);if(u&&!he(r))return u;let d=Tm(t,i?Fm(i.observationId):null);if(l&&d)return d;let m=zz(e,t,o);return m||d||Gz(n,a,c,u,s)}function zz(e,t,n){return Tm(t,n?Ai(ds(e,n)):null)}function Tm(e,t){return t&&e.has(t)?t:null}function Gz(e,t,n,r,i){let o=n===null?null:(e.get(t)??[]).filter(s=>s.startLine<=n&&s.endLine>=n).sort((s,a)=>s.endLine-s.startLine-(a.endLine-a.startLine)||s.startLine-a.startLine)[0]??null;return o?Ai(o):r??i}function Kz(e,t,n){let r=new Set(t.map(u=>u.id)),i=Te(n,u=>u.file),o=(u,d,m,p,f,g,h=!1)=>qz(e.db,r,i,u,d,m,p,f,g,h),s=[];KG(e,s);let a=Te(e.relations,u=>`${u.kind==="import"?Ni(e,u.fromFile):o(u.fromSymbol,u.fromBoundaryParticipant,u.fromSourceConstruct,u.fromRegionId,u.fromFile,u.line,u.kind==="runtime-boundary")}\0${u.kind==="import"?Ni(e,u.toFile):o(u.toSymbol,u.toBoundaryParticipant,u.toSourceConstruct,u.toRegionId,u.toFile,null)}\0${u.kind}`),c=new Set,l=u=>{if(u.kind==="runtime-boundary"&&u.fromBoundaryParticipant){let d=Fm(u.fromBoundaryParticipant.observationId),m=o(u.fromSymbol,void 0,u.fromSourceConstruct,u.fromRegionId,u.fromFile,u.line);m!==d&&!c.has(d)&&(c.add(d),s.push({id:Be("edge","boundary-observation",m,d),kind:"boundary-observation",fromNodeId:m,toNodeId:d,directed:!0,disposition:"folded",semantics:Mc("boundary-observation"),evidence:[{method:"runtime-boundary-observation-owner",strength:u.strength??"unknown",identity:u.fromBoundaryParticipant.observationId,location:{file:u.fromBoundaryParticipant.file,line:u.fromBoundaryParticipant.line,endLine:u.fromBoundaryParticipant.endLine}}]}))}};for(let u of a.values()){let d=u[0],m=d.kind==="import"?Ni(e,d.fromFile):o(d.fromSymbol,d.fromBoundaryParticipant,d.fromSourceConstruct,d.fromRegionId,d.fromFile,d.line,d.kind==="runtime-boundary"),p=d.kind==="import"?Ni(e,d.toFile):o(d.toSymbol,d.toBoundaryParticipant,d.toSourceConstruct,d.toRegionId,d.toFile,null);l(d),(m===p?t.find(g=>g.id===m):null)?.kind!=="structural-region"&&s.push({id:Be("edge",d.kind,m,p),kind:d.kind,fromNodeId:m,toNodeId:p,directed:!0,disposition:"folded",semantics:vC(d),evidence:nG(u.map(g=>({method:g.evidence,strength:g.strength??"unknown",identity:g.kind==="runtime-boundary"&&g.runtimeBoundaryKey?g.runtimeBoundaryKey:`${g.fromSymbol??g.fromFile} -> ${g.toSymbol??g.toFile}`,location:g.line===null?null:{file:g.fromFile,line:g.line}})))})}return s}function Wz(e,t,n){let r=[];for(let i of e.externalBoundaries){let o=Be("external",i.kind,i.name),s=re(i.fromFiles.map(a=>Ni(e,a)));t.push({id:o,kind:i.kind,label:i.name,disposition:i.kind==="unresolved-import"?"unsupported":"folded",location:null,anchorIds:[],attributes:{}}),i.kind==="unresolved-import"&&r.push({id:Be("frontier",i.kind,i.name,...s),kind:"import",direction:"outgoing",fromNodeIds:s,edgeIds:s.map(a=>Be("edge",i.kind,a,o)),memberNodeIds:[o],memberCount:1,disposition:"unsupported",reason:`Module reference ${i.name} has no resolved repository target; missing or dynamic imports cannot establish dependency completeness.`,expansion:null});for(let a of s)n.push({id:Be("edge",i.kind,a,o),kind:i.kind,fromNodeId:a,toNodeId:o,directed:!0,disposition:i.kind==="unresolved-import"?"unsupported":"folded",semantics:i.kind==="unresolved-import"?[{family:"identity",subtype:"imports-unresolved"}]:Mc("external-import"),evidence:[{method:"indexed-or-source-import",strength:"mixed",identity:`${a} -> ${i.name}`,location:null}]})}return e.boundaryFrontiers.forEach((i,o)=>{let s=e.regionForFile.get(i.file)?.id;if(!s)throw new Error(`Runtime-boundary frontier ${i.observationId} has no system-map region.`);let a=Be("unsupported","runtime-boundary",i.observationId,String(o)),c=Be("edge","runtime-boundary-frontier",s,a);t.push({id:a,kind:"runtime-boundary-frontier",label:i.address,disposition:"unsupported",location:{file:i.file,line:i.line},anchorIds:[],attributes:{action:i.action,strength:i.strength,owner:i.ownerShortName}}),n.push({id:c,kind:"runtime-boundary-frontier",fromNodeId:s,toNodeId:a,directed:!0,disposition:"unsupported",evidence:[{method:"runtime-boundary-extractor",strength:i.strength,identity:i.observationId,location:{file:i.file,line:i.line}}]}),r.push({id:Be("frontier","runtime-boundary",i.observationId,String(o)),kind:"runtime-boundary",direction:"unresolved",fromNodeIds:[s],edgeIds:[c],memberNodeIds:[a],memberCount:1,disposition:"unsupported",reason:i.reason,expansion:null})}),r}function Vz(e,t){let n=t.topologyFrontiers.some(g=>g==="frontier:program-facts"),r=yx(e,{expandedFrontierIds:t.topologyFrontiers.filter(g=>g!=="frontier:program-facts"),routeIds:t.routeIds}),i=r.nodes.filter(g=>g.disposition==="emitted"||r.anchors.some(h=>h.status==="matched"&&h.nodeIds.includes(g.id))),o=t.relations.filter(g=>i.some(h=>Yz(g,h))),s=t.boundaryFrontiers.filter(g=>i.some(h=>Qz(g,h))),a=qC(t.db,o,i),c=VC(t.db,i),l=WC(t.db,i),u=nx(t.db,i,s),d=[...a.nodes,...c.nodes,...l.nodes,...u.nodes].map(g=>n&&g.disposition==="folded"?{...g,disposition:"emitted"}:g),m=[...a.edges,...c.edges,...l.edges,...u.edges].map(g=>n&&g.disposition==="folded"?{...g,disposition:"emitted"}:g),p=n?null:Zz(i,d,m),f=qc({anchors:r.anchors,nodes:[...r.nodes,...d],edges:[...r.edges,...m],paths:r.paths,frontiers:[...r.frontiers,...a.frontiers,...c.frontiers,...l.frontiers,...u.frontiers,...p?[p]:[]],scope:r.coverage.scope,blindSpots:[...r.coverage.blindSpots,...a.blindSpots,...c.blindSpots,...u.blindSpots],incompleteReasons:r.coverage.status==="incomplete"?[r.coverage.explanation]:[],...r.routeCatalog?{routeCatalog:r.routeCatalog}:{}});f.completion=r.completion;for(let g of f.frontiers)g.disposition==="folded"&&(g.id.startsWith("frontier:program-facts:")||(g.expansion=eG(t,g.id)));return f}function _x(e,t){return[...e.filter(n=>n.status==="missing").map(n=>`${n.kind} selector ${JSON.stringify(n.query)} is ${n.status}`),...t>0?[`${t} ambiguous symbol candidate(s) were omitted`]:[]]}function Jz(e){let t=Az(e),n=_z(e,t),r=Bz(e,t,Oz(n)),i=Kz(e,r,t),o=Wz(e,r,i);return Vz(qc({anchors:n,nodes:r,edges:i,paths:[],frontiers:o,scope:`explicit anchors; relations ${e.requestedRelationKinds.join(", ")}; depth ${e.maxDepth}; evidence floor ${e.evidenceFloor}; source scopes ${e.includedSourceScopes.join(", ")}`,blindSpots:[...e.blindSpots],incompleteReasons:_x(e.anchors,e.omittedSymbolCandidates)}),e)}function Yz(e,t){return e.fromSymbol&&t.id===Sn(e.fromSymbol)||e.toSymbol&&t.id===Sn(e.toSymbol)?!0:t.location?Xz(e,t.location):!1}function Xz(e,t){let n=t.endLine??t.line;return t.file===e.fromFile&&e.line!==null&&e.line>=t.line&&e.line<=n||t.file===e.toFile}function Qz(e,t){if(!t.location||t.location.file!==e.file)return!1;let n=t.location.endLine??t.location.line;return e.line>=t.location.line&&e.line<=n||t.label===e.ownerShortName||typeof e.ownerShortName=="string"&&t.label.includes(e.ownerShortName)}function Zz(e,t,n){let r=re(t.filter(o=>o.disposition==="folded").map(o=>o.id)),i=re(n.filter(o=>o.disposition==="folded").map(o=>o.id));return r.length===0&&i.length===0?null:{id:Be("frontier","program-facts"),kind:"program-facts",direction:"outgoing",fromNodeIds:re(e.map(o=>o.id)),edgeIds:i,memberNodeIds:r,memberCount:r.length,disposition:"folded",reason:"Control, data, state, and temporal facts are folded beneath the selected high-level owners.",expansion:null}}function eG(e,t){return`scip-query system-map ${[...e.anchors.flatMap(r=>r.kind==="literal"?[`--search ${O(r.query)}`]:[`--symbol ${O(r.query)}`]),`--depth ${e.maxDepth}`,...e.requestedRelationKinds.map(r=>`--relation ${O(r)}`),`--evidence-floor ${O(e.evidenceFloor)}`,...e.includedSourceScopes.map(r=>`--source-scope ${O(r)}`),...e.fullLiteralTraversal?["--full-literal-traversal"]:[],`--topology-characters ${e.maxTopologyCharacters}`,...e.expandedRegionIds.map(r=>`--expand ${O(r)}`),...e.topologyFrontiers.map(r=>`--frontier ${O(r)}`),...e.routeIds.map(r=>`--route ${O(r)}`),`--frontier ${O(t)}`].join(" ")}`}function tG(e){let t=new Set;for(let n of e.nodes){if(n.disposition!=="emitted")continue;n.kind==="structural-region"&&t.add(n.id);let r=n.attributes.regionId;typeof r=="string"&&t.add(r)}return t}function nG(e){let t=new Map;for(let n of e){let r=n.location?`${n.location.file}:${n.location.line}`:"";t.set(`${n.method}\0${n.strength}\0${n.identity??""}\0${r}`,n)}return[...t.values()].sort((n,r)=>n.method.localeCompare(r.method)||(n.identity??"").localeCompare(r.identity??"")||(n.location?.file??"").localeCompare(r.location?.file??"")||(n.location?.line??0)-(r.location?.line??0))}function Be(...e){return e.map(t=>encodeURIComponent(t)).join(":")}function Sn(e){return Be("symbol",e)}function rG(e,t,n,r,i,o,s,a,c,l){let u=[...r].sort((g,h)=>Bx(g,h,i)),m=u.slice(0,xx).map(g=>g.id),p=u.slice(xx).map(g=>g.id),f=[...e.map(g=>`--search ${O(g)}`),...t.map(g=>`--symbol ${O(g)}`),`--depth ${n}`,...o.map(g=>`--relation ${O(g)}`),`--evidence-floor ${O(s)}`,...a.map(g=>`--source-scope ${O(g)}`),...c?["--full-literal-traversal"]:[],`--topology-characters ${l}`,...m.map(g=>`--expand ${O(g)}`)];return{command:m.length===0?null:`scip-query system-map ${f.join(" ")}`,regionCount:m.length,regionIds:m,candidateRegionCount:r.length,omittedRegionIds:p}}function iG(e,t,n,r,i,o,s,a,c,l,u,d,m){let p=[...c].sort((w,T)=>Bx(w,T,u)).filter(w=>!m||m.has(w.id)||d.has(w.id)),f=l.length>0?Math.floor(a*.4):0,g=a-f,h=WG(p,d,g),{selectedRegionIds:y}=h,S=h.estimatedCharacters,I=l.filter(w=>y.has(w.fromRegionId)&&y.has(w.toRegionId)).sort(oG),x=[];for(let w of I){let T=wx(w);x.length>0&&S+T>a||(x.push(Gc(w)),S+=T)}let E=c.filter(w=>!y.has(w.id)).map(w=>w.id).sort(),b=new Set(x),v=l.filter(w=>!b.has(Gc(w))).length,C=c.reduce((w,T)=>w+Ox(T),0)+l.reduce((w,T)=>w+wx(T),0),R=p.every(w=>y.has(w.id))&&x.length===I.length,P=[...e.map(w=>`--search ${O(w)}`),...t.map(w=>`--symbol ${O(w)}`),`--depth ${n}`,...r.map(w=>`--relation ${O(w)}`),`--evidence-floor ${O(i)}`,...o.map(w=>`--source-scope ${O(w)}`),...s?["--full-literal-traversal"]:[],`--topology-characters ${Math.max(a,C)}`];return{maxCharacters:a,estimatedCharacters:S,totalEstimatedCharacters:C,regionIds:[...y],omittedRegionIds:E,relationKeys:x,omittedRelations:v,complete:R,expansionCommand:R?null:`scip-query system-map ${P.join(" ")}`}}function Ox(e){return 120+e.id.length+e.anchorQueries.join(",").length+e.relationKinds.join(",").length+e.notableSymbols.slice(0,2).reduce((t,n)=>t+n.shortName.length+n.file.length,0)}function wx(e){return 70+e.fromRegionId.length+e.toRegionId.length+e.kinds.join(",").length+e.evidence.join(",").length}function oG(e,t){let n=r=>r.kinds.includes("runtime-boundary")?0:r.kinds.includes("contract-symbol")?1:2;return n(e)-n(t)||t.relationCount-e.relationCount||Gc(e).localeCompare(Gc(t))}function Gc(e){return`${e.fromRegionId}\0${e.toRegionId}`}function Bx(e,t,n){let r=a=>n.has(a.id)?0:1,i=a=>a.sourceFileCount===0?1:0,o=a=>a.symbolCount+a.literalHitCount>0?0:1,s=a=>[...a.incomingRegionIds,...a.outgoingRegionIds].filter(c=>n.has(c)).length;return r(e)-r(t)||o(e)-o(t)||i(e)-i(t)||e.minDepth-t.minDepth||s(t)-s(e)||t.literalHitCount-e.literalHitCount||e.testFileCount-t.testFileCount||e.label.localeCompare(t.label)}function sG(e){let t=[],n=new Set;for(let i of e.filter(o=>o.expanded))VG(i,t,n);let r=aG(t,n);return{command:r.length===0?null:`scip-query inspect ${r.map(i=>`--at ${O(`${i.file}:${i.line+1}`)}`).join(" ")} --view behavior`,definitionCommand:null,candidateAnchors:t.length,selectedAnchors:r.length,omittedAnchors:t.length-r.length,anchors:r}}function aG(e,t){let n=[...Te(e,s=>s.regionId).values()],r=[],i=new Set,o=Math.min(Oq,24);for(let s of e)if(!(!t.has(s.file)||i.has(s.file))&&(r.push(s),i.add(s.file),r.length===o))return r;return JG(n,r,i,o),r}function cG(e,t,n,r){let i=a=>a.kind==="test"?2:a.kind==="barrel"?1:0,o=a=>(r.get(a.file)??[]).some(c=>c.traversalSeed)?0:1,s=a=>{let c=n.get(a.file)??[];return Math.min(5,...c.map(l=>Ci(l.origins)))};return i(e)-i(t)||o(e)-o(t)||s(e)-s(t)||e.depth-t.depth||e.file.localeCompare(t.file)}function lG(e,t,n,r){let i=[];for(let o of q(e,{includeIgnored:!1}))uG(e,t,o,n,r,i);return i}function uG(e,t,n,r,i,o){let s=j(e,n);if(s.length===0)return;let a=[];for(let d=0;d<s.length;d+=1){let m=s[d]??"";m.includes(r)&&a.push({line:d,sourceLine:m})}if(a.length===0)return;let c=t.definitionsForFile(n),l=z(e,n)?.callables??[],u={db:e,relativePath:n,definitions:c,callables:l,boundaryObservationLocations:i,lexicalOwners:Qr(e,n,c)};for(let{line:d,sourceLine:m}of a){let p=new Map;for(let f=m.indexOf(r);f>=0;f=m.indexOf(r,f+Math.max(1,r.length))){let g=dG(u,d,m,r,f);p.set(ms(g),g)}o.push(...p.values())}}function dG(e,t,n,r,i){let{definitions:o,boundaryObservationLocations:s,relativePath:a}=e,c=_(e.db,a),l=z(e.db,a)?.language,u=c&&nr(c.rootNode,t,t,we,{startColumn:i,endColumn:i+r.length}),d=u&&l?su(u,l):null,m=o.filter(S=>S.startLine<=t&&S.endLine>=t&&(S.startLine!==t||(S.startChar??0)<=i)&&(S.endLine!==t||S.endChar===void 0||S.endChar>=i+r.length)),p=d?e.lexicalOwners.get(Xr(d))??null:m.length===1?m[0]:null,f=p&&!he(p.symbol)?p:null,g=d??mG(e,t,f,null,p),h=s.has(`${a}\0${t}`),y=!!(f?.isFunctionLike||d);return{relativePath:a,line:t,sourceLine:n,ownerSymbol:f?.symbol??null,ownerShortName:pG(f,d,p),ownerStartLine:g.startLine,ownerEndLine:g.endLine,ownerStartColumn:d?.startColumn,ownerEndColumn:d?.endColumn,matchKind:SG(n,r),seedPriority:h?0:y?1:2}}function mG(e,t,n,r,i){let{db:o,relativePath:s}=e,a=n?.startLine??r?.startLine??i?.startLine??t,c=n?.endLine??r?.endLine??i?.endLine??t;return To(o,s,t,a,c)}function pG(e,t,n){return e?L(e.symbol):t?.name??(n?L(n.symbol):null)}function fG(e,t){let n={"exact-value":0,boundary:1,embedded:2};return e.seedPriority-t.seedPriority||n[e.matchKind]-n[t.matchKind]||e.relativePath.localeCompare(t.relativePath)||e.line-t.line}function ki(e){return new Set(e.map(t=>`${t.relativePath}:${t.line}`)).size}function ms(e){return`${e.relativePath}\0${e.line}\0${e.ownerSymbol??e.ownerShortName}\0${e.ownerStartColumn??""}\0${e.ownerEndColumn??""}`}function $x(e,t,n){let r=z(e,t)?.callables??[],i=co(r,n);if(i)return{file:t,name:i.name,startLine:i.startLine,endLine:i.endLine,startColumn:i.startColumn,endColumn:i.endColumn};if(r.some(a=>a.startLine<=n&&a.endLine>=n))return null;let o=jx(e,t,n);if(!o)return null;let s=To(e,t,n,o.startLine,o.endLine);return{file:t,name:o.name,startLine:s.startLine,endLine:s.endLine}}function gG(e,t){if(e.type==="variable_declarator"){let n=e.childForFieldName("name")??e.namedChild(0),r=e.childForFieldName("value")??e.namedChild(1);if(n?.type==="identifier"&&r&&Mm(r,t))return{name:n.text,startLine:e.startPosition.row,endLine:e.endPosition.row}}return hG(e,t)}function hG(e,t){if(e.type==="pair"){let n=e.childForFieldName("key")??e.namedChild(0),r=e.childForFieldName("value")??e.namedChild(1),i=n?.text.replace(/^(?:['"])(.*)(?:['"])$/u,"$1");if(i&&r&&/^[A-Za-z_$][\w$]*$/u.test(i)&&Mm(r,t))return{name:i,startLine:e.startPosition.row,endLine:e.endPosition.row}}return null}function jx(e,t,n){let r=_(e,t)?.rootNode;if(!r||r.startPosition.row>n||r.endPosition.row<n)return null;let i=Dm(r,n);for(;i;){let s=gG(i,n);if(s)return s;i=i.parent}let o=si(e,t,n);return o?{name:`source@${n+1}`,startLine:o.startLine,endLine:o.endLine}:null}function Mm(e,t){return["arrow_function","function_expression","generator_function","generator_function_declaration"].includes(e.type)&&e.startPosition.row<=t&&e.endPosition.row>=t?!0:e.namedChildren.some(n=>n.startPosition.row<=t&&n.endPosition.row>=t&&Mm(n,t))}function Dm(e,t){let n=e.namedChildren.filter(r=>r.startPosition.row<=t&&r.endPosition.row>=t).sort((r,i)=>r.endIndex-r.startIndex-(i.endIndex-i.startIndex)||r.startPosition.row-i.startPosition.row)[0];return n?Dm(n,t):e}function yG(e,t){let n=t.match(/^(.+):(\d+)(?:-(\d+))?$/u);if(!n)return null;let r=Ur(e,n[1],{allowMultiple:!1})[0]?.relativePath;if(!r)return null;let i=Math.max(0,Number.parseInt(n[2],10)-1),o=n[3]?Math.max(i,Number.parseInt(n[3],10)-1):i,s=z(e,r),a=_(e,r);if(!s||!a)return null;let c=nr(a.rootNode,i,o,we);if(!c||!we.has(c.type))return null;let l=c.namedChild(0),u=l?su(l,s.language):null;return u?{file:r,...u,name:u.name??"<anonymous>"}:null}function bG(e){return{symbol:`source-construct:${e.file}:${e.startLine}:${e.endLine}:${e.name}`,shortName:e.name,relativePath:e.file,startLine:e.startLine,endLine:e.endLine}}function SG(e,t){let n=/[\p{L}\p{N}_$]/u,r=e.indexOf(t);for(;r>=0;){let i=e[r-1]??"",o=e[r+t.length]??"";if((i==="'"||i==='"'||i==="`")&&o===i)return"exact-value";if(!n.test(i)&&!n.test(o))return"boundary";r=e.indexOf(t,r+Math.max(1,t.length))}return"embedded"}function Lm(e){return F(e)==="test"?!1:!/(?:^|[/._-])(?:fixtures?|mocks?|previews?|demos?|examples?|stories)(?:[/._-]|$)/iu.test(e)}function vG(e,t){return e.matchKind!=="embedded"&&t(e.relativePath)&&(vu(e.relativePath)!=="production"||Lm(e.relativePath))}function CG(e,t){let n=[...t].sort(xG),r=[],i=new Set;for(let o of n)if(!i.has(o.relativePath)&&(r.push(o),i.add(o.relativePath),r.length>=Cx))break;for(let o of n){if(r.length>=Cx)break;r.includes(o)||r.push(o)}return r.map(o=>({query:e,file:o.relativePath,line:o.line,ownerSymbol:o.ownerSymbol,ownerShortName:o.ownerShortName,ownerStartLine:o.ownerStartLine,ownerEndLine:o.ownerEndLine,ownerStartColumn:o.ownerStartColumn,ownerEndColumn:o.ownerEndColumn,sourceLine:o.sourceLine.trim(),matchKind:o.matchKind,traversalSeed:!1}))}function xG(e,t){let n={"exact-value":0,boundary:1,embedded:2};return n[e.matchKind]-n[t.matchKind]||+(t.ownerSymbol!==null)-+(e.ownerSymbol!==null)||+!Lm(e.relativePath)-+!Lm(t.relativePath)||e.relativePath.localeCompare(t.relativePath)||e.line-t.line}function RG(e,t){let n=new Map;for(let r of t){let i=EG(r.relativePath);n.set(i,(n.get(i)??0)+1)}return[...n].sort(([r,i],[o,s])=>s-i||r.localeCompare(o)).slice(0,Aq).map(([r])=>`scip-query search ${O(e)} --scope ${O(r)}`)}function EG(e){let t=e.split("/").filter(Boolean);if(t.length<=1)return e;let n=t.slice(0,-1),r=n.lastIndexOf("src");return r>=0?n.slice(0,Math.min(n.length,r+3)).join("/"):n.slice(0,Math.min(n.length,3)).join("/")}function Hx(e,t,n){let r=new Set(t.callerFileMap([n],{semantic:!1}).get(n.symbolId));r.add(n.relativePath);let i=[];for(let o of[...r].sort()){let s=Yr(e,o,n.symbol),a=s!==null,c=s??IG(e,o,n);if(c.length===0){a||i.push({file:o,line:null,enclosingSymbol:null,compilerBound:a});continue}let l=t.definitionsForFile(o);for(let u of c)i.push({file:o,line:u,enclosingSymbol:ir(l,u)?.symbol??null,compilerBound:a})}return i}function IG(e,t,n){let r=V(e,t).filter(o=>o.importedName===n.leaf&&o.sourcePath!==null&&ze(o.sourcePath,n.relativePath)),i=r.length>0?r.map(o=>o.localName??o.importedName):[n.leaf];return[...new Set(i.filter(Boolean).flatMap(o=>uo(e,t,o)))].sort((o,s)=>o-s)}function Px(e,t){let n=_(e,t)?.rootNode,r=n&&ga(t,n);if(r?.available){let o=V(e,t);return r.moduleReferences().flatMap(s=>{let a=s.literal?ro(e,t,s.specifier):null,c=a&&it(e,a)?a:null,l=c?"internal":!s.literal||s.specifier.startsWith(".")||s.specifier.startsWith("/")?"unresolved":"external",u=o.filter(m=>c&&m.sourcePath===c),d={symbol:s.specifier,shortName:s.specifier,fromFile:c,source:"parsed-source",resolution:l};return u.length>0?u.map(m=>({...d,importedName:m.importedName,localName:m.localName??m.importedName})):[{...d,importedName:"*",localName:"*"}]})}let i=e.all(`SELECT DISTINCT gs.symbol, def_d.relative_path AS from_file
|
|
41
|
+
FROM mentions m
|
|
42
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
43
|
+
JOIN documents imp_d ON c.document_id = imp_d.id
|
|
44
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
45
|
+
LEFT JOIN (
|
|
46
|
+
SELECT m2.symbol_id, c2.document_id
|
|
47
|
+
FROM mentions m2
|
|
48
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
49
|
+
WHERE m2.role = 1
|
|
50
|
+
GROUP BY m2.symbol_id
|
|
51
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
52
|
+
LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
53
|
+
WHERE imp_d.relative_path = ? AND m.role = 2
|
|
54
|
+
ORDER BY def_d.relative_path, gs.symbol`,t);return i.length>0?i.map(o=>({symbol:o.symbol,shortName:L(o.symbol),importedName:Tx(L(o.symbol)),localName:Tx(L(o.symbol)),fromFile:o.from_file,source:"compiler"})):V(e,t).map(o=>{let s=wG(o.importedName,o.localName,o.kind),a=o.localName??o.importedName,c=o.importedName==="default"?a:o.importedName;return{symbol:s,shortName:s,importedName:c,localName:a,fromFile:o.sourcePath,source:"parsed-source"}})}function Tx(e){return e.slice(e.lastIndexOf(":")+1).replace(/\(\)$/u,"")||e}function wG(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 wr(e,t,n){let r=J(e,n);if(!r.match)return{matches:[],total:0,omitted:0};let i=[r.match,...r.candidates.map(s=>J(e,s.symbol).match)].filter(s=>s!==null),o=new Map;for(let s of i){let a=t.definitionsForFile(s.relativePath).find(c=>c.symbol===s.symbol);a&&o.set(a.symbol,a)}return{matches:[...o.values()],total:r.total,omitted:Math.max(0,r.total-o.size)}}function PG(e){return{symbol:e.symbol,shortName:L(e.symbol),relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine}}function lt(e,t){let n=[t.kind,t.fromFile,t.fromSymbol??"",t.toFile,t.toSymbol??"",t.fromBoundaryParticipant?.observationId??"",t.toBoundaryParticipant?.observationId??"",t.fromSourceConstruct?Xt(t.fromSourceConstruct):"",t.toSourceConstruct?Xt(t.toSourceConstruct):"",t.runtimeBoundaryKey??"",t.line??""].join("\0");e.set(n,t)}function Kc(e){return{observationId:e.id,action:e.action,protocol:e.protocol,role:e.role,address:qx(e),file:e.source.file,line:e.source.startLine,endLine:e.source.endLine,ownerName:e.owner.name,ownerSymbol:e.owner.symbol}}function Lx(e,t){let n=j(e,t.source.file);return Lt(e,t.source.file,0,Math.max(0,n.length-1),[t.source.startLine])}function Mx(e,t){let n=[...e.values()];for(let r of[t.owner,t.source]){let i=n.filter(o=>o.file===r.file&&o.startLine<=r.startLine&&o.endLine>=r.startLine).sort((o,s)=>o.endLine-o.startLine-(s.endLine-s.startLine)||o.startLine-s.startLine)[0];if(i)return i}return null}function Dx(e,t,n,r,i){let o=[],s=n.get(e.id);s!==void 0&&s<=t&&o.push(s);for(let a of r.values()){if(a.depth>t)continue;let c=a.definition;Fx(c,e)&&o.push(a.depth)}for(let a of i.values())a.depth>t||Fx(a,e)&&o.push(a.depth);return o.length>0?Math.min(...o):null}function Fx(e,t){let n=e.relativePath??e.file;return[t.owner,t.source].some(r=>n===r.file&&e.startLine<=r.startLine&&e.endLine>=r.startLine)}function Fm(e){return Be("runtime-boundary-participant",e)}function TG(e,t,n){let r=vn(e,n),i=vn(t,n);return r.relativeDir!==i.relativeDir?!0:/(?:^|\/)(?:contracts?|schemas?|db\/schema)(?:\/|$)/u.test(t)}function LG(e,t,n){return ps(e,n).id===ps(t,n).id}function Ux(e,t,n,r){if(e.referenceScope==="all")return!0;let i=ps(t,r).id;return[...n.values()].some(s=>s.promoteBoundaryImports&&ps(s.file,r).id===i)?!0:e.referenceScope!=="cross-workspace-or-forward"?!1:vn(t,r).relativeDir!==vn(e.definition.relativePath,r).relativeDir}function MG(e,t){let n={none:0,"forward-regions":1,"cross-workspace-or-forward":2,all:3};return n[e]>=n[t]?e:t}function DG(e,t){let n=Ex.get(e);if(n)return n;let r=t.fileDependencyGraph(),i={fileGraph:r,reverseFileGraph:FG(r),workspaces:kG(t.sourceFiles()),runtimeBoundaries:Zg(e)};return Ex.set(e,i),i}function FG(e){let t=new Map;for(let[n,r]of e)for(let i of r){let o=t.get(i)??new Set;o.add(n),t.set(i,o)}return t}function vn(e,t){return t.find(n=>e===n.relativeDir||e.startsWith(`${n.relativeDir}/`))??{name:"root",relativeDir:""}}function kG(e){let t=new Set(["apps","packages","services","crates","libs","tools"]),n=new Map;for(let r of e){let i=r.split("/").filter(Boolean);if(i.length<3||!t.has(i[0]))continue;let o=`${i[0]}/${i[1]}`;n.set(o,{name:i[1],relativeDir:o})}return[...n.values()].sort((r,i)=>i.relativeDir.length-r.relativeDir.length)}function ps(e,t){let n=vn(e,t),i=(n.relativeDir?e.slice(n.relativeDir.length+1):e).split("/").filter(Boolean);i[0]==="src"&&i.shift();let o=NG(i);return{id:`region:${n.relativeDir||"root"}:${o}`,label:`${n.name}:${o}`,workspace:n.name,structuralPath:o}}function NG(e){if(e.length<=1)return"root";let t=e[0],n=e[1];return["components","features","modules"].includes(t)?`${t}/${n}`:t==="db"?`${t}/${n}`:["contracts","routes","services"].includes(t)?t:t==="tests"||t==="__tests__"?"tests":t}function AG(e,t,n,r,i,o,s){let a=Te([...e.values()],p=>o.get(p.file).id),c=Te([...t.values()],p=>o.get(p.definition.relativePath).id),l=Te(n,p=>o.get(p.file).id),u=new Map;for(let p of r)for(let f of new Set([p.fromRegionId,p.toRegionId])){let g=u.get(f)??[];g.push(p),u.set(f,g)}let d=Te(i,p=>p.toRegionId),m=Te(i,p=>p.fromRegionId);return[...a.entries()].map(([p,f])=>{let g=o.get(f[0].file),h=c.get(p)??[],y=l.get(p)??[],S=u.get(p)??[],I=s.has(p),x=h.map(BG).sort(UG).slice(0,_q),E=f.filter(b=>F(b.file)==="test").length;return{id:p,label:g.label,workspace:g.workspace,structuralPath:g.structuralPath,minDepth:Math.min(...f.map(b=>b.depth)),fileCount:f.length,sourceFileCount:f.length-E,testFileCount:E,symbolCount:h.length,literalHitCount:y.length,anchorQueries:re([...y.map(b=>b.query),...h.flatMap(b=>[...b.anchorQueries])]),relationKinds:re(S.map(b=>b.kind)),incomingRegionIds:re((d.get(p)??[]).map(b=>b.fromRegionId)),outgoingRegionIds:re((m.get(p)??[]).map(b=>b.toRegionId)),memberCallCandidateRelationCount:S.filter(b=>b.evidence==="ast-member-import-candidate").length,notableSymbols:x,omittedNotableSymbols:Math.max(0,h.length-x.length),expanded:I,files:I?f.map(_G).sort(qG):[],symbols:I?h.map(OG).sort(zG):[],literalHits:I?[...y].sort(Gx):[],relations:I?[...S].sort(zx):[]}}).sort((p,f)=>p.minDepth-f.minDepth||p.label.localeCompare(f.label))}function _G(e){return{file:e.file,kind:F(e.file),depth:e.depth,origins:re([...e.origins])}}function OG(e){return{symbol:e.definition.symbol,shortName:L(e.definition.symbol),file:e.definition.relativePath,startLine:e.definition.startLine,endLine:e.definition.endLine,depth:e.depth,origins:re([...e.origins]),anchorQueries:re([...e.anchorQueries]),referenceExpansion:e.referenceScope!=="none",referenceScope:e.referenceScope}}function BG(e){return{shortName:L(e.definition.symbol),file:e.definition.relativePath,origins:re([...e.origins])}}function $G(e){return[...Te(e.filter(n=>n.fromRegionId!==n.toRegionId),n=>`${n.fromRegionId}\0${n.toRegionId}`).values()].map(n=>({fromRegionId:n[0].fromRegionId,toRegionId:n[0].toRegionId,kinds:re(n.map(r=>r.kind)),relationCount:n.length,fromFiles:re(n.map(r=>r.fromFile)),toFiles:re(n.map(r=>r.toFile)),fromSymbols:re(n.flatMap(r=>r.fromSymbol?[L(r.fromSymbol)]:[])),toSymbols:re(n.flatMap(r=>r.toSymbol?[L(r.toSymbol)]:[])),evidence:re(n.map(r=>r.evidence)),strengths:re(n.map(r=>r.strength??"unknown"))})).sort((n,r)=>n.fromRegionId.localeCompare(r.fromRegionId)||n.toRegionId.localeCompare(r.toRegionId))}function jG(e,t){return[...e.values()].map(n=>({kind:n.unresolved?"unresolved-import":"external-import",name:n.name,fromRegionIds:re([...n.fromFiles].flatMap(r=>{let i=t.get(r);return i?[i.id]:[]})),fromFiles:re([...n.fromFiles])})).sort((n,r)=>n.name.localeCompare(r.name))}function HG(e,t,n,r){let i=e.kind==="literal"?t.filter(o=>o.query===e.query).map(o=>o.file):[...n.values()].filter(o=>o.anchorQueries.has(e.query)).map(o=>o.definition.relativePath);return re(i.map(o=>r.get(o)?.id).filter(o=>!!o))}function qx(e){return e.keyParts.map(t=>`${t.name}=${t.value}`).join(" ")}function re(e){return[...new Set(e)].sort()}function zx(e,t){return e.fromRegionId.localeCompare(t.fromRegionId)||e.toRegionId.localeCompare(t.toRegionId)||e.kind.localeCompare(t.kind)||e.fromFile.localeCompare(t.fromFile)||e.toFile.localeCompare(t.toFile)||(e.line??-1)-(t.line??-1)}function UG(e,t){return Ci(e.origins)-Ci(t.origins)||e.shortName.localeCompare(t.shortName)}function qG(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)}function zG(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function Gx(e,t){return e.file.localeCompare(t.file)||e.line-t.line||e.query.localeCompare(t.query)}function GG(e,t,n){let r=wr(e.db,e.index,n).matches[0];r&&!he(r.symbol)&&e.addSymbol(r,0,"literal-owner",t,"all",!0)}function KG(e,t){for(let n of e.symbolStates.values()){let r=e.regionForFile.get(n.definition.relativePath)?.id;if(!r)continue;let i=Sn(n.definition.symbol);t.push({id:Be("edge","structural-membership",r,i),kind:"structural-membership",fromNodeId:r,toNodeId:i,directed:!0,disposition:"folded",semantics:Mc("structural-membership"),evidence:[{method:"indexed-definition-file",strength:"exact",identity:n.definition.symbol,location:{file:n.definition.relativePath,line:n.definition.startLine,endLine:n.definition.endLine}}]})}}function WG(e,t,n){let r=new Set,i=0;for(let o of e){let s=Ox(o);!t.has(o.id)&&r.size>0&&i+s>n||(r.add(o.id),i+=s)}return{selectedRegionIds:r,estimatedCharacters:i}}function VG(e,t,n){for(let s of e.symbols)s.origins.includes("symbol-anchor")&&n.add(s.file);let r=Te(e.symbols,s=>s.file),i=Te(e.literalHits,s=>s.file),o=[...e.files].sort((s,a)=>cG(s,a,r,i));for(let s of o){let a=(r.get(s.file)??[]).sort(nC)[0];if(a){t.push({kind:"symbol",regionId:e.id,file:a.file,line:a.startLine,endLine:a.endLine,label:a.shortName});continue}let c=(i.get(s.file)??[]).sort(Gx)[0];c&&t.push({kind:"literal",regionId:e.id,file:c.file,line:c.line,endLine:null,label:c.ownerShortName??c.query})}}function JG(e,t,n,r){for(let i=0;t.length<r;i+=1){let o=!1;for(let s of e){let a=s[i];if(a&&(o=!0,!n.has(a.file)&&(t.push(a),n.add(a.file),t.length===r)))break}if(!o)break}}var Qx=["causal","structure","complete"],XG={causal:["execution","runtime","dataflow","state","temporal"],structure:["contract","identity","ownership","dependencies"],complete:Mt},QG=2,ZG=48,Kx=64,eK=5e4;function tK(e,t,n={}){let{symbols:r,searches:i}=nK(t),{view:o,families:s,direction:a,subtypes:c,connecting:l,inventoryOnly:u,foldIds:d,maxDepth:m,maxEdges:p}=oK(n),f=kx(e,{symbols:r,searches:i,maxDepth:m,maxTopologyCharacters:eK,relations:uK(s)}),{allProjected:g,projected:h,rejected:y}=iK(f,s,c),S=new Set(f.anchors.flatMap(U=>U.nodeIds));if(l&&S.size<2)throw new Error("Connecting evidence requires at least two resolved root nodes.");let I=new Set(h.map(U=>U.id)),x=Wc(g,S,"incoming").filter(U=>I.has(U.id)),E=Wc(g,S,"outgoing").filter(U=>I.has(U.id)),b=Wc(g,S,"both").filter(U=>I.has(U.id)),v=gK(s,c,x,E,b),C={incoming:x,outgoing:E,both:b}[a],R=l?xK(C,[...S],a):C,P=RK(R,S,a),w=[...R].sort((U,pt)=>EK(U,pt,P)),{edges:T,folds:G,eligibleCount:K,omittedEdges:ue}=aK(w,p,d,u),ce=cK(f,g,S,s,a),Ce=ce.filter(U=>U.disposition==="unsupported").length,pe=[...y.values()].reduce((U,pt)=>U+pt,0),Je=[...y].map(([U,pt])=>`Provider rejected ${pt} ${U} relationship(s); inspect the selected source before making absence claims.`),$=f.coverage.status==="incomplete"||pe>0?"incomplete":ue>0?"bounded":"accounted";return{kind:"graph",view:n.families&&n.families.length>0?"custom":o,families:s,selection:{direction:a,subtypes:c,connecting:l,inventoryOnly:u,foldIds:d},targets:f.anchors.map(U=>({kind:U.kind,query:U.query,status:U.status,nodeIds:[...U.nodeIds],omittedCandidates:U.omittedCandidates})),inventory:v,edges:T,folds:G,coverage:{status:$,topologyStatus:f.coverage.status,scope:f.coverage.scope,maxDepth:m,maxEdges:p,matchedEdges:w.length,eligibleEdges:K,returnedEdges:T.length,omittedEdges:ue,frontierGroups:ce.length,unsupportedFrontiers:Ce,rejectedRelationships:pe,blindSpots:Ee([...f.coverage.blindSpots,...ce.filter(U=>U.disposition==="unsupported").map(U=>U.reason),...Je,...tC(s)]),explanation:rK({inventoryOnly:u,foldCount:d.length,matchedCount:w.length,status:$,omittedEdges:ue,topologyExplanation:f.coverage.explanation,rejectionNotes:Je})}}}function nK(e){let t=Ee([...e.symbols??[],...e.locations??[]]),n=Ee(e.searches??[]);if(t.length===0&&n.length===0)throw new Error("evidence requires at least one positional symbol, --symbol, --at, or --search selector.");return{symbols:t,searches:n}}function rK(e){return e.inventoryOnly?`${e.matchedCount} relationship(s) match the explicit projection; only exact inventory counts were requested.`:e.foldCount>0?`Every relationship in ${e.foldCount} explicitly selected recoverable fold(s) was emitted.`:e.status==="accounted"?"Every selected relationship in the bounded topology was emitted.":e.status==="bounded"?`${e.omittedEdges} selected relationship(s) were withheld by the explicit edge budget.`:[e.topologyExplanation,...e.rejectionNotes].join(" ")}function iK(e,t,n){let r=new Map(e.nodes.map(c=>[c.id,c])),i=new Map,o=(c,l,u)=>{if(!t.includes(c)||n.length>0&&!n.includes(l))return;let d=`${c}/${l} (${u})`;i.set(d,(i.get(d)??0)+1)},s=e.edges.filter(c=>c.disposition==="emitted"||c.disposition==="folded").flatMap(c=>dK(c,r,o)),a=s.filter(c=>t.includes(c.family)).filter(c=>n.length===0||n.includes(c.subtype));return{allProjected:s,projected:a,rejected:i}}function oK(e){let t=e.view??"causal",n=lK(e.families,t),r=e.direction??"both",i=Ee(e.subtypes??[]),o=e.connecting??!1,s=e.inventoryOnly??!1,a=Ee(e.foldIds??[]),c=e.maxDepth??QG,l=e.maxEdges??ZG;return sK({maxDepth:c,maxEdges:l,direction:r,inventoryOnly:s,foldIds:a}),{view:t,families:n,direction:r,subtypes:i,connecting:o,inventoryOnly:s,foldIds:a,maxDepth:c,maxEdges:l}}function sK({maxDepth:e,maxEdges:t,direction:n,inventoryOnly:r,foldIds:i}){if(!Number.isSafeInteger(e)||e<0)throw new RangeError(`Evidence depth must be a non-negative safe integer; received ${e}.`);if(!Number.isSafeInteger(t)||t<=0)throw new RangeError(`Evidence max edges must be a positive safe integer; received ${t}.`);if(!["incoming","outgoing","both"].includes(n))throw new Error(`Unsupported graph evidence direction: ${n}.`);if(r&&i.length>0)throw new Error("Evidence fold materialization cannot be combined with --inventory-only.")}function aK(e,t,n,r){let i=hK(e,t),o=bK(i,n),s=r?[]:n.length>0?e.filter(u=>o.has(u.id)):e,a=n.length>0?s:s.slice(0,t),c=n.length>0||r?[]:i,l=Math.max(0,s.length-a.length);return{edges:a,folds:c,eligibleCount:s.length,omittedEdges:l}}function cK(e,t,n,r,i){let o=new Set([...n,...Wc(t,n,i).flatMap(a=>[a.from.id,a.to.id])]),s=new Map(e.edges.map(a=>[a.id,a]));return e.frontiers.filter(a=>{let c=a.edgeIds.flatMap(l=>s.has(l)?[s.get(l)]:[]);return c.length===0?!0:c.some(l=>{let u=l.semantics?.some(d=>{let m=Zx(d);return m!==null&&r.includes(m)});return l.semantics?.length&&!u||!l.semantics?.length&&l.kind.startsWith("runtime-boundary")&&!r.includes("runtime")?!1:i!=="incoming"&&[l.fromNodeId,...a.fromNodeIds].some(d=>o.has(d))||i!=="outgoing"&&[l.toNodeId,...a.memberNodeIds].some(d=>o.has(d))})})}function lK(e,t){if(!Qx.includes(t))throw new Error(`Unsupported graph evidence view: ${t}.`);let n=e&&e.length>0?e:XG[t],r=n.filter(i=>!Mt.includes(i));if(r.length>0)throw new Error(`Unsupported graph evidence family: ${r.join(", ")}.`);return Ee(n)}function uK(e){return["call","contract-symbol","import","reference","runtime-boundary"]}function dK(e,t,n){let r=t.get(e.fromNodeId),i=t.get(e.toNodeId);return!r||!i?[]:(e.semantics??[]).flatMap((o,s)=>{let a=Zx(o);if(!a)return[];let c=Lc(a,o.subtype);if(!c)throw new Error(`No graph relation provider contract is registered for ${a}/${o.subtype}.`);let l=fK(e);return c.relation.evidenceStrengths.includes(l)?[{id:`${e.id}:${s}:${a}`,family:a,semanticFamily:o.family,subtype:o.subtype,from:Wx(r),to:Wx(i),sourceKind:e.kind,providerId:c.provider.id,supportCeiling:c.relation.supportCeiling,establishes:c.relation.establishes,nonClaims:[...c.relation.nonClaims],recoverWith:[...c.relation.recoverWith],evidenceStrength:l,evidenceMethods:Ee(e.evidence.map(u=>u.method)),evidenceConstituents:mK(e.evidence),context:o.context?{...o.context}:null,attributes:o.attributes?{...o.attributes}:null}]:(n(a,o.subtype,l),[])})}function mK(e){let t=new Map;for(let n of e)t.set(`${n.method}\0${n.strength}`,n);return[...t.values()].map(({method:n,strength:r})=>({method:n,strength:r}))}function Zx(e){switch(e.family){case"control":return e.context?.crossesRuntimeBoundary===!0||e.subtype==="runtime-handoff"?"runtime":"execution";case"data":return"dataflow";case"state":return"state";case"temporal":return"temporal";case"contract":return"contract";case"identity":return IK(e.subtype)}}function Wx(e){let t=pK(e);return{id:e.id,kind:e.kind,label:t?L(t):e.label,symbol:t,location:e.location?{...e.location}:null}}function pK(e){return e.kind!=="symbol"||!e.id.startsWith("symbol:")?null:decodeURIComponent(e.id.slice(7))}function fK(e){let t=Ee(e.evidence.map(n=>n.strength));return t.length===1?t[0]:t.includes("exact")&&t.every(n=>n==="exact"||n==="derived")?"mixed":t.includes("candidate")?"candidate":t.includes("unknown")||t.length===0?"unknown":"mixed"}function Wc(e,t,n){let r=km(e,n),i=new Map,o=new Map,s=[...t].sort();for(let a of s)o.set(a,0);for(let a=0;a<s.length;a+=1){let c=s[a],l=o.get(c);for(let u of r.get(c)??[])i.set(u.edge.id,u.edge),!o.has(u.next)&&(o.set(u.next,l+1),s.push(u.next))}return[...i.values()]}function km(e,t){let n=new Map,r=(i,o,s)=>{let a=n.get(i)??[];a.push({edge:s,next:o}),n.set(i,a)};for(let i of e)t!=="incoming"&&r(i.from.id,i.to.id,i),t!=="outgoing"&&r(i.to.id,i.from.id,i);for(let i of n.values())i.sort((o,s)=>o.edge.id.localeCompare(s.edge.id)||o.next.localeCompare(s.next));return n}function gK(e,t,n,r,i){let o=new Set;for(let u of[...n,...r,...i])o.add(`${u.family}\0${u.subtype}`);if(t.length>0)for(let u of e)for(let d of t)o.add(`${u}\0${d}`);let s=u=>{let d=new Map;for(let m of u){let p=`${m.family}\0${m.subtype}`;d.set(p,(d.get(p)??0)+1)}return d},a=s(n),c=s(r),l=s(i);return[...o].map(u=>{let[d,m]=u.split("\0");return{family:d,subtype:m,incoming:a.get(u)??0,outgoing:c.get(u)??0,both:l.get(u)??0}}).sort((u,d)=>Mt.indexOf(u.family)-Mt.indexOf(d.family)||u.subtype.localeCompare(d.subtype))}function hK(e,t){let n=e.slice(t),r=new Map;for(let s of n){let a=yK(s),c=`${s.family}\0${a}`,l=r.get(c)??[];l.push(s),r.set(c,l)}let i=new Map(e.map((s,a)=>[s.id,a+1])),o=[];for(let[s,a]of[...r].sort(([c],[l])=>c.localeCompare(l))){let[c,l]=s.split("\0"),u=[...a].sort((d,m)=>d.id.localeCompare(m.id));for(let d=0;d<u.length;d+=Kx){let m=u.slice(d,d+Kx),p=m.map(y=>y.id),f=Ee(m.map(y=>y.subtype)).sort(),g=f.length===1?f[0]:"mixed",h=[...new Set(m.flatMap(y=>[y.from.id,y.to.id]))].sort();o.push({id:CK(c,f.join("\0"),p),mode:SK(m),family:c,subtype:g,subtypes:f,region:l,edgeCount:p.length,edgeIds:p,nodeIds:h,minimumMaxEdges:Math.max(...p.map(y=>i.get(y)??e.length))})}}return o.sort((s,a)=>Mt.indexOf(s.family)-Mt.indexOf(a.family)||(s.region??"").localeCompare(a.region??"")||s.id.localeCompare(a.id))}function yK(e){let t=e.from.location?.file??`kind:${e.from.kind}`,n=e.to.location?.file??`kind:${e.to.kind}`;return t===n?t:`${t} -> ${n}`}function bK(e,t){if(t.length===0)return new Set;let n=new Map(e.map(i=>[i.id,i])),r=t.filter(i=>!n.has(i));if(r.length>0){let i=e.map(o=>o.id).sort();throw new Error(`Unknown evidence fold ${r.join(", ")} for this projection. Available folds: ${i.join(", ")||"(none)"}.`)}return new Set(t.flatMap(i=>n.get(i).edgeIds))}function SK(e){let t=new Map,n=new Map,r=new Set;for(let o of e){r.add(o.from.id),r.add(o.to.id);let s=t.get(o.from.id)??new Set;s.add(o.to.id),t.set(o.from.id,s);let a=n.get(o.to.id)??new Set;a.add(o.from.id),n.set(o.to.id,a)}return vK(r,t)?"scc":[...r].every(o=>(n.get(o)?.size??0)<=1&&(t.get(o)?.size??0)<=1)?"linear":"topology"}function vK(e,t){let n=new Set,r=new Set,i=o=>{if(n.has(o))return!0;if(r.has(o))return!1;n.add(o);for(let s of t.get(o)??[])if(i(s))return!0;return n.delete(o),r.add(o),!1};return[...e].some(i)}function CK(e,t,n){return`fold:${YG("sha256").update([e,t,...n].join("\0")).digest("hex").slice(0,16)}`}function xK(e,t,n){let r=new Map,i=[...new Set(t)].sort();for(let o=0;o<i.length;o+=1)for(let s=o+1;s<i.length;s+=1){let a=[Vx(e,i[o],i[s],n)];n!=="both"&&a.push(Vx(e,i[s],i[o],n));for(let c of a.flat())r.set(c.id,c)}return[...r.values()]}function Vx(e,t,n,r){let i=km(e,r),o=new Map([[t,0]]),s=new Map,a=[t];for(let l=0;l<a.length;l+=1){let u=a[l],d=o.get(u);if(u!==n)for(let m of i.get(u)??[])o.has(m.next)||(o.set(m.next,d+1),s.set(m.next,{node:u,edge:m.edge}),a.push(m.next))}if(!o.has(n))return[];let c=[];for(let l=n;l!==t;){let u=s.get(l);if(!u)return[];c.push(u.edge),l=u.node}return c.reverse()}function RK(e,t,n){let r=km(e,n),i=new Map,o=[...t];for(let s of t)i.set(s,0);for(let s=0;s<o.length;s+=1){let a=o[s],c=i.get(a);for(let{next:l}of r.get(a)??[])i.has(l)||(i.set(l,c+1),o.push(l))}return i}function EK(e,t,n){return Jx(e,n)-Jx(t,n)||Yx(e)-Yx(t)||Xx(e.evidenceStrength)-Xx(t.evidenceStrength)||Mt.indexOf(e.family)-Mt.indexOf(t.family)||e.from.label.localeCompare(t.from.label)||e.to.label.localeCompare(t.to.label)||e.subtype.localeCompare(t.subtype)||e.id.localeCompare(t.id)}function Jx(e,t){return Math.min(t.get(e.from.id)??Number.MAX_SAFE_INTEGER,t.get(e.to.id)??Number.MAX_SAFE_INTEGER)}function Yx(e){let t=[e.from,e.to].filter(n=>n.kind==="structural-region").length;return t===2?2:t}function Xx(e){switch(e){case"exact":return 0;case"mixed":return 1;case"derived":return 2;case"candidate":return 3;case"unknown":return 4}}function IK(e){return e.startsWith("contains")||e.startsWith("owns-")?"ownership":e.startsWith("import")?"dependencies":"identity"}function Nm(e,t){let n=ar(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let r=n.filter(a=>!e.isIgnored(a)).sort(),i=sa(e,r,{sort:!0}),o=Vr(e,"forward",n).filter(a=>!e.isIgnored(a)),s=Vr(e,"reverse",n).filter(a=>!e.isIgnored(a));return{files:r,symbols:i,dependsOn:o,dependedOnBy:s}}function Am(e,t){let n=ar(e,t);return n.length===0?[]:tR([...eR(e,n),...PK(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(nR)}function wK(e,t){let n=ar(e,t);return n.length===0?[]:tR(eR(e,n)).filter(r=>!e.isIgnored(r.relative_path)).map(r=>({...nR(r),basis:"external-reference"}))}function eR(e,t){return e.all(`WITH selected_paths(path) AS (SELECT value FROM json_each(?))
|
|
55
|
+
SELECT DISTINCT d1.relative_path, gs.symbol
|
|
56
|
+
FROM mentions m
|
|
57
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
58
|
+
JOIN documents d1 ON c.document_id = d1.id
|
|
59
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
60
|
+
WHERE d1.relative_path NOT IN (SELECT path FROM selected_paths)
|
|
61
|
+
AND (
|
|
62
|
+
EXISTS (
|
|
63
|
+
SELECT 1
|
|
64
|
+
FROM defn_enclosing_ranges der
|
|
65
|
+
JOIN documents d2 ON der.document_id = d2.id
|
|
66
|
+
WHERE der.symbol_id = gs.id
|
|
67
|
+
AND d2.relative_path IN (SELECT path FROM selected_paths)
|
|
68
|
+
)
|
|
69
|
+
OR EXISTS (
|
|
70
|
+
SELECT 1
|
|
71
|
+
FROM mentions def_m
|
|
72
|
+
JOIN chunks def_c ON def_m.chunk_id = def_c.id
|
|
73
|
+
JOIN documents d2 ON def_c.document_id = d2.id
|
|
74
|
+
WHERE def_m.symbol_id = gs.id
|
|
75
|
+
AND def_m.role = 1
|
|
76
|
+
AND d2.relative_path IN (SELECT path FROM selected_paths)
|
|
77
|
+
)
|
|
78
|
+
)
|
|
79
|
+
AND m.role != 1
|
|
80
|
+
AND ${e.localSymbolPredicate}
|
|
81
|
+
${e.pathExclusionsFor("d1")}
|
|
82
|
+
ORDER BY d1.relative_path, gs.symbol`,JSON.stringify(t))}function PK(e,t){let n=new N(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>Xe(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function tR(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 nR(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:L(e.symbol)}}var fs=new WeakMap,rR=rt({kind:"definition-exclusions",invalidation:Re("definition-exclusions"),serialize:e=>JSON.stringify(e),deserialize:TK});function oR(e,t){let n=se(t);if(!(n==="rust"||n==="typescript"||n==="tsx"||n==="javascript"))return[];let i=H(e,t);if(!i)return[];let o=bt(e,t,i),s=rR.read(e,t,o);if(s)return s;let a=n==="rust"?UK(e,t):kK(e,t);return rR.write(e,t,o,a),a}function TK(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=t.map(LK);return n.some(r=>r===null)?null:n}catch{return null}}function LK(e){if(!e||typeof e!="object")return null;let t=e;if(!MK(t))return null;let n=t.disposition===void 0?rW(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}:{}}}function MK(e){return!(typeof e.startLine!="number"||!Number.isFinite(e.startLine)||typeof e.endLine!="number"||!Number.isFinite(e.endLine)||typeof e.reason!="string"||e.containerName!==void 0&&typeof e.containerName!="string")}var sR=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),DK=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,FK=/\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 kK(e,t){let n=H(e,t);if(!n||!BK(n))return[];let r=_(e,t);if(!r)return[];let i=fs.get(r);if(i)return i;let o=r.rootNode,s=[];return NK(o)&&s.push({startLine:0,endLine:o.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)",disposition:"exclude"}),s.push(...OK(o)),s.push(...aR(r,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),fs.set(r,s),s}function NK(e){return e.namedChildren.some(t=>{if(t.type!=="expression_statement")return!1;let n=t.namedChild(0);if(n?.type!=="call_expression")return!1;let r=n.namedChild(0);if(!r)return!1;let i=r.type==="member_expression"?r.namedChild(r.namedChildCount-1)?.text:r.text;return i!==void 0&&sR.has(i)})}function AK(e){if(e.type==="function_declaration"){let t=e.namedChild(0)?.text;return t?{name:t,node:e}:void 0}if(e.type==="export_statement"){let t=e.namedChild(0);if(t?.type!=="function_declaration")return;let n=t.namedChild(0)?.text;return n?{name:n,node:t}:void 0}return _K(e)}function _K(e){if(e.type!=="lexical_declaration")return;let t=e.namedChild(0);if(t?.type!=="variable_declarator")return;let n=t.namedChild(0)?.text,r=t.namedChild(1);if(!(!n||r?.type!=="arrow_function"&&r?.type!=="function_expression"))return{name:n,node:t}}function OK(e){let t=[];for(let n of e.namedChildren){let r=AK(n);!r||!/^use[A-Z]/.test(r.name)||t.push({startLine:r.node.startPosition.row,endLine:r.node.endPosition.row,reason:"React custom hook (use*)",disposition:"exclude"})}return t}function BK(e){if(e.includes("scip-query"))return!0;let t=!1;for(let n of sR)if(e.includes(n)){t=!0;break}return t&&DK.test(e)?!0:e.includes("use")&&FK.test(e)}function $K(e){return e.split(/\r?\n/).some(t=>{let n=zr(t);return n===""||n==="dead"||n==="dead-code"||n==="stale"})}function aR(e,t,n){let r=[],i=o=>{t.has(o.type)&&jK(o,n)&&r.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"scip-query suppression comment",disposition:"exclude"});for(let s of o.namedChildren)i(s)};return i(e.rootNode),r}function jK(e,t){if(!e.parent)return!1;let n=e.parent.children,r=-1;for(let i=0;i<n.length;i+=1)if(n[i].startIndex===e.startIndex&&n[i].type===e.type){r=i;break}return HK(n,r,t)}function HK(e,t,n){for(let r=t-1;r>=0;r-=1){let i=e[r];if(n.has(i.type)){if($K(i.text))return!0;continue}if(!(i.type==="attribute_item"||i.type==="inner_attribute_item"))break}return!1}function UK(e,t){let n=_(e,t);if(!n)return[];let r=fs.get(n);if(r)return r;let i=[],o=qK(n);return o?(fs.set(n,o),o):(cR(n.rootNode,i,!1,!1),i.push(...aR(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(...ZK(n.rootNode)),fs.set(n,i),i)}function qK(e){return iW(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)",disposition:"exclude"}]:null}function cR(e,t,n,r){let i=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")&&(i=!0,t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl block (dynamic dispatch)",disposition:"implicit-usage"}));let o=zK(e,t,n,r);for(let s of e.namedChildren)cR(s,t,o,i)}function zK(e,t,n,r){if(e.type==="function_item"||e.type==="function_signature_item")GK(e,t,n,r);else if(r&&QK(e))t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl associated item (dynamic dispatch)",disposition:"implicit-usage"});else if(e.type==="struct_item"||e.type==="enum_item"||e.type==="union_item")KK(e,t,n);else if(e.type==="mod_item"&&_m(e).some(i=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(i)))return!0;return n}function GK(e,t,n,r){let i=_m(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(lR(s)){o={reason:"#[allow(dead_code)]",disposition:"exclude"};break}let a=YK(s);if(a){o=a;break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o.reason,disposition:o.disposition})}function KK(e,t,n){let r=_m(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(XK)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(...)] - generated impl may access fields",disposition:"implicit-usage",containerName:i}),r.some(lR)&&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 _m(e){let t=e.parent;if(!t)return[];let n=t.children,r=sW(n,e);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 WK=new Set(["test","bench","tokio::test","async_std::test"]),VK=new Set(["no_mangle","export_name","link_name","used","macro_export","proc_macro","proc_macro_derive","proc_macro_attribute"]),JK=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 YK(e){if(/#\[\s*cfg\s*\(\s*test\s*\)/.test(e))return{reason:"#[cfg(test)]",disposition:"exclude"};let t=eW(e);return t?WK.has(t)?{reason:`#[${t}]`,disposition:"exclude"}:VK.has(t)?{reason:`Rust ABI/export attribute #[${t}]`,disposition:"implicit-usage"}:JK.has(t)?null:{reason:`Rust attribute macro #[${t}]`,disposition:"implicit-usage"}:null}function XK(e){return/#\[\s*derive\s*\(/.test(e)}function lR(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function QK(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function ZK(e){let t=oW(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 eW(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}var tW=new Set(["#[tauri::command]","#[command]","#[wasm_bindgen]","#[no_mangle]","#[napi]","#[pyfunction]","#[pymethod]","#[pyo3]","#[doc(hidden)]"]),nW=["trait ","#[derive(<reflective>)]","#[derive(...)]",'serde `with = "','attribute `with = "',"Rust attribute macro #[","Rust ABI/export attribute #["];function rW(e){return tW.has(e)||nW.some(t=>e.startsWith(t))?"implicit-usage":"exclude"}function iW(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(aW(n))return!0}return!1}var iR=/\bwith\s*=\s*"([^"]+)"/g;function oW(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){iR.lastIndex=0;let r;for(;(r=iR.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function sW(e,t){let n=-1;for(let r=0;r<e.length;r+=1)if(e[r].startIndex===t.startIndex&&e[r].type===t.type){n=r;break}return n}function aW(e){return!!(/@generated\b/.test(e.text)||/This file is .*generated\b/i.test(e.text)||/Code generated by/i.test(e.text)||/Generated by:\s*https?:\/\/openapi-generator/i.test(e.text)||/openapi-generator/i.test(e.text)&&/Generated by/i.test(e.text))}function uR(e){let t=Om(e);return(n,r,i,o)=>t(n,r,i,o)?.disposition==="exclude"}function Om(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=oR(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 aa(o))l.add(u);for(let u of l){let d=a.containers.get(u);d&&c.push(...d)}return cW(c)}}function cW(e){if(e.length===0)return null;let n=e.find(r=>r.disposition==="exclude")??e[0];return{disposition:n.disposition,reason:n.reason}}var lW=/(?:^|\/)(?:migrations?\/meta\/|drizzle\/meta\/|prisma\/migrations\/|__generated__\/|generated\/)|(?:^|\/)(?:_journal\.json|migration_lock\.toml)$|(?:^|\/)[^/]*(?:snapshot|\.generated|\.gen)\.[a-z0-9]+$|(?:^|\/)(?:migrations?|drizzle)\/[^/]+\.sql$|(?:^|\/)(?:migrations?|drizzle)\/(?:schema|relations)\.[cm]?[jt]s$/i;function Vc(e){return lW.test(ee(e))}function Bm(e,t={}){no(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function dR(e,t,n={}){no(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function uW(e,t){if(t.isIgnoredPath(e.relativePath))return"ignored-file";if(he(e.symbol))return"module-like-symbol";if(!Jc(e.symbol))return"non-value-symbol";if(!e.isFunctionLike&&e.enclosingSymbol&&Jc(e.enclosingSymbol))return"nested-non-callable-value"}function dW(e,t){if(!t.includeTests&&!gW(e.relativePath))return"test-file";if(!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName))return"excluded-file-region"}function mW(e){let t=A(e.symbol);if(t==="<constructor>")return"implicit-constructor";if(e.symbol.startsWith("scip-python ")){if(t==="__all__")return"python-runtime-metadata";if(/^__[^_].*__$/.test(t))return"python-protocol-member"}}function pW(e,t){if(t.isDeclarationOnlyCallable())return"declaration-only-callable";if(t.isFrameworkContractCallable())return"framework-contract-member";if(ke(e.symbol))return"rust-trait-impl-member"}function fW(e,t){if(ta(e.symbol))return"rust-test-module";if(!t.includeMembers&&!yW(e))return"member";if(e.endLine-e.startLine+1<t.minLoc)return"below-min-loc"}function mR(e,t){let n=uW(e,t)??dW(e,t)??mW(e)??pW(e,t)??fW(e,t);return n===void 0?{accepted:!0}:hW(n)}function gW(e){return F(e)!=="test"}function hW(e){return{accepted:!1,rejectionReason:e}}function Jc(e){return be(e)||e.endsWith("().")||e.endsWith(".")}function yW(e){return Xe(e.symbol)||aa(e.symbol).length===0}function pR(){return new Map}function fR(e,t,n){let r=new Map;for(let i of vg(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||Xc(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function gR(e,t,n,r={}){let i=new Set;if(r.conservative||n.size===0){for(let o of xg(e,t))i.add(o.symbol_id);return i}for(let o of Cg(e,t))e.isIgnored(o.relative_path)||n.has(o.relative_path)||i.add(o.symbol_id);return i}function $m(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 Yc(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 hR(e){return e?.occurrences??0}function Xc(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=bR(e,t,n);o.occurrences+=r,o.sources.add(i)}function yR(e,t,n,r,i){if(r<=0)return;let o=bR(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function bR(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 bW=new Set(["componentDidCatch","componentDidMount","componentDidUpdate","componentWillUnmount","getDerivedStateFromError","getDerivedStateFromProps","getSnapshotBeforeUpdate","render","shouldComponentUpdate","UNSAFE_componentWillMount","UNSAFE_componentWillReceiveProps","UNSAFE_componentWillUpdate"]);function Qc(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=_(e,t.relativePath);if(!n)return!1;let r=n.rootNode.descendantsOfType("method_definition").find(i=>i.startPosition.row<=t.startLine&&i.endPosition.row>=t.endLine);return r?/\boverride\b/.test(r.text.slice(0,Math.max(0,r.text.indexOf("{"))))?!0:SW(r,t.leaf):!1}function SW(e,t){let n=e.parent;for(;n&&n.type!=="class_declaration"&&n.type!=="class";)n=n.parent;if(!n)return!1;let r=n.text.slice(0,Math.max(0,n.text.indexOf("{")));return/\bimplements\b/.test(r)||/\bextends\b/.test(r)?!0:bW.has(t)&&/\bextends\s+(?:React\.)?(?:Component|PureComponent)\b/.test(r)}var vW=64,CW=300;function Pr(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=M("dead.candidates",()=>{let E=ge(xW(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c);return u=E.length,E},()=>({definitions:u})),m=0,p=o?M("dead.inactive-barrels",()=>{let E=new Set(qS(e));return m=E.size,E},()=>({paths:m})):new Set,f=0,g=a?pR():M("dead.mention-reference-counts",()=>{let E=fR(e,p,d.map(b=>b.symbolId));return f=E.size,E},()=>({definitions:d.length,symbolsWithReferences:f})),h=0,y=a?M("dead.mentioned-symbol-ids",()=>{let E=gR(e,d.map(b=>b.symbolId),p,{conservative:p.size===0});return h=E.size,E},()=>({definitions:d.length,referencedSymbols:h})):new Set,S=a?d.filter(E=>!y.has(E.symbolId)):d.filter(E=>!Yc(g,E.symbolId,E.relativePath));a?M("dead.source-fallback.dead-code-only",()=>MW(e,S,g,{inactiveBarrelPaths:p}),()=>({definitions:S.length,testReferencesIncluded:!0})):M("dead.source-fallback.ast",()=>LW(e,S,g,{inactiveBarrelPaths:p}),()=>({definitions:S.length,testReferencesIncluded:!0}));let I=a?S.filter(E=>!$m(g,E.symbolId)):S.filter(E=>!Yc(g,E.symbolId,E.relativePath));M("dead.caller-map-supplement",()=>NW(e,I,g,{inactiveBarrelPaths:p,includeSemantic:!a&&l}),()=>({definitions:I.length,semantic:!a&&l}));let x=a?S.filter(E=>!$m(g,E.symbolId)):d;return PW(e,IW(x,g))}function xW(e,t){let n=uR(e),r=[];for(let i of lo(e,{scope:t.scope,symbolMatches:Jc,sqlPrefilter:"function-like"}))mR(i,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n,isDeclarationOnlyCallable:()=>EW(e,i),isFrameworkContractCallable:()=>Qc(e,i)}).accepted&&r.push(i);return r}var RW=["method_signature","abstract_method_signature","call_signature","construct_signature"];function EW(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=_(e,t.relativePath);if(n)return n.rootNode.descendantsOfType([...RW]).some(i=>i.startPosition.row<=t.startLine&&i.endPosition.row>=t.endLine);let r=j(e,t.relativePath).slice(t.startLine,t.endLine+1).join(`
|
|
83
|
+
`).trim();return r.endsWith(";")&&!r.includes("=>")&&!r.includes("{")}function IW(e,t){return e.map(n=>wW(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 wW(e,t){let n=t.get(e.symbolId)??new Map,r=hR(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 PW(e,t){let n=Om(e),r=[],i=0,o=0,s=0,a=0,c=0,l=0,u=0;for(let d of t){if(e.isIgnored(d.relative_path))continue;if(Ke(e,d.relative_path)){a++;continue}if(Vc(d.relative_path)){l++;continue}if(We(e,d.symbol,d.relative_path)){c++;continue}let m=TW(d,n),p=m.kind;p==="dead-code"?i++:p==="file-internal"?o++:s++,u+=d.loc,r.push(m)}return{symbols:r,counts:{total:r.length,deadCode:i,fileInternal:o,implicitUsage:s,loc:u},applicability:{entrySurfaceExcluded:a,externalRootExcluded:c,generatedArtifactExcluded:l,implicitUsageSignals:s},totalCount:r.length,deadCodeCount:i,fileInternalCount:o,implicitUsageCount:s,totalLoc:u}}function TW(e,t){let n=t(e.relative_path,e.start_line,e.symbol,e.parent_type_name),r=n?.disposition==="implicit-usage"?n.reason:void 0,i=r?"implicit-usage":e.same_file_refs===0?"dead-code":"file-internal";return{relativePath:e.relative_path,startLine:e.start_line,endLine:e.end_line,loc:e.loc,symbol:e.symbol,shortName:L(e.symbol),sameFileRefs:e.same_file_refs,kind:i,...r?{implicitUsageReason:r}:{}}}function LW(e,t,n,r){if(t.length===0)return;let i=new N(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 q(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)&&(FW(e,c)||Xc(n,c.target.symbolId,c.sourceFile,kW(c),"source-fallback"))})}function MW(e,t,n,r){if(t.length===0)return;let i=new N(e),o=fg(t),s=new Set(i.sourceFiles());for(let u of q(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=Ig(e,u),c.set(u,d)),d};i.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>r.inactiveBarrelPaths.has(u),resolveTargets:({sourceFile:u,name:d,kind:m})=>{let p=o.get(d);return p?DW(u,d,p,()=>l(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),dR(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&SR(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||Xc(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function DW(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=AW(n,s.get(t));if(a.length>0)return a;let c=wg(s);for(let l of c){let u=n.filter(d=>ze(l,d.relativePath));if(u.length>0&&u.length===n.length)return u}return i.permissive?[...n]:[]}function FW(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&SR(e,t)}function kW(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function SR(e,t){return t.occurrences>1?!1:V(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function NW(e,t,n,r){let i=r.includeSemantic!==!1,o=i&&t.length>=vW&&q(e).length>=CW,s=(u,d)=>{d===u.relativePath||e.isIgnored(d)||r.inactiveBarrelPaths.has(d)||yR(n,u.symbolId,d,1,"caller-map")};if(o?M("dead.caller-map.per-symbol-non-semantic",()=>{let u=Pn(e,t,{semantic:!1,semanticEvidence:ie});for(let d of t){let m=u.get(d.symbolId)??[];for(let p of m)s(d,p.file)}},()=>({definitions:t.length,semantic:!1,batched:!0})):M("dead.caller-map.per-symbol",()=>{for(let u of t){let d=ti(e,u,{semantic:i,semanticEvidence:ie});if(d.length!==0)for(let m of d)s(u,m.file)}},()=>({definitions:t.length,semantic:i})),!o)return;let a=0,c=M("dead.caller-map.semantic-candidates",()=>{let u=t.filter(d=>!Yc(n,d.symbolId,d.relativePath));return a=u.length,u},()=>({definitions:t.length,semanticCandidates:a}));if(c.length===0)return;let l=Tb(e,c);for(let u of c){let d=l.get(u.symbolId);if(d)for(let m of d)s(u,m)}}function AW(e,t){if(t)for(let n of t){let r=e.filter(i=>ze(n,i.relativePath));if(r.length>0)return r}return[]}function _W(e,t={}){let{limit:n=30,scope:r}=t,i=r?"AND instr(def_d.relative_path, ?) > 0":"",o=r?[r]:[],a=e.all(`SELECT
|
|
84
|
+
gs.symbol,
|
|
85
|
+
COUNT(DISTINCT m.chunk_id) AS ref_count,
|
|
86
|
+
COUNT(DISTINCT ref_d.id) AS file_count,
|
|
87
|
+
def_d.relative_path AS defined_in
|
|
88
|
+
FROM mentions m
|
|
89
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
90
|
+
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
91
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
92
|
+
JOIN (
|
|
93
|
+
SELECT m2.symbol_id, c2.document_id
|
|
94
|
+
FROM mentions m2
|
|
95
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
96
|
+
WHERE m2.role = 1
|
|
97
|
+
GROUP BY m2.symbol_id
|
|
98
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
99
|
+
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
100
|
+
WHERE m.role != 1
|
|
101
|
+
AND def_d.id != ref_d.id
|
|
102
|
+
${e.pathExclusionsFor("def_d")}
|
|
103
|
+
${e.symbolNoiseFor("gs")}
|
|
104
|
+
${i}
|
|
105
|
+
GROUP BY gs.id
|
|
106
|
+
ORDER BY ref_count DESC, gs.symbol
|
|
107
|
+
LIMIT ?`,...o,n).filter(c=>!e.isIgnored(c.defined_in)).map(c=>({symbol:c.symbol,shortName:L(c.symbol),refCount:c.ref_count,fileCount:c.file_count,definedIn:c.defined_in,basis:"scip-cross-file-mentions",countUnit:"referencing-chunks"}));return a.length>0?a:OW(e,r,n)}function OW(e,t,n){return Pe(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>BW(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function BW(e,t){let r=ti(e,t,{semanticEvidence:ie}).filter(i=>i.file!==t.relativePath);return{symbol:t.symbol,shortName:L(t.symbol),refCount:r.length,fileCount:new Set(r.map(i=>i.file)).size,definedIn:t.relativePath,basis:"source-backed-incoming-evidence",countUnit:"distinct-incoming-evidence-rows"}}import{ts as Cn}from"@ts-morph/common";function $W(e,t,n={}){return XW(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile,evidence:r.evidence}))??[]}function jW(e,t){let n=J(e,t);if(n.candidates.length>0)throw new Error(`Ambiguous symbol: ${t}. Use an exact symbol.`);let r=n.match,i=r?UW(e,r.symbol):[];if(!r&&!Zc(t))return[];let o=qW(e,t,r);return Zc(t)&&o.length>0?o:zW([...i,...o])}function HW(e,t,n={}){let r=Ht(e,t);if(!r)return[];let i=xR(e,r),o=n.semantic===!1?null:CR(e,r);return(o?vR(o,i):i).filter(a=>!a.used).map(a=>({symbol:a.symbol,shortName:a.shortName,importedIn:a.importer}))}function vR(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 UW(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
|
|
108
|
+
FROM mentions m
|
|
109
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
110
|
+
JOIN documents d ON c.document_id = d.id
|
|
111
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
112
|
+
WHERE gs.symbol = ?
|
|
113
|
+
AND m.role = 2
|
|
114
|
+
ORDER BY d.relative_path`,t).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:L(r.symbol),fromFile:r.importer,evidence:"indexed-import"}))}function qW(e,t,n){let r=n?.relativePath??null,i=n?A(n.symbol):t.replace(/\(\)$/,""),o=n?he(n.symbol):!1,s=r?WW(e,r,i):new Set([i]),a=new Set;for(let l of q(e,{includeIgnored:!1}))for(let u of V(e,l))GW(u,l,{targetFile:r,targetLeaf:i,exportNames:s,targetIsModule:o,targetPattern:t})&&a.add(l);let c=Zc(t)?t.trim():null;return[...a].sort().map(l=>({symbol:c??n?.symbol??i,shortName:c??(n?L(n.symbol):i),fromFile:l,evidence:"source-import-candidate"}))}function zW(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 GW(e,t,n){return!e.sourcePath||n.targetFile&&ee(e.sourcePath)!==ee(n.targetFile)?!1:e.kind==="side-effect"?!!(n.targetFile&&n.targetIsModule):n.targetFile&&tV(t)?!0:KW(e,n)}function KW(e,t){return e.kind==="namespace"&&YW(e,t.targetPattern)||t.targetIsModule?!0:e.kind==="default"?t.exportNames.has("default"):e.kind==="named"&&t.exportNames.has(e.importedName)?!0:e.kind==="namespace"&&e.usedMembers.some(n=>t.exportNames.has(n))}function WW(e,t,n){let r=new Set([n]);if(!/\.[cm]?[jt]sx?$/.test(t))return r;let i=H(e,t),o=Cn.createSourceFile(t,i,Cn.ScriptTarget.Latest,!0);for(let s of o.statements)if(VW(s)===n&&r.add("default"),Cn.isExportDeclaration(s))for(let a of JW(s))(a.propertyName??a.name).text===n&&r.add(a.name.text);return r}function VW(e){if(Cn.isExportAssignment(e))return!e.isExportEquals&&Cn.isIdentifier(e.expression)?e.expression.text:void 0;if(Cn.isFunctionDeclaration(e)||Cn.isClassDeclaration(e))return e.modifiers?.some(t=>t.kind===Cn.SyntaxKind.DefaultKeyword)?e.name?.text:void 0}function JW(e){return e.moduleSpecifier||!e.exportClause||!Cn.isNamedExports(e.exportClause)?[]:e.exportClause.elements}function YW(e,t){let n=t.trim().replace(/\(\)$/,"");return Zc(n)?e.importedName===n||e.localName===n:!1}function Zc(e){let t=e.trim().replace(/\(\)$/,"");return t.includes(".")&&!t.includes("/")&&!t.includes(":")}function XW(e,t,n={}){let r=Ht(e,t);if(!r)return null;let i=QW(e,r,n)??[],o=xR(e,r),s=n.semantic===!1?null:CR(e,r),a=s?vR(s,o):o;return[...i,...a.filter(c=>!i.some(l=>l.fromFile===c.fromFile&&A(l.symbol)===c.importedName))]}function QW(e,t,n){let i=e.all(`SELECT DISTINCT
|
|
115
|
+
gs.symbol,
|
|
116
|
+
def_d.relative_path AS from_file,
|
|
117
|
+
imp_d.relative_path AS importer,
|
|
118
|
+
EXISTS (
|
|
119
|
+
SELECT 1
|
|
120
|
+
FROM mentions ref_m
|
|
121
|
+
JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
|
|
122
|
+
WHERE ref_m.symbol_id = gs.id
|
|
123
|
+
AND ref_m.role != 1
|
|
124
|
+
AND ref_c.document_id = imp_d.id
|
|
125
|
+
) AS used
|
|
126
|
+
FROM mentions m
|
|
127
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
128
|
+
JOIN documents imp_d ON c.document_id = imp_d.id
|
|
129
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
130
|
+
LEFT JOIN (
|
|
131
|
+
SELECT m2.symbol_id, c2.document_id
|
|
132
|
+
FROM mentions m2
|
|
133
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
134
|
+
WHERE m2.role = 1
|
|
135
|
+
GROUP BY m2.symbol_id
|
|
136
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
137
|
+
LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
138
|
+
WHERE imp_d.relative_path = ?
|
|
139
|
+
AND m.role = 2
|
|
140
|
+
ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(i.length>0){let o=n.semantic===!1?[]:Ho(e,t);return i.map(s=>({symbol:s.symbol,shortName:L(s.symbol),fromFile:s.from_file??"(external)",importer:s.importer,used:s.used!==0||o.some(a=>a.isUsed&&a.sourcePath===s.from_file),evidence:"indexed-import"}))}return null}function CR(e,t){let n=Ho(e,t);return n.length>0?n.map(r=>{let i=RR(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,importedName:r.importedName,evidence:"semantic-import"}}):null}function xR(e,t){let n=ZW(t,H(e,t));return V(e,t).map(r=>{let i=RR(r.importedName,r.localName,r.kind),o=r.kind==="side-effect"||eV(t,r)||n.has(r.localName??r.importedName)?!0:r.used;return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:o,importedName:r.importedName,evidence:"source-import-candidate"}})}function ZW(e,t){let n=new Set;if(se(e)!=="python")return n;let r=/(?:^|\n)\s*__all__\s*(?:\+?=)\s*[[(]([\s\S]*?)[\])]/g;for(let i of t.matchAll(r)){let o=i[1]??"";for(let s of o.matchAll(/(['"])([A-Za-z_]\w*)\1/g))n.add(s[2])}return n}function eV(e,t){if(se(e)!=="rust"||t.used||t.kind==="side-effect")return!1;let n=t.localName??t.importedName;return n==="_"||/^[A-Z]/.test(n)}function RR(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 tV(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function nV(e,t){let n=Bt(e,t);if(!n)return[];let r=D(e,n.relativePath),i=new Set(r.map(a=>a.symbol)),o=pg(e,n.relativePath),s=D(e,n.relativePath,{includeClassMemberFallbacks:!0}).filter(a=>a.symbol!==n.symbol).filter(a=>na(n.symbol,a.symbol)).map(a=>({symbol:a.symbol,shortName:L(a.symbol),startLine:i.has(a.symbol)?a.startLine:o.get(a.symbol)?.start_line??a.startLine,endLine:i.has(a.symbol)?a.endLine:o.get(a.symbol)?.end_line??a.endLine,kind:vt(a.symbol)??"unknown"})).sort((a,c)=>a.startLine-c.startLine||a.endLine-c.endLine);return se(n.relativePath)!=="clojure"?s:iV(s,rV(e,n))}function rV(e,t){let n=A(t.symbol);if(!n)return[];let r=L(t.symbol);return(z(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 iV(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 el(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
|
|
141
|
+
FROM mentions m
|
|
142
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
143
|
+
JOIN (
|
|
144
|
+
SELECT m2.symbol_id, c2.document_id
|
|
145
|
+
FROM mentions m2
|
|
146
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
147
|
+
WHERE m2.role = 1
|
|
148
|
+
GROUP BY m2.symbol_id
|
|
149
|
+
) sym_def ON sym_def.symbol_id = m.symbol_id
|
|
150
|
+
WHERE m.symbol_id = ?
|
|
151
|
+
AND m.role != 1
|
|
152
|
+
AND sym_def.document_id != c.document_id`,t)?.file_count??0}function oV(e,t){let n=J(e,t);if(n.candidates.length>0)throw new Error(`Ambiguous symbol: ${t}. Use an exact SCIP symbol or file:line.`);let r=n.match;return r?[{name:L(r.symbol),count:el(e,r.symbolId),symbol:r.symbol,definedIn:r.relativePath}]:[]}function sV(e,t){let n=Ht(e,t);return n?e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
|
|
153
|
+
FROM mentions m
|
|
154
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
155
|
+
JOIN documents d ON c.document_id = d.id
|
|
156
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
157
|
+
JOIN (
|
|
158
|
+
SELECT m2.symbol_id, c2.document_id
|
|
159
|
+
FROM mentions m2
|
|
160
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
161
|
+
WHERE m2.role = 1
|
|
162
|
+
GROUP BY m2.symbol_id
|
|
163
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
164
|
+
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
165
|
+
WHERE d.relative_path = ?
|
|
166
|
+
AND m.role != 1
|
|
167
|
+
AND def_d.id != d.id
|
|
168
|
+
GROUP BY d.id
|
|
169
|
+
ORDER BY symbol_count DESC, d.relative_path`,n).filter(o=>!e.isIgnored(o.relative_path)).map(o=>({name:o.relative_path,count:o.symbol_count,file:o.relative_path,basis:"external-symbol-references"})):[]}function aV(e,t={}){return cV(e,t).map(n=>({name:L(n.symbol),count:n.file_count,symbol:n.symbol,definedIn:n.defined_in}))}function cV(e,t){let{limit:n=30,scope:r}=t,i=r?"AND instr(def_d.relative_path, ?) > 0":"",o=r?[r]:[];return e.all(`SELECT gs.symbol,
|
|
170
|
+
COUNT(DISTINCT c.document_id) AS file_count,
|
|
171
|
+
def_d.relative_path AS defined_in
|
|
172
|
+
FROM mentions m
|
|
173
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
174
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
175
|
+
JOIN (
|
|
176
|
+
SELECT m2.symbol_id, c2.document_id
|
|
177
|
+
FROM mentions m2
|
|
178
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
179
|
+
WHERE m2.role = 1
|
|
180
|
+
GROUP BY m2.symbol_id
|
|
181
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
182
|
+
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
183
|
+
WHERE m.role != 1
|
|
184
|
+
AND def_d.id != c.document_id
|
|
185
|
+
${e.pathExclusionsFor("def_d")}
|
|
186
|
+
${e.symbolNoiseFor("gs")}
|
|
187
|
+
${i}
|
|
188
|
+
GROUP BY gs.id
|
|
189
|
+
HAVING file_count > 0
|
|
190
|
+
ORDER BY file_count DESC, gs.symbol
|
|
191
|
+
LIMIT ?`,...o,n)}function lV(e,t={}){let{limit:n=30,scope:r}=t,i=r?"AND instr(d.relative_path, ?) > 0":"",o=r?[r]:[];return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
|
|
192
|
+
FROM mentions m
|
|
193
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
194
|
+
JOIN documents d ON c.document_id = d.id
|
|
195
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
196
|
+
JOIN (
|
|
197
|
+
SELECT m2.symbol_id, c2.document_id
|
|
198
|
+
FROM mentions m2
|
|
199
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
200
|
+
WHERE m2.role = 1
|
|
201
|
+
GROUP BY m2.symbol_id
|
|
202
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
203
|
+
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
204
|
+
WHERE m.role != 1
|
|
205
|
+
AND def_d.id != d.id
|
|
206
|
+
${e.pathExclusionsFor("d")}
|
|
207
|
+
${e.symbolNoiseFor("gs")}
|
|
208
|
+
${i}
|
|
209
|
+
GROUP BY d.id
|
|
210
|
+
ORDER BY symbol_count DESC, d.relative_path
|
|
211
|
+
LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}))}var ER=`SELECT COUNT(*) AS shared
|
|
212
|
+
FROM (
|
|
213
|
+
SELECT definition_m.symbol_id
|
|
214
|
+
FROM documents definition_d
|
|
215
|
+
JOIN chunks definition_c ON definition_c.document_id = definition_d.id
|
|
216
|
+
JOIN mentions definition_m ON definition_m.chunk_id = definition_c.id
|
|
217
|
+
AND definition_m.role = 1
|
|
218
|
+
JOIN mentions reference_m ON reference_m.symbol_id = definition_m.symbol_id
|
|
219
|
+
AND reference_m.role != 1
|
|
220
|
+
JOIN chunks reference_c ON reference_c.id = reference_m.chunk_id
|
|
221
|
+
JOIN documents reference_d ON reference_d.id = reference_c.document_id
|
|
222
|
+
WHERE definition_d.relative_path = ?
|
|
223
|
+
AND reference_d.relative_path = ?
|
|
224
|
+
UNION
|
|
225
|
+
SELECT definition_m.symbol_id
|
|
226
|
+
FROM documents definition_d
|
|
227
|
+
JOIN chunks definition_c ON definition_c.document_id = definition_d.id
|
|
228
|
+
JOIN mentions definition_m ON definition_m.chunk_id = definition_c.id
|
|
229
|
+
AND definition_m.role = 1
|
|
230
|
+
JOIN mentions reference_m ON reference_m.symbol_id = definition_m.symbol_id
|
|
231
|
+
AND reference_m.role != 1
|
|
232
|
+
JOIN chunks reference_c ON reference_c.id = reference_m.chunk_id
|
|
233
|
+
JOIN documents reference_d ON reference_d.id = reference_c.document_id
|
|
234
|
+
WHERE definition_d.relative_path = ?
|
|
235
|
+
AND reference_d.relative_path = ?
|
|
236
|
+
)`;function uV(e,t,n){let r=bo(e,t),i=bo(e,n);if(!r||!i)throw new Error("Coupling requires two uniquely resolved indexed files. Use exact project paths.");if(r===i)throw new Error("Coupling requires two distinct files.");let o=e.get(ER,r,i,i,r);return{...IR(r,i,o?.shared??0)}}function dV(e,t={}){let{limit:n=20,scope:r}=t,i=r?"AND instr(def_d.relative_path, ?) > 0 AND instr(ref_d.relative_path, ?) > 0":"",o=r?[r,r]:[];return e.all(`SELECT
|
|
237
|
+
CASE WHEN def_d.relative_path < ref_d.relative_path THEN def_d.relative_path ELSE ref_d.relative_path END AS file1,
|
|
238
|
+
CASE WHEN def_d.relative_path < ref_d.relative_path THEN ref_d.relative_path ELSE def_d.relative_path END AS file2,
|
|
239
|
+
COUNT(DISTINCT gs.id) AS shared
|
|
240
|
+
FROM mentions m
|
|
241
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
242
|
+
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
243
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
244
|
+
JOIN (
|
|
245
|
+
SELECT m2.symbol_id, c2.document_id
|
|
246
|
+
FROM mentions m2
|
|
247
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
248
|
+
WHERE m2.role = 1
|
|
249
|
+
GROUP BY m2.symbol_id
|
|
250
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
251
|
+
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
252
|
+
WHERE m.role != 1
|
|
253
|
+
AND def_d.id != ref_d.id
|
|
254
|
+
${e.pathExclusionsFor("def_d","ref_d")}
|
|
255
|
+
${i}
|
|
256
|
+
GROUP BY file1, file2
|
|
257
|
+
ORDER BY shared DESC, file1, file2
|
|
258
|
+
LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.file1)&&!e.isIgnored(a.file2)).map(a=>IR(a.file1,a.file2,a.shared))}function IR(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 ut(e){let t=new Map,n=[],r=new Map,i=new Map,o=new Set,s=[],a=0,c=m=>(e.get(m)??[]).values();function l(m,p){r.set(m,a),i.set(m,a),a+=1,s.push(m),o.add(m),p.push({node:m,iter:c(m),pendingChild:null})}function u(m){if(i.get(m)!==r.get(m))return;let p=[];for(;;){let f=s.pop();if(o.delete(f),p.push(f),t.set(f,n.length),f===m)break}n.push(p)}function d(m){let p=m[m.length-1];if(p.pendingChild!==null){let h=p.pendingChild;p.pendingChild=null,i.set(p.node,Math.min(i.get(p.node),i.get(h)))}let f=p.iter.next();if(f.done){u(p.node),m.pop();return}let g=f.value;r.has(g)?o.has(g)&&i.set(p.node,Math.min(i.get(p.node),r.get(g))):(p.pendingChild=g,l(g,m))}for(let m of e.keys()){if(r.has(m))continue;let p=[];for(l(m,p);p.length>0;)d(p)}return{components:n,componentOf:t}}function jm(e,t={}){return MR(e,t).cycles}function MR(e,t={}){return Hm(e,t)}function gs(e,t={}){return Hm(e,t).cycles}function Hm(e,t={}){let{scope:n,maxDepth:r=10,edgeBasis:i="symbol-references"}=t,o=Fe(e,n,i==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-and-reexports"}:void 0),{components:s}=ut(o),a=s.filter(c=>DR(o,c)).map(c=>{let l=[...c].sort(),{path:u,kind:d}=mV(o,l);return{path:u,component:l,edgeBasis:i,witness:!0,classification:d==="real"?"dependency-cycle":"module-structure-candidate",kind:d}});return a.sort((c,l)=>c.kind!==l.kind?c.kind==="real"?-1:1:c.path.length-l.path.length),{cycles:a,truncated:!1,edgeBasis:i,maxDepth:r}}function mV(e,t){let n=wR(e,t),r=new Set(t.filter(c=>pV(c)));if(r.size===0)return{path:n,kind:PR(n)};let i=new Set(t),o=new Map;for(let c of t)r.has(c)||o.set(c,new Set([...e.get(c)??[]].filter(l=>i.has(l)&&!r.has(l))));let s=ut(o).components.filter(c=>DR(o,c)).map(c=>[...c].sort()).sort((c,l)=>c[0].localeCompare(l[0]))[0];if(!s)return{path:n,kind:"module-hierarchy"};let a=wR(o,s);return{path:a,kind:PR(a)}}function pV(e){let t=F(e);return t==="test"||t==="barrel"||t==="entry"||Sr(e)}function DR(e,t){if(t.length>1)return!0;let n=t[0];return n!==void 0&&e.get(n)?.has(n)===!0}function wR(e,t){let n=t[0];if(!n)return[];let r=new Set(t);for(let i of[...e.get(n)??[]].filter(o=>r.has(o)).sort()){if(i===n)return[n,n];let o=fV(e,i,n,r);if(o)return[n,...o]}throw new Error(`Cyclic component did not contain a witness path from ${n}.`)}function fV(e,t,n,r){let i=[t],o=new Map([[t,null]]);for(let s=0;s<i.length;s+=1){let a=i[s];if(a===n){let c=[];for(let l=a;l!==null;l=o.get(l)??null)c.push(l);return c.reverse()}for(let c of[...e.get(a)??[]].filter(l=>r.has(l)).sort())o.has(c)||(o.set(c,a),i.push(c))}return null}function PR(e){for(let r of e)if(gV(r))return"module-hierarchy";if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":hV(t,n)}function gV(e){let t=F(e);return t==="test"||t==="barrel"||t==="entry"}function hV(e,t){return Sr(e)||Sr(t)||TR(e,t)||TR(t,e)||LR(e,t)||LR(t,e)||F(e)==="entry"||F(t)==="entry"?"module-hierarchy":"real"}function TR(e,t){if(!e.endsWith(".rs")||!t.endsWith(".rs"))return!1;let n=t.replace(/\.rs$/,"/");return e.startsWith(n)?!e.slice(n.length).includes("/"):!1}function LR(e,t){if(!e.endsWith(".rs")||!t.endsWith(".rs"))return!1;let n=e.replace(/\.rs$/,""),r=t.replace(/\.rs$/,"");if(n===r+"_tests"||n===r+"/tests")return!0;let i=e.split("/"),o=t.split("/");if(i.length===o.length&&i.includes("tests")&&o.includes("src")){let s=i[i.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}function Ft(e,t){let n=FR(e),r=FR(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 FR(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}import{readdirSync as yV}from"fs";import{join as kR}from"path";function bV(e){return NR(e).replace(/\/\*\*?$/,"")}function tl(e,t){let n=NR(t),r=bV(n),i=n.endsWith("/**"),o=[],s=(a,c)=>{let l;try{l=yV(a,{withFileTypes:!0})}catch{return}for(let u of l){if(u.name.startsWith("."))continue;let d=c?`${c}/${u.name}`:u.name;Ft(n,d)&&o.push(d),i&&u.isDirectory()&&s(kR(a,u.name),d)}};return s(kR(e,r),r),o.sort()}function NR(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}var SV=/\.(test|spec)\.(ts|tsx|js|jsx|mts|cts)$/,AR=new Map;function _R(e,t,n,r){if(!t?.testPaths?.length)return[];let i=CV(t),o=[];for(let s of xV(e,t.testPaths)){let a=RV(e,s,r),c=a?n(a):null;c&&vV(e,s,c,n,i,o)}return EV(o)}function vV(e,t,n,r,i,o){for(let s of V(e,t)){let a=s.sourcePath;if(!a)continue;let c=r(a);c&&c!==n&&(i.get(n)?.has(c)||o.push({testFile:t,ownerBoundary:n,importedFile:a,importedBoundary:c,reason:"outside-owner-policy"}))}}function CV(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 xV(e,t){let n=`${e.config.projectRoot}\0${t.join("\0")}`,r=AR.get(n);if(r)return r;let i=new Set;for(let s of t)for(let a of tl(e.config.projectRoot,s))SV.test(a)&&i.add(a);let o=[...i].sort();return AR.set(n,o),o}function RV(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=V(e,t).map(s=>s.sourcePath).filter(s=>!!s&&n(s)&&s.split("/").pop()===i);return o.length===1?o[0]:null}function EV(e){let t=new Map;for(let n of e){let r=`${n.testFile}\0${n.importedBoundary}`;t.has(r)||t.set(r,n)}return[...t.values()].sort((n,r)=>n.testFile.localeCompare(r.testFile)||n.importedBoundary.localeCompare(r.importedBoundary))}function Tr(e,t){let n=(e?.boundaries??[]).filter(r=>r.paths.some(i=>Ft(i,t)));return n.length===1?n[0].name:null}import Mr from"path";import{isBuiltin as FV}from"module";import{ts as BR}from"@ts-morph/common";import $n from"path";import{ts as Lr}from"@ts-morph/common";var IV={allowJs:!0,moduleResolution:Lr.ModuleResolutionKind.Node10};function nl(e,t,n){let r=new Set(e),i=new Map,o=[],s=p=>{if(i.has(p))return i.get(p);if(!(!p.endsWith(".json")||!r.has(p)))try{let f=n(p);return f!==void 0&&i.set(p,f),f}catch(f){o.push(`${p}: configuration unavailable: ${f instanceof Error?f.message:String(f)}`);return}},a=eu(Lr,e,s),c=wV(t),l=PV(r,c,a,o),u=new Set,d=LV(r,c,s,o,u);for(let p of e)(p==="package.json"||p.endsWith("/package.json"))&&s(p);r.has(".scipquery.json")&&s(".scipquery.json");let m=eu(Lr,e,p=>i.get(p));return{inputs:i,inventory:r,configs:l,packages:d,host:MV(m,d),problems:o,architecture:DV(i.get(".scipquery.json"),o),resolutionCaches:new Map,fileConfigs:new Map,ambiguousPackages:u}}function wV(e){let t=new Set(["."]);for(let n of e){let r=$n.posix.dirname(n);for(;!t.has(r);)t.add(r),r=$n.posix.dirname(r)}return t}function PV(e,t,n,r){let i=[...t].flatMap(a=>["tsconfig.json","jsconfig.json"].map(l=>$n.posix.join(a,l)).filter(l=>e.has(l)).slice(0,1)),o=new Set,s=[];for(let a=0;a<i.length;a++){let c=i[a];if(o.has(c))continue;o.add(c);let l=TV(c,n,r);if(!l)continue;let u="/"+c;s.push({file:c,directory:$n.posix.dirname(u),files:new Set(l.fileNames),options:l.options});for(let d of l.projectReferences??[]){let m=d.path.endsWith(".json")?d.path:$n.posix.join(d.path,"tsconfig.json");i.push(m.replace(/^\//,""))}}return s}function TV(e,t,n){let r="/"+e,i=Lr.readConfigFile(r,t.readFile);if(i.error){n.push(`${e}: ${Lr.flattenDiagnosticMessageText(i.error.messageText," ")}`);return}let o=Lr.parseJsonConfigFileContent(i.config,t,$n.posix.dirname(r),void 0,r);for(let s of o.errors)s.code!==18003&&s.code!==18002&&n.push(`${e}: ${Lr.flattenDiagnosticMessageText(s.messageText," ")}`);return o}function LV(e,t,n,r,i){let o=new Map;for(let s of t){let a=$n.posix.join(s,"package.json");if(e.has(a))try{let c=JSON.parse(n(a)??"{}");if(!k(c)||typeof c.name!="string"||i.has(c.name))continue;let l=o.get(c.name);if(l&&l!==s){r.push(`${a}: repository package name ${c.name} is also declared in ${l}.`),i.add(c.name),o.delete(c.name);continue}o.set(c.name,s)}catch{r.push(`${a}: malformed package metadata.`)}}return o}function MV(e,t){let n=r=>{let i="/node_modules/",o=r.lastIndexOf(i);if(o<0)return r;let s=r.slice(o+i.length),a=rl(s),c=t.get(a);return c===void 0?r:$n.posix.join("/",c,s.slice(a.length))};return{...e,fileExists:r=>e.fileExists(n(r)),readFile:r=>e.readFile(n(r)),directoryExists:r=>r.endsWith("/node_modules")||e.directoryExists?.(n(r))===!0,realpath:n}}function rl(e){return e.startsWith("@")?e.split("/").slice(0,2).join("/"):e.split("/")[0]}function Um(e,t){let n=e.fileConfigs.get(t);if(n)return n;let r="/"+t,i=e.configs.filter(c=>c.files.has(r)),o=i.length?i:e.configs.filter(c=>r.startsWith(c.directory.replace(/\/$/,"")+"/")),s=Math.max(...o.map(c=>c.directory.length)),a=o.length?o.filter(c=>c.directory.length===s):[{file:"",directory:"/",files:new Set,options:IV}];return e.fileConfigs.set(t,a),a}function OR(e,t,n){return n.startsWith(".")||n.startsWith("/")||n.startsWith("#")||e.packages.has(rl(n))?!0:Um(e,t).some(r=>Object.keys(r.options.paths??{}).some(i=>{let[o,s]=i.split("*");return s===void 0?n===i:n.startsWith(o)&&n.endsWith(s)}))}function DV(e,t){if(e===void 0)return;let n=mr(e);if(n.kind==="malformed"||n.kind==="unsupported"){t.push(`.scipquery.json: ${n.kind==="malformed"?n.reason:"unsupported schema version"}`);return}let r=[];if(Za(n.config,r),r.some(i=>i.level==="error")){t.push(...r.map(i=>`.scipquery.json ${i.path}: ${i.message}`));return}return n.config.architecture}function qm(e,t,n,r){let i=[],o=Um(n,e.fileName);for(let s of Fg(e,r)){let{literal:a,...c}=s,l=a?kV(n,t,e.fileName,s.specifier,o):{resolution:"dynamic"};i.push({...c,file:e.fileName,role:F(e.fileName)==="test"?"test":"production",configs:o.map(u=>u.file).filter(Boolean),...l})}return i}function kV(e,t,n,r,i){if(FV(r))return{resolution:"builtin"};let o=NV(e,n,r);if(o)return{resolution:"excluded",target:o};if(e.ambiguousPackages.has(rl(r)))return{resolution:"ambiguous",alternatives:[]};let s=i.map(l=>{let u=e.resolutionCaches.get(l.file);return u||(u=BR.createModuleResolutionCache("/",d=>d,{allowJs:!0,...l.options}),e.resolutionCaches.set(l.file,u)),BR.resolveModuleName(r,"/"+n,{allowJs:!0,...l.options},e.host,u).resolvedModule?.resolvedFileName}),a=[...new Set(s.filter(l=>l!==void 0).map(l=>Mr.posix.normalize(e.host.realpath?.(l)??l).replace(/^\//,"")))];if(a.length>1||a.length===1&&s.some(l=>!l))return{resolution:"ambiguous",alternatives:a};let c=a[0];return c?{resolution:t.has(c)?"internal":"excluded",target:c}:AV(e,n,r)}function NV(e,t,n){if(!n.startsWith("."))return;let r=Mr.posix.normalize(Mr.posix.join(Mr.posix.dirname(t),n));return e.inventory.has(r)&&!/\.[cm]?[jt]sx?$/.test(r)?r:void 0}function AV(e,t,n){let r=Mr.posix.normalize(Mr.posix.join(Mr.posix.dirname(t),n));return n.startsWith(".")&&ca(r)?{resolution:"excluded",excludedReason:`Requested managed output ${r}; build/install existence is not established by the source inventory.`}:{resolution:OR(e,t,n)?"missing":"external"}}function $R(e,t,n){let r={imports:[],unavailable:[]},i=_V(e,t,r);if(i.size===0)return r;let o=nl(Br(e),[...i.keys()],s=>te(e,s));for(let[s,a]of i){if(n&&!s.includes(n))continue;let c=Dg(s,a),l=[...o.problems,...c.errors];l.length?r.unavailable.push({file:s,reason:l.join("; ")}):r.imports.push(...qm(c.sourceFile,i,o,c.checker))}return r}function _V(e,t,n){let r=new Map;for(let i of t.filter(o=>/\.[cm]?[jt]sx?$/.test(o)))try{r.set(i,te(e,i))}catch(o){n.unavailable.push({file:i,reason:`current source unavailable: ${o instanceof Error?o.message:String(o)}`})}return r}var xn="architecture:";function il(e,t,n,r={}){let i=r.scope?{scope:r.scope,limitations:["A file-filtered projection cannot establish repository-wide cycle freedom, size compliance or unused allowances. Rerun architecture without --scope for full policy evaluation."]}:{},o=e,s=UR(e,t),a=t2(e,n);e=a.graph;let c={excludedTestEdges:a.excludedTestEdges,basis:"production-imports-including-types",cycleMeaning:"Boundary cycles concern declared groups. File cycle members, when present, concern observed imports including types and deferred imports; neither establishes a runtime initialization failure."};if(!n||n.boundaries.length===0)return{configured:!1,dependencyRoles:c,boundaries:[],edges:[],forbiddenEdges:[],reciprocalPairs:[],cycles:[],coarseBoundaries:[],staleAllowances:[],boundaryLimits:[],fragileEdges:[],testBoundaryViolations:[],coverage:{...i,totalFiles:s.length,mappedFiles:0,unmappedFiles:s,ambiguousFiles:[]},policyCoverage:{declaredRows:0,totalBoundaries:0,missingRows:[],requiresCompletePolicy:!1,requiresCompleteCoverage:!1,requiresMinimalPolicy:!1}};let{resolved:l,filesByBoundary:u,unmappedFiles:d,ambiguousFiles:m}=OV(s,n),p=jR(e,l,n),f=new Map([...o].map(([R,P])=>[R,new Set([...P].filter(w=>!e.get(R)?.has(w)))])),g=jR(f,l,n),h=p,y=new Map(h.map(R=>[_i(R.from,R.to),R])),S=new Map(n.boundaries.map(R=>[R.name,new Set]));for(let R of h)S.get(R.from).add(R.to);let I=BV(h,y),x=ut(e).components.filter(R=>R.length>1&&new Set(R.map(P=>l.get(P)).filter(Boolean)).size>1),{components:E}=ut(S),b=E.filter(R=>R.length>1).map(R=>{let P=KV(R,h,n.requireAcyclic===!0),w=new Set(R),T=x.filter(G=>G.every(K=>w.has(l.get(K)??""))).flat();return{...P,origin:T.length>0?"contains-file-cycle":"grouping-only",fileCycleMembers:[...new Set(T)].sort()}}).sort((R,P)=>P.boundaries.length-R.boundaries.length||R.boundaries.join("/").localeCompare(P.boundaries.join("/"))),v=n.allowedDependencies??{},C=n.boundaries.map(R=>R.name).filter(R=>!Object.hasOwn(v,R)).sort();return{configured:!0,dependencyRoles:c,testEdges:g,testForbiddenEdges:g.filter(R=>R.policyStatus==="forbidden"),boundaries:n.boundaries.map(R=>({name:R.name,paths:[...R.paths],fileCount:u.get(R.name).size,dependencyPolicyDeclared:Object.hasOwn(v,R.name)})).sort((R,P)=>R.name.localeCompare(P.name)),edges:p,forbiddenEdges:h.filter(R=>R.policyStatus==="forbidden"),reciprocalPairs:I,cycles:b,staleAllowances:r.scope?[]:YV(n,[...h,...g],u),boundaryLimits:XV(n,h,u),fragileEdges:h.filter(R=>R.fragile),testBoundaryViolations:r.testBoundaryViolations??[],coarseBoundaries:WV(e,u,r.isModuleHierarchyFile,n.requireResolvedBoundaries===!0,R=>n.boundaries.find(P=>P.name===R)?.subUnits??"directory"),coverage:{...i,totalFiles:s.length,mappedFiles:l.size,unmappedFiles:d,ambiguousFiles:m},policyCoverage:{declaredRows:n.boundaries.length-C.length,totalBoundaries:n.boundaries.length,missingRows:C,requiresCompletePolicy:n.requireCompletePolicy===!0,requiresCompleteCoverage:n.requireCompleteCoverage===!0,requiresMinimalPolicy:n.requireMinimalPolicy===!0}}}function OV(e,t){let n=new Map,r=new Map(t.boundaries.map(s=>[s.name,new Set])),i=[],o=[];for(let s of e){let a=t.boundaries.filter(c=>c.paths.some(l=>Ft(l,s))).map(c=>c.name).sort();if(a.length===0)i.push(s);else if(a.length>1)o.push({file:s,boundaries:a});else{let c=a[0];n.set(s,c),r.get(c).add(s)}}return{resolved:n,filesByBoundary:r,unmappedFiles:i,ambiguousFiles:o}}function BV(e,t){let n=[];for(let r of e){if(r.from>=r.to)continue;let i=t.get(_i(r.to,r.from));i&&n.push({boundaries:[r.from,r.to],forward:r,reverse:i})}return n}function hs(e,t={}){let n=q(e,{includeIgnored:!1}),{graph:r,unresolved:i}=$V(e,n,t.scope),o=n.filter(c=>!t.scope||c.includes(t.scope)),s=new Set(o),a=il(r,o,e.config.architecture,{scope:t.scope,isModuleHierarchyFile:c=>HV(e,c),testBoundaryViolations:_R(e,e.config.architecture,c=>Tr(e.config.architecture,c),c=>s.has(c))});return a.coverage.limitations=[...a.coverage.limitations??[],"This graph covers indexed documents and observed import/re-export relationships, supplemented by compiler-resolved current TS/JS imports (including literal dynamic imports, import types and unshadowed CommonJS). Unindexed files, nonliteral imports and unsupported relationships cannot establish repository-wide absence; allowances from boundaries without observed source files are not classified as unused."],jV(a,i,e.config.architecture),a}function $V(e,t,n){let r=Fe(e,n,{scipEdges:"imports-only",sourceEdges:"imports-and-reexports"}),i=new Map([...r].map(([a,c])=>[a,new Set(c)])),o=$R(e.config.projectRoot,t,n),s=o.unavailable;for(let a of o.imports){if(["internal","external","builtin"].includes(a.resolution)||s.push({file:a.file,reason:`${a.line}: ${a.specifier} (${a.resolution})`}),a.resolution!=="internal"||!a.target)continue;let c=i.get(a.file)??new Set;c.add(a.target),i.set(a.file,c)}return{graph:i,unresolved:s}}function jV(e,t,n){if(t.length===0)return;let r=new Set(t.map(i=>Tr(n,i.file)));e.staleAllowances=e.staleAllowances.filter(i=>!r.has(i.from)),e.coverage.limitations??=[],e.coverage.limitations.push("Unused-allowance claims are withheld for owners with unavailable or unresolved current TS/JS imports:",...t.map(i=>`${i.file}: ${i.reason}`))}function HV(e,t){let n=F(t);return n==="test"||n==="entry"?!0:n!=="barrel"?!1:D(e,t).length===0}function zm(e){let t=[...e.forbiddenEdges,...e.testForbiddenEdges??[]].map(n=>`${xn}forbidden-edge:${encodeURIComponent(n.from)}:${encodeURIComponent(n.to)}`);t.push(...UV(e));for(let n of e.testBoundaryViolations)t.push(`${xn}test-boundary:${encodeURIComponent(n.testFile)}:${encodeURIComponent(n.importedBoundary)}`);for(let n of e.boundaryLimits)t.push(`${xn}boundary-limit:${n.kind}:${encodeURIComponent(n.boundary)}`);t.push(...qV(e.coarseBoundaries));for(let n of e.cycles)n.violatesPolicy&&t.push(`${xn}cycle:${n.boundaries.map(r=>encodeURIComponent(r)).sort().join("|")}`);return[...new Set(t)].sort()}function UV(e){let t=[];if(e.policyCoverage.requiresCompletePolicy)for(let n of e.policyCoverage.missingRows)t.push(`${xn}missing-policy-row:${encodeURIComponent(n)}`);if(e.policyCoverage.requiresCompleteCoverage){for(let n of e.coverage.unmappedFiles)t.push(`${xn}unmapped-file:${encodeURIComponent(n)}`);for(let n of e.coverage.ambiguousFiles)t.push(`${xn}ambiguous-file:${encodeURIComponent(n.file)}:${n.boundaries.map(r=>encodeURIComponent(r)).sort().join("|")}`)}if(e.policyCoverage.requiresMinimalPolicy)for(let n of e.staleAllowances)t.push(`${xn}stale-allowance:${encodeURIComponent(n.from)}:${encodeURIComponent(n.to)}`);return t}function qV(e){let t=[],n=new Map;for(let r of e)r.violatesPolicy&&n.set(r.boundary,(n.get(r.boundary)??0)+1);for(let[r,i]of n){let o=`${xn}coarse-boundary:${encodeURIComponent(r)}`;t.push(o);for(let s=2;s<=i;s+=1)t.push(`${o}:component:${s}`)}return t}function UR(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 zV(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:GV(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 GV(e,t,n){return!e.allowedDependencies||!Object.hasOwn(e.allowedDependencies,t)?"undeclared":e.allowedDependencies[t].includes(n)?"allowed":"forbidden"}function KV(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 WV(e,t,n=QV,r=!1,i=()=>"directory"){let o=[];for(let[s,a]of t){let c=i(s)==="file"?m=>m:ZV,l=[...a].filter(m=>!n(m));if(l.length<2)continue;let{edges:u,subGraph:d}=VV(e,l,c);for(let m of JV(s,r,u,d))o.push(m)}return o.sort((s,a)=>a.subUnits.length-s.subUnits.length||s.boundary.localeCompare(a.boundary))}function VV(e,t,n){let r=new Set(t),i=new Map,o=new Map;for(let s of t)o.set(n(s),new Set);for(let s of t)for(let a of e.get(s)??[]){if(!r.has(a))continue;let c=n(s),l=n(a);if(c===l)continue;let u=_i(c,l),d=i.get(u);d||(d={from:c,to:l,fileEdges:[]},i.set(u,d)),d.fileEdges.push({fromFile:s,toFile:a}),o.get(c).add(l)}return{edges:i,subGraph:o}}function JV(e,t,n,r){let i=[],{components:o}=ut(r);for(let s of o){if(s.length<2)continue;let a=new Set(s),c=[...n.values()].filter(u=>a.has(u.from)&&a.has(u.to)).map(u=>({from:u.from,to:u.to,fileEdgeCount:u.fileEdges.length,examples:u.fileEdges.slice(0,5)})).sort((u,d)=>u.from.localeCompare(d.from)||u.to.localeCompare(d.to)),l=Math.min(...c.map(u=>u.fileEdgeCount));i.push({boundary:e,violatesPolicy:t,subUnits:[...s].sort(),internalEdges:c,narrowestEdges:c.filter(u=>u.fileEdgeCount===l)})}return i}function YV(e,t,n){let r=new Set(t.map(a=>_i(a.from,a.to))),i=e.allowedDependencies??{},o=new Set(e.boundaries.map(a=>a.name)),s=[];for(let[a,c]of Object.entries(i))if(n.get(a)?.size)for(let l of c)!o.has(l)||r.has(_i(a,l))||s.push({from:a,to:l});return s.sort((a,c)=>a.from.localeCompare(c.from)||a.to.localeCompare(c.to))}function XV(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){HR(r,o.name,"fan-out",i.get(o.name)??0,e.maxBoundaryFanOut);let s=o.maxFiles??e.maxBoundaryFiles;HR(r,o.name,"files",n.get(o.name)?.size??0,s)}return r.sort((o,s)=>o.boundary.localeCompare(s.boundary)||o.kind.localeCompare(s.kind))}function QV(e){let t=F(e);return t==="test"||t==="entry"}function ZV(e){let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)}function _i(e,t){return`${e}\0${t}`}function e2(e,t){return e.from.localeCompare(t.from)||e.to.localeCompare(t.to)}function t2(e,t){let n=new Set(UR(e,[]).filter(o=>F(o)==="test"||/(^|\/)(fixtures|benchmarks)(\/|$)/.test(o)||(t?.testPaths??[]).some(s=>Ft(s,o)))),r=new Map,i=0;for(let[o,s]of e){let a=new Set;for(let c of s)n.has(o)||n.has(c)?i++:a.add(c);r.set(o,a)}return{graph:r,excludedTestEdges:i}}function jR(e,t,n){let r=new Map;for(let[i,o]of e){let s=t.get(i);if(s)for(let a of o){let c=t.get(a);if(!c||s===c)continue;let l=_i(s,c),u=r.get(l);u||(u={from:s,to:c,fileEdges:[],importers:new Set,importedFiles:new Set},r.set(l,u)),u.fileEdges.push({fromFile:i,toFile:a}),u.importers.add(i),u.importedFiles.add(a)}}return[...r.values()].map(i=>zV(i,n)).sort(e2)}function HR(e,t,n,r,i){i!==void 0&&r>i&&e.push({boundary:t,kind:n,observed:r,limit:i})}function n2(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:o=2,scanLimit:s}=t,a=new N(e),c=ge(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s),l=t.semantic!==!1,u=Pn(e,c,{semantic:l,semanticEvidence:ie});return c.map(m=>r2(e,m,l,u.get(m.symbolId)??[])).filter(m=>m.fanIn>=i&&m.fanOut>=o).sort((m,p)=>p.score-m.score||p.fanIn-m.fanIn).slice(0,n)}function r2(e,t,n,r){let i=r.filter(p=>p.file!==t.relativePath),o=[...new Set(i.map(p=>p.file))].sort(),s=[...new Set(i.filter(p=>p.source!=="caller-map-inversion"||ye(p.callEvidence)==="candidate").map(p=>p.file))].sort(),a=new Map;for(let p of jt(e,t,{semantic:n,semanticEvidence:ie})){if(p.file===t.relativePath)continue;let f=`${p.symbol}|${p.file}`;(!a.has(f)||a.get(f).evidenceStrength==="candidate"&&ye(p.source)==="exact")&&a.set(f,{symbol:p.symbol,shortName:L(p.symbol),file:p.file,evidenceStrength:ye(p.source),evidenceSource:p.source})}let c=[...a.values()].sort((p,f)=>p.file.localeCompare(f.file)||p.symbol.localeCompare(f.symbol)),l=o.length,u=c.length,d=l*u,m=c.filter(p=>p.evidenceStrength==="candidate").map(p=>p.symbol);return{symbol:t.symbol,shortName:L(t.symbol),fanIn:l,fanOut:u,callerFiles:o,candidateCallerFiles:s,externalCallees:c.map(({symbol:p,shortName:f,file:g})=>({symbol:p,shortName:f,file:g})),externalCalleeEvidence:c,candidateExternalCallees:m,inputBasis:"mixed-static-call-or-reference-evidence",score:d,definedIn:t.relativePath,actionTier:"signal",riskKind:"coordination-hotspot",evidenceReasons:[`${l} incoming file(s) reference this symbol`,`${u} distinct cross-file callee target(s) are observed; candidate targets do not establish reachability`,`centrality score is ${d} (fan-in * fan-out)`,`${s.length} incoming file(s) and ${m.length} outgoing target(s) rely on candidate rather than exact call evidence`],recommendation:"Review ownership, API stability, and caller groups before changing this central symbol; do not refactor solely from graph centrality."}}import{SymbolInformation_Kind as Et}from"@c4312/scip";function i2(e){let t=e.trim().toLowerCase();if(!t)return null;if(/^\d+$/.test(t)){let i=Number(t);return du.has(i)?i:null}let n=Mg.get(t);if(n!==void 0)return n;let r=[...du].filter(([,i])=>i.toLowerCase().includes(t));return r.length===1?r[0][0]:null}function o2(e,t,n={}){let{scope:r,limit:i=100}=n,o=i2(t);if(o===null)throw new Error(`Unknown or ambiguous symbol kind: ${JSON.stringify(t)}. Use an exact SCIP kind name or number.`);return qR(e,r).map(a=>({row:a,resolvedKind:zR(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:L(a.symbol),kind:c,kindName:mu(c),relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function s2(e,t={}){let n=new Map;for(let r of qR(e,t.scope)){let i=zR(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:mu(r),count:i}))}function qR(e,t){return Pe(e,{scope:t}).map(a2)}function a2(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 zR(e){return e.kind!==null&&e.kind!==0?GR(e.kind,e.symbol,e.documentation):c2(e.symbol,e.documentation,e.enclosing_symbol)}function GR(e,t,n){let r=(n??"").toLowerCase();if(vt(t)==="type"){if(r.includes("type "))return Et.TypeAlias;if(r.includes("interface "))return Et.Interface;if(r.includes("struct "))return Et.Struct;if(r.includes("trait "))return Et.Trait;if(r.includes("class "))return Et.Class}return e}function c2(e,t,n){let r=Jr(e);if("kind"in r)return null;let i=r.descriptors,o=i[i.length-2]??null,s=vt(e),a=(t??"").toLowerCase();return s==="type"?GR(Et.Class,e,t):s==="method"?o?.suffix==="type"?Et.Method:Et.Function:s==="namespace"?Et.Module:s!=="term"?null:l2(a,n,o?.suffix??null)}function l2(e,t,n){return e.includes("async def ")||e.includes("def ")?Et.Function:(t?vt(t):n)==="type"?Et.Field:Et.Variable}function u2(e,t={}){let{limit:n=10,scope:r,minDepth:i=3,edgeBasis:o="symbol-references"}=t,s=Fe(e,r,o==="imports"?{scipEdges:"imports-only",sourceEdges:"imports-and-reexports"}:void 0),{components:a,componentOf:c}=ut(s),l=d2(s,a.length,c),u=m2(l,a);function d(g){return u[g]}let m=a.map(g=>[...g].sort()),p=new Set,f=[];for(let g=0;g<a.length;g++){let y=d(g).map(x=>m[x]),S=y.map(x=>x[0]);if(y.length<i)continue;let I=S.join(" ");p.has(I)||(p.add(I),f.push(f2(S,y,o)))}return f.sort((g,h)=>h.depth-g.depth||g.chain.join("\0").localeCompare(h.chain.join("\0"))),g2(f).slice(0,n)}function d2(e,t,n){let r=new Map;for(let i=0;i<t;i++)r.set(i,new Set);for(let[i,o]of e){let s=n.get(i);for(let a of o){let c=n.get(a);c!==s&&r.get(s).add(c)}}return r}function m2(e,t){let n=new Array(t.length),r=new Array(t.length);for(let i=0;i<t.length;i++){let o=[],s=0;for(let a of[...e.get(i)].sort((c,l)=>c-l)){let c=r[a];(c>s||c===s&&p2(n[a],o,t)<0)&&(s=c,o=n[a])}n[i]=[i,...o],r[i]=1+s}return n}function p2(e,t,n){if(t.length===0)return-1;let r=e.map(o=>[...n[o]].sort()[0]??"").join("\0"),i=t.map(o=>[...n[o]].sort()[0]??"").join("\0");return r.localeCompare(i)}function f2(e,t,n){let r=t.reduce((o,s)=>o+s.length,0),i=t.filter(o=>o.length>1).length;return{chain:e,components:t,depth:t.length,fileCount:r,edgeBasis:n,actionTier:"signal",chainKind:"transitive-dependency-depth",evidenceReasons:[`${t.length} condensed dependency component(s) form the representative transitive path`,`${r} file(s) are represented; ${i} component(s) contain a dependency cycle`,`edge basis: ${n==="imports"?"resolved file imports":"cross-file symbol references plus resolved source imports"}`,"cycles count once toward depth and retain their full membership separately"],recommendation:"Review whether the chain crosses ownership or layer boundaries; shorten it only when the dependency direction is accidental."}}function g2(e){let t=[];for(let n of e)t.some(r=>h2(n.chain,r.chain))||t.push(n);return t}function h2(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 y2(e,t){let n=Bt(e,t);if(!n)return[];let r=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
|
|
259
|
+
WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:L(r.symbol),depth:0}],o=r.enclosing_symbol,s=1,a=new Set([r.symbol]);for(;o&&!a.has(o);){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:L(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(i.length>1)return i;let c=Jr(r.symbol);if("kind"in c||c.descriptors.length<=1)return i;let u=D(e,n.relativePath).filter(d=>r.symbol.startsWith(d.symbol)&&ra(d.symbol,r.symbol)).sort((d,m)=>m.symbol.length-d.symbol.length);return[...i,...u.map((d,m)=>({symbol:d.symbol,shortName:L(d.symbol),depth:m+1}))]}function b2(e,t={}){let r=new N(e).productionCallableDefinitions({scope:t.scope,requireCallableSymbol:!0,includeSuppressed:!0}),i=VR(e,r),o=t.search?.trim().toLocaleLowerCase();return r.map(s=>JR(e,s,i.get(s.symbolId)??[])).filter(s=>s!==null).map(s=>s.result).filter(s=>!o||C2(s).includes(o)).sort(x2)}function S2(e,t,n={}){let r=J(e,t);if(!r.match)return{kind:"missing",query:t};if(r.total>1)return{kind:"ambiguous",query:t,total:r.total,candidates:[{symbol:r.match.symbol,shortName:L(r.match.symbol),relativePath:r.match.relativePath,startLine:r.match.startLine},...r.candidates]};let i=new N(e),o=i.definitionsForFile(r.match.relativePath).find(p=>p.symbol===r.match.symbol);if(!o?.isFunctionLike)return{kind:"not-entry",query:t,symbol:r.match.symbol,shortName:L(r.match.symbol),file:r.match.relativePath,reason:"The resolved symbol is not a callable definition."};let s=VR(e,[o]),a=JR(e,o,s.get(o.symbolId)??[]);if(!a)return{kind:"not-entry",query:t,symbol:o.symbol,shortName:L(o.symbol),file:o.relativePath,reason:"The callable is neither an external root nor an uncalled callable on a detected entry surface."};let c=R2(e,i,o),l=new Set(n.expand??[]),u=P2(c,l),d=new Set(u.regions.filter(p=>p.expanded).map(p=>p.id)),m=[...l].filter(p=>!d.has(p)).sort();return{kind:"matched",query:t,entry:a.result,regions:u.regions,regionEdges:u.regionEdges,unmatchedExpansions:m,coverage:{completeWithinSelectedStaticEvidence:!0,candidateReachabilityIncluded:c.edges.some(p=>p.evidenceStrength==="candidate"),dynamicDispatchRepresented:!1,symbolCount:c.symbols.length,symbolEdgeCount:c.edges.length,exactSymbolEdgeCount:c.edges.filter(p=>p.evidenceStrength==="exact").length,candidateSymbolEdgeCount:c.edges.filter(p=>p.evidenceStrength==="candidate").length,regionCount:u.regions.length,regionEdgeCount:u.regionEdges.length,externalCallCount:c.externalCalls.length}}}function VR(e,t){let n=t.filter(r=>YR(e,r.relativePath)||bi(e,r.symbol,r.relativePath).length>0);return Pn(e,n,{semantic:!1,semanticEvidence:ie})}function JR(e,t,n){let r=v2(e,t),i=r.length>0,o=YR(e,t.relativePath)&&n.length===0;if(!i&&!o)return null;let s=[...r];return o&&s.push("entry-surface-without-indexed-caller"),{definition:t,result:{symbol:t.symbol,shortName:L(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,documentation:t.documentation,confidence:r.some(a=>a!=="package-public-export")?"root":"candidate",evidence:s,observedCallerCount:n.length}}}function YR(e,t){return Ke(e,t)||/(?:^|\/)entry\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(t)}function v2(e,t){let n=bi(e,t.symbol,t.relativePath),r=[];return KR(n,["package-surface-file","transitive-package-surface"])&&Pt(e,t)&&r.push("package-public-export"),n.includes("rust-public-library")&&r.push("rust-public-library"),n.includes("framework-entrypoint")&&r.push("framework-dispatched-export"),KR(n,["configured-file","configured-path-prefix","configured-qualified-var","configured-symbol-pattern"])&&r.push("configured-entry-root"),r}function KR(e,t){return t.some(n=>e.includes(n))}function C2(e){return[e.symbol,e.shortName,e.file,e.documentation??"",...e.evidence].join(`
|
|
260
|
+
`).toLocaleLowerCase()}function x2(e,t){return WR(e.confidence)-WR(t.confidence)||e.file.localeCompare(t.file)||e.startLine-t.startLine||e.symbol.localeCompare(t.symbol)}function WR(e){return e==="root"?0:1}function R2(e,t,n){let r=new Map([[n.symbol,0]]),i=new Map,o=new Map([[n.symbol,n]]),s=new Map,a=new Map,c=[n];for(;c.length>0;){let l=t.calleeMap(c,{additive:!1,semantic:!1}),u=[];for(let d of c){let m=r.get(d.symbol)??0;i.set(d.symbol,XR(d,m));for(let p of l.get(d.symbolId)??[]){let f=E2(t,p,o);if(!f){let g=w2(d,p);a.set(M2(g),g);continue}N2(d,f,p,m,r,i,s,u)}}c=u}return{symbols:[...i.values()].sort(D2),edges:[...s.values()].sort(F2),externalCalls:[...a.values()].sort(k2)}}function E2(e,t,n){let r=n.get(t.symbol);if(r)return r;let i=e.definitionsForFile(t.file).find(o=>o.symbol===t.symbol)??null;return i&&n.set(i.symbol,i),i}function XR(e,t){return{symbol:e.symbol,shortName:L(e.symbol),file:e.relativePath,depth:t}}function I2(e,t,n){return{fromSymbol:e.symbol,fromShortName:L(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:L(t.symbol),toFile:t.relativePath,source:n.source,evidenceStrength:ye(n.source)}}function w2(e,t){return{fromSymbol:e.symbol,fromShortName:L(e.symbol),fromFile:e.relativePath,toSymbol:t.symbol,toShortName:L(t.symbol),reportedFile:t.file,source:t.source,evidenceStrength:ye(t.source)}}function P2(e,t){let n=Te(e.symbols,l=>l.file),r=Te(e.edges.filter(l=>l.fromFile===l.toFile),l=>l.fromFile),i=Te(e.externalCalls,l=>l.fromFile),o=T2(e.edges.filter(l=>l.fromFile!==l.toFile)),s=Te(o,l=>l.toRegionId),a=Te(o,l=>l.fromRegionId);return{regions:[...n.entries()].map(([l,u])=>{let d=Gm(l),m=t.has(d),p=r.get(l)??[],f=i.get(l)??[];return{id:d,file:l,minDepth:Math.min(...u.map(g=>g.depth)),symbolCount:u.length,internalEdgeCount:p.length,externalCallCount:f.length,incomingRegionIds:ys((s.get(d)??[]).map(g=>g.fromRegionId)),outgoingRegionIds:ys((a.get(d)??[]).map(g=>g.toRegionId)),expanded:m,symbols:m?u:[],internalEdges:m?p:[],externalCalls:m?f:[]}}).sort((l,u)=>l.minDepth-u.minDepth||l.file.localeCompare(u.file)),regionEdges:o}}function T2(e){let t=new Map;for(let n of e){let r=`${n.fromFile}\0${n.toFile}`,i=t.get(r)??[];i.push(n),t.set(r,i)}return[...t.values()].map(n=>{let r=n[0];return{fromRegionId:Gm(r.fromFile),fromFile:r.fromFile,toRegionId:Gm(r.toFile),toFile:r.toFile,callCount:n.length,exactCallCount:n.filter(i=>i.evidenceStrength==="exact").length,candidateCallCount:n.filter(i=>i.evidenceStrength==="candidate").length,fromSymbols:ys(n.map(i=>i.fromShortName)),toSymbols:ys(n.map(i=>i.toShortName)),evidence:ys(n.map(i=>i.source))}}).sort((n,r)=>n.fromFile.localeCompare(r.fromFile)||n.toFile.localeCompare(r.toFile))}function Gm(e){return`file:${e}`}function ys(e){return[...new Set(e)].sort()}function L2(e){return`${e.fromSymbol}\0${e.toSymbol}`}function M2(e){return`${e.fromSymbol}\0${e.toSymbol}`}function D2(e,t){return e.depth-t.depth||e.file.localeCompare(t.file)||e.symbol.localeCompare(t.symbol)}function F2(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function k2(e,t){return e.fromFile.localeCompare(t.fromFile)||e.fromSymbol.localeCompare(t.fromSymbol)||e.toSymbol.localeCompare(t.toSymbol)}function N2(e,t,n,r,i,o,s,a){let c=r+1,l=i.get(t.symbol);(l===void 0||c<l)&&i.set(t.symbol,c),o.set(t.symbol,XR(t,Math.min(c,l??c)));let u=I2(e,t,n);s.set(L2(u),u),l===void 0&&a.push(t)}import{createHash as $J}from"crypto";import{execFileSync as A2}from"child_process";var nE=2e3,ol=50,_2=64,O2=8,B2=3,$2=2160*60*60,j2=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,H2=3,U2=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,q2=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function z2(e){let t=X(e,{clearGroups:["whole-project"]});return(n,r,i)=>{let o=i??Km(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 sl(e){let t=X(e,{clearGroups:["whole-project"]});return(n,r,i,o)=>{let s=o??Km(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 G2=sl("git-commit-history");function kt(e,t={}){let n=t.historyMode??"bounded",r=t.head;return{capability:i=>K2(e,i,r),commitHistory:()=>bs(e,n,r),fileChurn:()=>J2(e,n,r),changeAmplification:()=>Y2(e,n,r),trackedFiles:()=>Q2(e,r),fileAddRecords:()=>eJ(e,n,r),coChangePairs:(i={})=>uJ(e,i,n,r),coChangePairsForFiles:(i,o={})=>oE(e,i,o,n,r),directionalCoChangePairsForFiles:(i,o={})=>dJ(e,i,o,n,r)}}function bs(e,t="bounded",n){return G2(e,Oi(t),(r,i)=>W2(r,i,t),n)}function K2(e,t,n){let r=n??Km(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 Km(e){try{return et(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function et(e,t){return A2("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"})}function W2(e,t,n){let r;try{r=et(e,["log","--no-merges","--name-only",...al(n),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}return{head:t,...Jm(r,ol)}}function V2(e){return j2.test(e.subject)}function J2(e,t,n){let r=bs(e,t,n);if(!r)return null;let i=new Map;for(let o of r.commits){let s=V2(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 Y2(e,t,n){let r=bs(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:QR(i,.5),p90FilesPerCommit:QR(i,.9),commitsAnalyzed:i.length}}function QR(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var X2=z2("git-tracked-files");function Q2(e,t){return X2(e,n=>{try{let r=et(n,["ls-files"]);return new Set(r.split(`
|
|
261
|
+
`).map(i=>i.trim()).filter(i=>i!==""))}catch{return null}},t)}var Z2=sl("git-file-adds"),ZR="__git__/file-adds",eE=rt({kind:"git-file-adds",invalidation:Re("git-file-adds"),serialize:nJ,deserialize:iJ});function rE(e){return kt(e).fileAddRecords()}function eJ(e,t,n){let r=Oi(t);return Z2(e,r,(i,o)=>tJ(e,i,o,t),n)}function tJ(e,t,n,r){let i=eE.read(e,tE(r),n);if(i)return i;let o=oJ(t,r);return o&&eE.write(e,tE(r),n,o),o}function nJ(e){return JSON.stringify([...e.entries()])}function rJ(e){let t=e;return!t||typeof t.commitsAgo!="number"||!Number.isFinite(t.commitsAgo)||typeof t.addedAt!="number"||!Number.isFinite(t.addedAt)?null:{commitsAgo:t.commitsAgo,addedAt:t.addedAt}}function iJ(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=rJ(r[1]);if(!i)return null;n.set(r[0],{commitsAgo:i.commitsAgo,addedAt:i.addedAt})}return n}catch{return null}}function oJ(e,t){let n;try{n=et(e,["log","--no-merges","--find-renames","--name-status",...al(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(`
|
|
262
|
+
`),c=a>=0?s.slice(0,a):s,[,l]=c.split("\0"),u=Number(l)||0;a<0||sJ(s.slice(a+1),{commitsAgo:o,addedAt:u},r,i)}return r}function sJ(e,t,n,r){for(let i of e.split(`
|
|
263
|
+
`)){let o=cJ(i);o&&aJ(o,t,n,r)}}function aJ(e,t,n,r){if(e.status==="R"&&e.from&&e.to){let o=r.get(e.to)??new Set([e.to]);r.set(e.from,o);return}if(e.status!=="A"||!e.to)return;let i={commitsAgo:t.commitsAgo,addedAt:t.addedAt};n.set(e.to,i);for(let o of r.get(e.to)??[])n.set(o,i)}function cJ(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 iE=sl("git-co-change-pairs"),lJ=sl("git-directional-co-change-pairs");function uJ(e,t,n,r){let i=`all\0${Oi(n)}\0${Wm(t)}`,o=iE(e,i,()=>{let s=bs(e,n,r);return s?Vm(s,t):null},r);return o&&[...o]}function oE(e,t,n,r,i){if(t.size===0)return[];let o=`files\0${Oi(r)}\0${sE(t)}\0${Wm(n)}`,s=iE(e,o,()=>{let a=bs(e,r,i);return a?Vm(a,n,t):null},i);return s&&[...s]}function dJ(e,t,n,r,i){if(t.size===0)return[];let o=n.maxFilesPerCommit??ol;if(t.size>_2)return oE(e,t,n,r,i);let s=`directional\0${Oi(r)}\0${sE(t)}\0${Wm({...n,maxFilesPerCommit:o})}`,a=lJ(e,s,(c,l)=>{let u=hJ(c,l,t,o,r);return u?Vm(u,n,t):null},i);return a&&[...a]}function Wm(e){let t=e.minTogether??4,n=e.minConfidence??.6,r=e.maxFilesPerCommit??ol;return`${t}\0${n}\0${r}`}function sE(e){return[...e].sort().join("\0")}function Vm(e,t,n){let{minTogether:r=4,minConfidence:i=.6,maxFilesPerCommit:o=ol}=t,s=new Map,a=new Map,c=e.newestAnalyzedAt??0;for(let d of e.commits){let m=[...new Set(d.files)].sort();if(m.length>o)continue;e.newestAnalyzedAt===void 0&&d.timestamp>c&&(c=d.timestamp);let p=SJ(m),f=n===void 0||m.some(g=>n.has(g));mJ(s,m),f&&pJ(a,m,d,p,n)}let l=[],u=c-$2;for(let[d,m]of a){let p=gJ(d,m,s,r,i,u);p&&l.push(p)}return l.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),l}function mJ(e,t){for(let n of t)e.set(n,(e.get(n)??0)+1)}function pJ(e,t,n,r,i){for(let o=0;o<t.length;o++)for(let s=o+1;s<t.length;s++)i&&!i.has(t[o])&&!i.has(t[s])||fJ(e,`${t[o]}\0${t[s]}`,n,r)}function fJ(e,t,n,r){let i=e.get(t)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};i.together+=1,r?i.broadTogether+=1:i.focusedTogether+=1,n.timestamp>i.lastTogetherAt&&(i.lastTogetherAt=n.timestamp),i.timestamps.push(n.timestamp),i.subjects.push(n.subject),e.set(t,i)}function gJ(e,t,n,r,i,o){let s=t.together;if(s<r)return null;let[a,c]=e.split("\0"),l=n.get(a)??s,u=n.get(c)??s,d=Math.max(s/l,s/u);if(d<i)return null;let m=t.broadTogether/s,p=t.timestamps.filter(f=>f>=o).length;return{fileA:a,fileB:c,together:s,confidence:d,changesA:l,changesB:u,focusedTogether:t.focusedTogether,broadTogether:t.broadTogether,broadCommitRatio:m,lastTogetherAt:t.lastTogetherAt,recentTogether:p,commitScope:CJ(t.broadTogether,s),recency:p>0?"recent":"stale",subjectContext:xJ(t.subjects)}}function hJ(e,t,n,r,i){let o;try{o=yJ(e,i)}catch{return null}if(o.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:0};let s;try{s=et(e,["log","--no-merges","--format=%H",...al(i),"--",...[...n].sort()])}catch{return null}let a=new Set(o.map(m=>m.hash)),c=s.split(`
|
|
264
|
+
`).map(m=>m.trim()).filter(m=>m!==""&&a.has(m)),l=bJ(e,o,r);if(c.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:l};let u;try{u=et(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...c])}catch{return null}let d=Jm(u,r);return{head:t,...d,newestAnalyzedAt:l}}function yJ(e,t){return et(e,["log","--no-merges","--format=%H%x00%ct",...al(t)]).split(`
|
|
265
|
+
`).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 al(e){return e==="full"?[]:["-n",String(aE())]}function aE(){return Dn(process.env.SCIP_QUERY_GIT_HISTORY_MAX_COMMITS)??nE}function Oi(e){return e==="full"?"full":`bounded:${aE()}`}function tE(e){let t=Oi(e);return t===`bounded:${nE}`?ZR:`${ZR}:${t}`}function bJ(e,t,n){for(let i=0;i<t.length;i+=20){let o=t.slice(i,i+20),s;try{s=et(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=Jm(s,n);if(a.commits.length>0)return a.commits[0].timestamp}return 0}function Jm(e,t){let n=[],r=0;for(let i of e.split("")){if(i.trim()==="")continue;let o=i.indexOf(`
|
|
266
|
+
`),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(`
|
|
267
|
+
`).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 SJ(e){return e.length>=O2?!0:vJ(e).size>=B2}function vJ(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 CJ(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function xJ(e){let t=new Set,n=[],r=[];for(let i of e){!r.includes(i)&&r.length<H2&&r.push(i);for(let o of EJ(i))t.add(o);for(let o of i.match(U2)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:r,externalIssueLabelStatus:"unavailable"}}var RJ=[[/\b(?:feat|feature)\b/i,"feature"],[/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,"fix"],[/\b(?:docs?|documentation|guide|readme)\b/i,"docs"],[/\brefactor(?:ing|ed)?\b/i,"refactor"],[/\btests?\b/i,"test"],[/\b(?:release|version|v\d+\.\d+)\b/i,"release"],[/\bchore\b/i,"chore"],[/\bbuild\b/i,"build"],[/\bci\b/i,"ci"],[/\bperf(?:ormance)?\b/i,"perf"]];function EJ(e){let t=new Set,n=q2.exec(e)?.[1]?.toLowerCase();n&&t.add(IJ(n));for(let[r,i]of RJ)r.test(e)&&t.add(i);return[...t]}function IJ(e){return e==="feat"?"feature":e}import{existsSync as uE,readdirSync as wJ,statSync as PJ}from"fs";import{join as Bi}from"path";var cE="components.json",TJ=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),LJ=3,MJ=/(?:^|\/)components\/ui$/i,DJ=X("ui-kit-surface",{clearGroups:["whole-project"]});function FJ(e){return DJ.get(e,()=>kJ(e))}function Ym(e,t){let n=ee(t),r=n.lastIndexOf("/");if(r<0)return null;let i=n.slice(0,r);for(let o of FJ(e).directories)if(i===o.directory)return o;return MJ.test(i)?{directory:i,source:"ui-directory-convention"}:null}function dE(e,t){return Ym(e,t)!==null}function kJ(e){let t=new Map;for(let n of NJ(e.config.projectRoot)){let r=AJ(e,n);r&&!t.has(r)&&t.set(r,{directory:r,source:"shadcn-components-manifest",manifest:n})}return{directories:[...t.values()].sort((n,r)=>n.directory.localeCompare(r.directory))}}function NJ(e){let t=[],n=(r,i)=>{let o=r?Bi(e,r):e,s=r?`${r}/${cE}`:cE;if(uE(Bi(e,s))&&t.push(s),i>=LJ)return;let a=OJ(o);for(let c of a)!c.isDirectory()||TJ.has(c.name)||c.name.startsWith(".")||n(r?`${r}/${c.name}`:c.name,i+1)};return n("",0),t}function AJ(e,t){let n;try{n=JSON.parse(te(e.config.projectRoot,t,{inputKind:"components manifest"}))}catch(o){return o instanceof Error&&xe(o),null}if(!lE(n))return null;let r=n.aliases;if(!lE(r))return null;let i=BJ(r);return i?_J(e,t,i):null}function _J(e,t,n){let r=t.includes("/")?t.slice(0,t.lastIndexOf("/")):"",i=[];if(n.startsWith("./")||n.startsWith("../")||n.startsWith("/"))i.push(ee(Bi(r,n)));else{let o=Xf(e,t,n);o&&i.push(o);let s=n.replace(/^[@~]\//,"");i.push(ee(Bi(r,"src",s)),ee(Bi(r,s)))}for(let o of i){let s=Bi(e.config.projectRoot,o);if(uE(s)&&PJ(s).isDirectory())return o.replace(/\/+$/,"")}return null}function lE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function OJ(e){try{return wJ(e,{withFileTypes:!0})}catch{return[]}}function BJ(e){let t=typeof e.ui=="string"?e.ui:null,n=typeof e.components=="string"?e.components:null;return t??(n?`${n}/ui`:null)}var mE=new WeakMap,jJ=3;function Xm(e,t={}){return cl(e,t).groups}function cl(e,t={}){let{scope:n,maxLoc:r=15,minLoc:i=jJ,limit:o,scanLimit:s}=t,a=rE(e),c=zJ(e,{scope:n,maxLoc:r,scanLimit:s}).map(d=>GJ(e,d,a,i)).filter(d=>d!==null),{groups:l,exclusions:u}=UJ(e,gE(c));return{groups:o?l.slice(0,o):l,exclusions:u}}var HJ=/^(?:GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD|default|loader|action|load|actions)$/;function UJ(e,t){let n=new Map,r=(o,s)=>{let a=n.get(o);a?a.count+=1:n.set(o,{reason:o,detail:s,count:1})},i=[];for(let o of t){let s=[];for(let a of o.functions){let c=qJ(e,a);if(c){r(c.reason,c.detail);continue}s.push(a)}s.length<2||new Set(s.map(a=>a.file)).size<2||i.push({hash:o.hash,canonical:s[0],functions:s})}return{groups:i,exclusions:[...n.values()].sort((o,s)=>o.reason.localeCompare(s.reason))}}function qJ(e,t){let n=A(t.symbol);return n.startsWith("<")&&n.endsWith(">")?{reason:"synthetic-members",detail:"duplicate constructors and other compiler-named members every class carries"}:F(t.file)==="test"?{reason:"test-file-members",detail:"duplicate bodies in test files (fixture reuse, not product duplication)"}:HJ.test(n)&&gn(t.file)?{reason:"framework-route-exports",detail:"duplicate route-file verb exports whose identical glue the framework convention dictates"}:dE(e,t.file)?{reason:"ui-kit-members",detail:"duplicate bodies in vendored UI-kit directories generated from one template"}:null}function ll(e){let t=ot("duplicate.ts",e);return t.errors.length===0&&t.functions[0]?t.functions[0].bodyHash:Qt(e).trim()}function gE(e){let t=new Map;for(let r of e){if(r.normalizedBody.length<8)continue;let i=YJ(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(XJ).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=fE(i)-fE(r);return s!==0?s:r.canonical.file.localeCompare(i.canonical.file)}),n}function zJ(e,t){let n=Pe(e,{scope:t.scope}).filter(r=>r.isFunctionLike&&!e.isIgnored(r.relativePath)).filter(r=>!_e(e,r.relativePath,r.startLine,"similar")).filter(r=>oe(r)<=t.maxLoc);return n.sort((r,i)=>oe(i)-oe(r)||r.relativePath.localeCompare(i.relativePath)),ge(n,t.scanLimit)}function GJ(e,t,n,r){let i=tt(e,t);if(!i||JJ(i)<r)return null;let o=Qm(e,t);return o?{symbol:t.symbol,shortName:L(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:oe(t),ageCommits:n?.get(t.relativePath)?.commitsAgo??null,normalizedBody:o}:null}function Qm(e,t){let n=tt(e,t);return n&&ll(n)||null}function tt(e,t){let n=it(e,t.relativePath);if(!n||n.freshness.semantic.state==="stale")return null;if(/\.[cm]?[jt]sx?$/i.test(t.relativePath)){let r=mE.get(e);r||(r=new Map,mE.set(e,r));let i=r.get(t.relativePath);(!i||i.text!==n.text)&&(i={text:n.text,functions:ot(t.relativePath,n.text).functions},r.set(t.relativePath,i));let o=A(t.symbol),s=o==="<constructor>"?"constructor":o,a=i.functions.filter(c=>(c.name===s||c.name.endsWith(`.${s}`))&&c.startLine-1>=t.startLine&&c.endLine-1<=t.endLine);return a.length!==1?null:n.text.slice(a[0].startOffset,a[0].endOffset)}return n.text.split(`
|
|
268
|
+
`).slice(t.startLine,t.endLine+1).join(`
|
|
269
|
+
`)}function Qt(e){let t=0;for(let n=0;n<e.length;n+=1){let r=e[n],i=KJ(e,n,t);if(i!==null)return i;"([{".includes(r)?t+=1:")]}".includes(r)&&(t=Math.max(0,t-1))}return e}function KJ(e,t,n){if(n!==0)return null;let r=e[t];if(r==="{"&&!VJ(e,t))return pE(e,t);if(r==="="&&e[t+1]===">"){let i=e.slice(t+2).trimStart();return i.startsWith("{")?pE(i,0):i.replace(/;+\s*$/,"")}return null}var WJ=new Set([":","<","|","&",",","(","="]);function VJ(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n-=1;return n>=0&&WJ.has(e[n])}function pE(e,t){let n=e.lastIndexOf("}");return n>t?e.slice(t+1,n):e}function JJ(e){return Qt(e).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0).length}function YJ(e){return $J("sha256").update(e).digest("hex").slice(0,16)}function XJ(e,t){let n=e.ageCommits??-1;return(t.ageCommits??-1)-n||e.file.localeCompare(t.file)||e.startLine-t.startLine}function fE(e){return e.functions.reduce((t,n)=>t+n.loc,0)}function It(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function Ne(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function jn(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 hE(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 Zm(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 $i(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 ji(e,t){let n=0;for(let r of e){let i=t.get(r)??0;n+=i*i}return Math.sqrt(n)}function yE(e,t,n,r={}){let i=0,o=0,s=r.medianIdf??$i(n),a=[],c=[];for(let m of e){let p=n.get(m)??0;o+=p*p,t.has(m)&&(i+=p*p,p>=s?a.push(m):c.push(m))}if(a.length===0&&c.length===0)return{similarity:0,significantShared:[],trivialShared:[]};let l=QJ(t,n),u=Math.sqrt(o)*Math.sqrt(l),d=u>0?i/u:0;return a.sort((m,p)=>(n.get(p)??0)-(n.get(m)??0)),{similarity:d,significantShared:a,trivialShared:c}}function bE(e,t,n,r){let i=0,o=r.medianIdf??$i(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 QJ(e,t){let n=0;for(let r of e){let i=t.get(r)??0;n+=i*i}return n}function Ss(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=lY(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!be(o.symbol))return[];if(o.callees.size===0)return SE(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"});let s=tY(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):SE(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"})}function ZJ(e,t,n,r={}){let i=ul(e,t),o=ul(e,n);if(!i||!o)return null;let s=Ss(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:L(i.symbol),file:i.relativePath,loc:a},symbolB:{symbol:o.symbol,shortName:L(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:eY(s)}}function eY(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?`Inspect whether control flow and effects permit a shared helper around the ${e.sharedCallees.length} shared ${t}(s). Check whether the ${e.uniqueToA.length+e.uniqueToB.length} divergent point(s) can be parameters or callbacks.`:`Inspect whether control flow and effects permit extracting 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 tY(e,t,n,r){let i=Hi(e).calleeIndex({minCallees:3,scanLimit:r.scanLimit,semantic:r.semantic}),o=yY(t,i.corpus),s=fY(o,i),a=nY(o,i),c=$i(a),l=ji(o.callees,a),u=[];for(let d of s){if(d.callees.size<3)continue;let m=ji(d.callees,a),p=RE(o,d,a,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:c,magnitudeA:l,magnitudeB:m});p&&u.push(p)}return u.sort((d,m)=>m.similarity-d.similarity),u}function nY(e,t){let n=new Map(t.docFreq);for(let r of e.callees)n.set(r,(n.get(r)??0)+1);return Zm(n,t.corpus.length+1)}function RE(e,t,n,r){let i=iY(e,t,n,r);if(!oY(i,r))return null;let{similarity:o,significantShared:s,trivialShared:a}=i,c=s.length>0?s:a,l=EY(LE(c,"callees"),{similarity:o,sharedCount:c.length,sameFile:e.file===t.file});return{symbolA:e.symbol,shortNameA:L(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:L(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:c.map(L),uniqueToA:[...Ne(e.callees,t.callees)].map(L),uniqueToB:[...Ne(t.callees,e.callees)].map(L),...l}}function rY(e,t,n,r){let i=r.magnitudeA??ji(e.callees,n),o=r.magnitudeB??ji(t.callees,n),s=r.medianIdf??$i(n),{dotProduct:a,significantShared:c,sharedCount:l}=WY(e,t,n,s);if(l===0)return!1;let u=i*o;return(u>0?a/u:0)<r.minSimilarity?!1:c>=r.requireSignificantShared||l>=r.requireSharedCount}function iY(e,t,n,r){return r.magnitudeA===void 0||r.magnitudeB===void 0?yE(e.callees,t.callees,n,{medianIdf:r.medianIdf}):bE(e.callees,t.callees,n,{medianIdf:r.medianIdf,magnitudeA:r.magnitudeA,magnitudeB:r.magnitudeB})}function oY(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 vs(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=fe(),u=0,d=0,m=0,p=0,f=0,g=0,h=0;return M("similar.all",()=>{let S=Hi(e).calleeIndex({minCallees:o,scope:i,scanLimit:a,semantic:c}),I=S.corpus;u=I.length;let x=t.focusFiles,E=[],b=0,v=(C,R,P)=>{let w=I[R];if(s&&C.file===w.file){l&&(f+=1);return}if(IE(C,w)){l&&(g+=1);return}l&&(p+=1);let T=RE(C,w,S.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:S.medianIdf,magnitudeA:P,magnitudeB:S.weightedMagnitudes[R]});T&&(aY(E,T,r,b),l&&(h+=1),b+=1)};return M("similar.all.pair-scan",()=>EE(S,x,v,C=>{l&&(m+=C,C>0&&(d+=1))}),()=>({corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:p,crossFileSkips:f,signatureSkips:g,insertedResults:h,topResults:E.length})),M("similar.all.sort-project",()=>(E.sort((C,R)=>R.result.similarity-C.result.similarity||C.order-R.order),E.map(C=>C.result)),()=>({topResults:E.length}))},()=>({minSimilarity:n,limit:r,scope:i,minCallees:o,crossFileOnly:s,scanLimit:a,semantic:c,corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:p,crossFileSkips:f,signatureSkips:g,insertedResults:h}))}function rp(e,t={}){let{minSimilarity:n=.5,scope:r,minCallees:i=4,crossFileOnly:o=!1,scanLimit:s}=t,a=t.semantic!==!1,c=fe(),l=0,u=0,d=0,m=0,p=0,f=0,g=0;return M("similar.all-count",()=>{let y=Hi(e).calleeIndex({minCallees:i,scope:r,scanLimit:s,semantic:a}),S=y.corpus;l=S.length;let I=t.focusFiles,x=(E,b,v)=>{let C=S[b];if(o&&E.file===C.file){c&&(p+=1);return}if(IE(E,C)){c&&(f+=1);return}c&&(m+=1),rY(E,C,y.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:y.medianIdf,magnitudeA:v,magnitudeB:y.weightedMagnitudes[b]})&&(g+=1)};return M("similar.all-count.pair-scan",()=>EE(y,I,x,E=>{c&&(d+=E,E>0&&(u+=1))}),()=>({corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:p,signatureSkips:f,insertedResults:g})),g},()=>({minSimilarity:n,scope:r,minCallees:i,crossFileOnly:o,scanLimit:s,semantic:a,corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:p,signatureSkips:f,insertedResults:g}))}function EE(e,t,n,r){for(let i=0;i<e.corpus.length;i+=1){let o=e.corpus[i],s=e.weightedMagnitudes[i],a=sY(e,i,t);r(a.size);for(let c of a)n(o,c,s)}}function sY(e,t,n){let r=e.corpus[t],i=n?.has(r.file)??!1,o=new Set,s=a=>{for(let c of a)c<=t||n&&!i&&!n.has(e.corpus[c].file)||o.add(c)};for(let a of r.callees){let c=e.candidateIndexesByCallee.get(a);c&&s(c)}return o}function IE(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 wE=rt({kind:"source-fingerprints",invalidation:Re("source-fingerprints"),serialize:zY,deserialize:UY});function aY(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 cY=["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 ul(e,t){let n=J(e,t);if(n.candidates.length>0)throw new Error(`Ambiguous similarity target: ${t}. Use an exact symbol or file:line.`);return n.match}function lY(e,t,n){let r=ul(e,t);if(!r||!be(r.symbol))return null;let i=new N(e),o=jt(e,r,{semantic:n.semantic,semanticEvidence:ie});return{symbol:r.symbol,file:r.relativePath,callees:dl(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}var uY=X("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),dY=X("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function PE(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=t.semantic!==!1,a=uY.get(e,()=>new Map),c=`${n}|${r??""}|${o??""}|${s}`,l=!0,u=0,d=0;return M("similar.callee-fingerprints.resolve",()=>{let m=a.get(c);if(l=m!==void 0,m||(m=gY(e,{minCallees:n,scope:r,scanLimit:o,semantic:s}),a.set(c,m)),u=m.length,i===void 0)return m;let p=m.filter(f=>f.symbol!==i);return d=m.length-p.length,p},()=>({minCallees:n,scope:r,scanLimit:o,semantic:s,cacheHit:l,corpusSize:u,excludeSymbol:i!==void 0,excludedSymbols:d}))}function mY(e,t){let{minCallees:n,scope:r,scanLimit:i}=t,o=t.semantic!==!1,s=dY.get(e,()=>new Map),a=`${n}|${r??""}|${i??""}|${o}`,c=!0,l=0,u=0,d=0;return M("similar.callee-index.resolve",()=>{let m=s.get(a);return c=m!==void 0,m||(m=pY(PE(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 Hi(e){return{calleeCorpus:t=>PE(e,t),calleeIndex:t=>mY(e,t),sourceCorpus:(t={})=>NE(e,t),sourceIndex:(t={})=>xE(e,t),sourceCandidates:(t,n)=>(n.candidateMode??"full")==="target-pruned"?NY(e,t,{minSimilarity:n.minSimilarity,scanLimit:n.scanLimit}):kY(t,xE(e,{scanLimit:n.scanLimit}))}}function pY(e){let t=fe(),n=0,r=M("similar.callee-index.doc-frequency",()=>{let m=new Map;for(let p of e)for(let f of p.callees)m.set(f,(m.get(f)??0)+1);return n=m.size,m},()=>({corpusSize:e.length,uniqueCallees:n})),i=Math.max(8,Math.ceil(Math.sqrt(e.length))),o=M("similar.callee-index.idf-weights",()=>Zm(r,e.length),()=>({corpusSize:e.length,uniqueCallees:r.size})),s=M("similar.callee-index.weighted-magnitudes",()=>e.map(m=>ji(m.callees,o)),()=>({corpusSize:e.length})),a=0,c=0,l=0,u=M("similar.callee-index.candidate-buckets",()=>{let m=new Map;for(let p=0;p<e.length;p+=1){let f=e[p];for(let g of f.callees){if((r.get(g)??0)>i){t&&(c+=1);continue}VY(m,g,p),t&&(a+=1)}}return t&&(l=m.size),m},()=>({corpusSize:e.length,buckets:l,candidateRefs:a,ubiquitousSkips:c,ubiquityThreshold:i})),d=M("similar.callee-index.median-idf",()=>$i(o),()=>({uniqueCallees:o.size}));return{corpus:e,candidateIndexesByCallee:u,docFreq:r,idfWeights:o,weightedMagnitudes:s,medianIdf:d,ubiquityThreshold:i}}function fY(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 gY(e,t){let{minCallees:n,scope:r,scanLimit:i,semantic:o}=t,s=fe(),a=new N(e),c=0,l=M("similar.callee-fingerprints.candidates",()=>{let g=ge(a.productionCallableDefinitions({scope:r,minLoc:5,sortByLocDesc:typeof i=="number"&&i>0}).filter(h=>!_e(e,h.relativePath,h.startLine,"similar")),i);return c=g.length,g},()=>({scope:r,scanLimit:i,candidateCount:c})),u=0,d=M("similar.callee-fingerprints.callee-map",()=>{let g=a.calleeMap(l,{semantic:o});if(s)for(let h of g.values())u+=h.length;return g},()=>({candidateCount:c,semantic:o,calleeEdges:u})),m=0,p=0,f=0;return M("similar.callee-fingerprints.shape",()=>{let g=l.map(S=>({symbol:S.symbol,file:S.relativePath,callees:dl((d.get(S.symbolId)??[]).filter(I=>I.kind!=="jsx-render").map(I=>I.symbol)),paramCount:a.callableSignature(S)?.paramCount??-1})),h=hY(g);s&&(f=h.filter((S,I)=>S.callees.size!==g[I].callees.size).length);let y=h.filter(S=>S.callees.size>=n);return m=y.length,s&&(p=y.reduce((S,I)=>S+I.callees.size,0)),y},()=>({candidateCount:c,fingerprintCount:m,retainedCalleeCount:p,minCallees:n,siblingSaturatedFingerprints:f}))}var TE=5;function hY(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)>=TE);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 yY(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>=TE);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=>!bY(t)))}function bY(e){return cY.some(t=>e.includes(t))}function SE(e,t,n){let r=TY(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 M("similar.source-shape",()=>{let m=Hi(e).sourceCandidates(r,{minSimilarity:i,scanLimit:n.scanLimit,candidateMode:s});a=m.length;for(let p of m){if(p.symbol===r.symbol||p.tokens.size<3)continue;c+=1;let f=It(r.tokens,p.tokens);if(f.size<2){l+=1;continue}let g=new Set([...r.tokens,...p.tokens]),h=g.size>0?f.size/g.size:0;if(h<i){u+=1;continue}o.push({symbolA:r.symbol,shortNameA:L(r.symbol),fileA:r.file,symbolB:p.symbol,shortNameB:L(p.symbol),fileB:p.file,similarity:h,similarityBasis:"source-tokens",sharedCallees:[...f].sort(),uniqueToA:[...Ne(r.tokens,p.tokens)].sort(),uniqueToB:[...Ne(p.tokens,r.tokens)].sort(),...LE([...f],"source-tokens")})}return o.sort((p,f)=>f.similarity-p.similarity||p.shortNameB.localeCompare(f.shortNameB)),o.slice(0,n.limit)},()=>({symbol:r.symbol,file:r.file,targetTokens:r.tokens.size,candidateMode:s,candidates:a,comparedPairs:c,sharedSkips:l,similaritySkips:u,results:o.length}))}function LE(e,t){let n=e.flatMap(tp),r=e.flatMap(h=>vE(h,t)),i=ep(n,ME),o=ep(n,DE),s=ep(r,np),a=[...new Set(r.filter(CE))],c=e.filter(h=>{let y=vE(h,t);return y.some(S=>np.has(S))&&y.some(CE)}).length,l=t==="source-tokens"&&n.length>0&&n.every(h=>FE.has(h)),u=CY(i,o,s,a,l),d=s.length>0&&a.length>0,m=i.length+o.length>0,p=SY(t,d,e.length,a.length,c),f=vY(p,d,m,i.length>0,o.length>0||l);f==="structural-overlap"&&e.length>0&&u.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let g=f==="domain-behavior"&&(e.length>=3||p)?"direct":"signal";return{evidenceClass:f,actionTier:g,evidenceClassReasons:u,recommendation:IY(f,g)}}function SY(e,t,n,r,i){return e==="callees"&&t&&n>=4&&r>=4&&i>=2}function vY(e,t,n,r,i){return e?"domain-behavior":t?n?"mixed":"domain-behavior":r?"access-query-scaffolding":i?"framework-scaffolding":"structural-overlap"}function CY(e,t,n,r,i){let o=[];return e.length>0&&o.push(`access/query scaffolding: ${e.slice(0,5).join(", ")}`),t.length>0&&o.push(`framework/generic scaffolding: ${t.slice(0,5).join(", ")}`),n.length>0&&o.push(`domain behavior verbs: ${n.slice(0,5).join(", ")}`),n.length>0&&r.length>0&&o.push(`domain-specific terms: ${r.slice(0,5).join(", ")}`),i&&o.push("shared source tokens are generic scaffolding"),o}var xY=.5,RY=.6;function EY(e,t){if(e.actionTier==="direct"||t.sharedCount<4)return e;let n=t.sameFile&&t.similarity>=xY,r=e.evidenceClass==="mixed"&&t.similarity>=RY;if(!n&&!r)return e;let i=n?`same-file siblings share ${t.sharedCount} callees at similarity ${t.similarity.toFixed(2)}`:`mixed domain and scaffolding evidence at similarity ${t.similarity.toFixed(2)} across ${t.sharedCount} shared callees`;return{...e,actionTier:"direct",evidenceClassReasons:[...e.evidenceClassReasons,i],recommendation:n?"Sibling functions have overlapping weighted callee sets; compare ordering, guards and effects before considering extraction.":"Shared evidence carries domain behavior alongside scaffolding at high overlap; review for an extract/reuse opportunity."}}function IY(e,t){return t==="direct"?"Shared names match the domain vocabulary heuristic; compare behavior before considering extraction or reuse.":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 ep(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function tp(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function vE(e,t){if(t==="source-tokens")return tp(e);let n=A(e);return tp(n.length>0?n:wY(e))}function wY(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 CE(e){return e.length>3&&!np.has(e)&&!ME.has(e)&&!DE.has(e)&&!FE.has(e)&&!PY.has(e)}var np=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),ME=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),DE=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"]),FE=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),PY=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 TY(e,t){let n=ul(e,t);if(!n||!be(n.symbol))return null;let r=LY(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function LY(e,t){let n=A(t.symbol),r=tt(e,t)??"",i=_E(r,n);return i.size>0?i:null}var MY=X("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),DY=X("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function kE(e){return`${e.scanLimit??""}`}function NE(e,t={}){let n=MY.get(e,()=>new Map),r=kE(t),i=n.get(r);return i||(i=BY(e,t),n.set(r,i)),i}function xE(e,t={}){let n=DY.get(e,()=>new Map),r=kE(t),i=n.get(r);return i||(i=FY(NE(e,t)),n.set(r,i)),i}function FY(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 kY(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 NY(e,t,n){let r=fe(),i=new N(e),o=AY(t.tokens.size,n.minSimilarity),s=0,a=0,c=0,l=M("similar.source-shape.target-files",()=>{let f=[...t.tokens],g=[];for(let h of q(e,{includeIgnored:!1})){s+=1;let y=H(e,h);y&&(a+=1,_Y(y,f,o)&&g.push(h))}return c=g.length,g},()=>({symbol:t.symbol,targetTokens:t.tokens.size,requiredSharedTokens:o,scannedFiles:s,readableFiles:a,candidateFiles:c})),u=0,d=M("similar.source-shape.target-definitions",()=>{let f=ge(i.productionCallableDefinitions({files:l,sortByLocDesc:typeof n.scanLimit=="number"&&n.scanLimit>0}).filter(g=>!_e(e,g.relativePath,g.startLine,"similar")),n.scanLimit);return u=f.length,f},()=>({symbol:t.symbol,candidateFiles:c,scanLimit:n.scanLimit,definitionCount:u})),m=0;return M("similar.source-shape.target-fingerprints",()=>{let f=AE(e,d);return r&&(m=f.length),f},()=>({symbol:t.symbol,definitionCount:u,fingerprintCount:m})).filter(f=>f.symbol!==t.symbol)}function AY(e,t){return Math.max(2,Math.ceil(e*t))}function _Y(e,t,n){if(t.length<n)return!1;let r=e.toLowerCase(),i=0;for(let o of t)if(OY(r,o)&&(i+=1,i>=n))return!0;return!1}function OY(e,t){return t==="num"?/\b\d+\b/.test(e):e.includes(t)}function BY(e,t={}){let n=new N(e),{scanLimit:r}=t,i=ge(n.productionCallableDefinitions({sortByLocDesc:typeof r=="number"&&r>0}).filter(o=>!_e(e,o.relativePath,o.startLine,"similar")),r);return AE(e,i)}function AE(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)for(let s of $Y(e,i,o))r.set(s.symbol,s);return t.map(i=>r.get(i.symbol)).filter(i=>!!i)}function $Y(e,t,n){let r=[],i=H(e,t);if(!i)return[];let o=bt(e,t,i),s=HY(e,t,o),a=!1;for(let c of n){let l=jY(c),u=s.get(l),d=u?new Set(u.tokens):null;d||(d=_E(tt(e,c)??"",c.leaf),s.set(l,{key:l,symbol:c.symbol,startLine:c.startLine,endLine:c.endLine,leaf:c.leaf,tokens:[...d].sort()}),a=!0),d.size>0&&r.push({symbol:c.symbol,file:c.relativePath,tokens:d})}return a&&GY(e,t,o,s),r}function jY(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function HY(e,t,n){return wE.read(e,t,n)??new Map}function UY(e){try{let t=JSON.parse(e);if(t.version!==2||!Array.isArray(t.entries))return null;let n=new Map;for(let r of t.entries){if(!qY(r))return null;n.set(r.key,r)}return n}catch{return null}}function qY(e){return k(e)&&typeof e.key=="string"&&typeof e.symbol=="string"&&typeof e.startLine=="number"&&typeof e.endLine=="number"&&typeof e.leaf=="string"&&Array.isArray(e.tokens)&&e.tokens.every(t=>typeof t=="string")}function zY(e){let t={version:2,entries:[...e.values()].sort((n,r)=>n.key.localeCompare(r.key))};return JSON.stringify(t)}function GY(e,t,n,r){wE.write(e,t,n,new Map(r))}function _E(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=KY(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 KY(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 WY(e,t,n,r){let i=0,o=0,s=0;for(let a of e.callees){if(!t.callees.has(a))continue;let c=n.get(a)??0;i+=c*c,s+=1,c>=r&&(o+=1)}return{dotProduct:i,significantShared:o,sharedCount:s}}function VY(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function Zt(e,t){let n=new Map;return e.forEach((r,i)=>{let o=new Set;for(let s of t(r)){if(o.has(s))continue;o.add(s);let a=n.get(s);a?a.push(i):n.set(s,[i])}}),{candidatesFor:(r,i)=>{let o=new Set;for(let s of t(r)){let a=n.get(s);if(a)for(let c of a)c!==i&&o.add(c)}return[...o].sort((s,a)=>s-a)}}}function en(e){let t=OE(e.profile?.name),n=()=>{let r=[];t=OE(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)};e.filePattern?JY(e,i):e.focusFiles?.size!==0&&(t.overrunApplied=YY(e,i,()=>r.length)),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?M(`pairwise-profile:${e.profile.name}`,n,()=>({...ZY(e.profile?.metadata),...t})):n()}function JY(e,t){let n=new Set;for(let r=0;r<e.profiles.length;r++){let i=e.profiles[r];if(i.file.includes(e.filePattern))for(let o of XY(e,r)){let s=e.profiles[o];if(!BE(e.focusFiles,i,s))continue;let a=`${Math.min(r,o)}:${Math.max(r,o)}`;n.has(a)||(n.add(a),t(r,o))}}}function YY(e,t,n){let r=typeof e.overrunFactor=="number"&&Number.isFinite(e.limit)?e.limit*e.overrunFactor:Number.POSITIVE_INFINITY;for(let i=0;i<e.profiles.length;i+=1){let o=e.profiles[i];for(let s of QY(e,i))BE(e.focusFiles,o,e.profiles[s])&&t(i,s);if(n()>r)return!0}return!1}function BE(e,t,n){return e===void 0||e.has(t.file)||e.has(n.file)}function XY(e,t){if(e.candidateIndex)return $E(e,t,-1);let n=[];for(let r=0;r<e.profiles.length;r+=1)r!==t&&n.push(r);return n}function QY(e,t){if(e.candidateIndex)return $E(e,t,t);let n=[];for(let r=t+1;r<e.profiles.length;r+=1)n.push(r);return n}function $E(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 OE(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 ZY(e){return typeof e=="function"?e():e??{}}function e4(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:4),{profiles:a,distinctiveDeps:c}=t4(e,{scope:i,minDeps:s}),l=Zt(a,u=>u.deps);return en({profiles:a,limit:r,filePattern:o,overrunFactor:5,candidateIndex:l,profile:{name:"similar-files"},compare:(u,d)=>r4(u,d,n,c,s)})}function t4(e,t){let{scope:n,minDeps:r}=t,i=Fe(e),{universalDeps:o,distinctiveDeps:s}=n4(i),a=[];for(let[c,l]of i){if(n&&!c.includes(n))continue;let u=new Set([...l].filter(d=>!o.has(d)));u.size>=r&&a.push({file:c,deps:u})}return{profiles:a,distinctiveDeps:s}}function n4(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 r4(e,t,n,r,i){let o=new Set;for(let u of e.deps)t.deps.has(u)&&o.add(u);if(o.size<Math.min(3,i))return null;let s=0;for(let u of o)r.has(u)&&s++;if(s<Math.min(2,i))return null;let a=jn(e.deps,t.deps);if(a<n)return null;let c=jE(e.deps,t.deps),l=jE(t.deps,e.deps);return{fileA:e.file,fileB:t.file,similarity:a,evidenceBasis:"filtered-dependency-overlap",sharedDeps:[...o],uniqueToA:c,uniqueToB:l}}function jE(e,t){let n=[];for(let r of e)t.has(r)||n.push(r);return n}function Hn(e){let t=[],n=[],r=[];for(let s of e.primitiveGroups)s.values.length!==0&&HE(s.bucket,n,r).push(`${s.reasonPrefix}: ${s.values.join(", ")}`);for(let s of e.nameGroups)i4(s.names,s.label,e.genericWords,e.stripPrefixes??[],t,HE(s.fallbackBucket,n,r));let i=s4(t,n,r);return{actionTier:i==="domain-behavior"||i==="mixed"?"signal":"support",evidenceClass:i,reasons:[...t,...r,...n].slice(0,6),recommendation:e.recommendation(i)}}function ml(e,t){if(e.size===0||t.size===0)return 0;let i=It(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(jn(e,t),i)}function Un(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 pl(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 Q(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function $e(e){return[...e].sort()}function i4(e,t,n,r,i,o){let s=[],a=[];for(let c of e)o4(c,r).filter(u=>!n.has(u)).length>0?s.push(c):a.push(c);s.length&&i.push(`${t} has name(s) outside the generic vocabulary: ${s.slice(0,6).join(", ")}`),a.length&&o.push(`${t} matches the generic-name vocabulary: ${a.slice(0,6).join(", ")}`)}function o4(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 HE(e,t,n){return e==="generic"?t:n}function fl(e,t){return+(e.actionTier!=="signal")-+(t.actionTier!=="signal")||t.similarity-e.similarity||e.fileA.localeCompare(t.fileA)||e.componentA.localeCompare(t.componentA)||e.fileB.localeCompare(t.fileB)||e.componentB.localeCompare(t.componentB)}function s4(e,t,n){let r=e.length>0,i=t.length>0,o=n.length>0;return r?i||o?"mixed":"domain-behavior":o?"shared-abstraction":"generic-workflow-scaffolding"}var a4=new Set(["page","layout","template","loading","error","not-found","global-error","default","route"]),UE=/\.(?:ts|tsx|js|jsx|mjs|cjs)$/,c4=/^\((\.{1,3})\)(.*)$/,l4=/^\(\.\.\)\(\.\.\)(.*)$/;function qE(e){return ip(e)!==null}function ip(e){let t=ee(e);if(!UE.test(t))return null;let n=t.split("/"),r=n[n.length-1].replace(UE,"");if(!a4.has(r))return null;let i=n.findIndex((a,c)=>a==="app"&&c<n.length-1);if(i<0)return null;let o=[],s=!1;for(let a of n.slice(i+1,-1))s=u4(o,a)||s;return{route:o,entry:r,intercepting:s}}function zE(e,t){let n=ip(e),r=ip(t);return!n||!r||!n.intercepting&&!r.intercepting||n.entry!==r.entry?!1:n.route.join("/")===r.route.join("/")}function u4(e,t){if(t.startsWith("@"))return!1;let n=l4.exec(t);if(n)return e.splice(Math.max(0,e.length-2)),e.push(n[1]),!0;let r=c4.exec(t);if(r){let i=r[1];return i===".."?e.splice(Math.max(0,e.length-1)):i==="..."&&e.splice(0),e.push(r[2]),!0}return t.startsWith("(")&&t.endsWith(")")||e.push(t),!1}function Ui(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=d4(e,r);return t.set(r,o),o};return{roleOf:n,pairContext:(r,i)=>{let o=n(r),s=n(i);return o==="ui-kit"&&s==="ui-kit"?"ui-kit-pair":r!==i&&zE(r,i)?"intercepting-route-pair":o==="framework-route"&&s==="framework-route"&&r!==i?"framework-route-pair":"product"}}}function d4(e,t){return F(t)==="test"?"test":Ym(e,t)?"ui-kit":qE(t)||gn(t)?"framework-route":"product"}var qn=class{counts=new Map;record(t,n,r=1){if(r<=0)return;let i=this.counts.get(t);if(i){i.count+=r;return}this.counts.set(t,{reason:t,detail:n,count:r})}list(){return[...this.counts.values()].sort((t,n)=>t.reason.localeCompare(n.reason))}},tn={testFiles:"components defined in test files (fixture scaffolding, not product code)",uiKitPairs:"pairs where both components are vendored UI-kit primitives (similar by construction)",uiKitFiles:"components defined in vendored UI-kit directories",hookComponentPairs:"pairs that mix a hook with a component (a hook is already the extraction target)"};function gl(e){switch(e){case"framework-route-pair":return"both files are framework route entries; route files share framework scaffolding by design";case"intercepting-route-pair":return"intercepting route and its target route are meant to render the same view";case"ui-kit-pair":return"both files are vendored UI-kit primitives";case"product":return null}}function op(e,t={}){return sp(e,t).results}function sp(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=Ui(e),u=new qn,d=St(e).reactProfiles({scope:o,minJsxTokens:r,scanLimit:s}).filter(f=>f.kind==="component").filter(f=>l.roleOf(f.file)!=="test"?!0:(u.record("test-files",tn.testFiles),!1)).map(f=>({file:f.file,component:f.name,tokens:f.jsxTokens,profile:f})),m=Zt(d,f=>f.tokens);return{results:en({profiles:d,limit:i,filePattern:a,focusFiles:c,candidateIndex:m,profile:{name:"react-component-duplicates"},compare:(f,g)=>{let h=l.pairContext(f.file,g.file),y=m4(f,g,n,h);return y?h==="ui-kit-pair"?(u.record("ui-kit-pairs",tn.uiKitPairs),null):y:null},sort:fl}),exclusions:u.list()}}function m4(e,t,n,r){let i=It(e.tokens,t.tokens);if(i.size<6||!y4(i))return null;let o=jn(e.tokens,t.tokens);if(o<n)return null;let s=Q(i,"component:"),a=Q(i,"native:"),c=Q(i,"prop:"),l=Q(i,"event:"),u=Q(i,"binding:"),d=b4({sharedComponents:s,sharedNativeTags:a,sharedProps:c,sharedEvents:l,sharedBindings:u}),m=gl(r),p=f4(e.component,t.component,s),f=p?{actionTier:"support",recommendation:h4}:p4(r,d.actionTier,d.recommendation),g=[m,p].filter(h=>h!==null);return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:$e(i),sharedComponents:s,sharedNativeTags:a,sharedProps:c,sharedEvents:l,sharedBindings:u,evidenceClass:d.evidenceClass,actionTier:f.actionTier,evidenceClassReasons:[...g,...d.reasons],recommendation:f.recommendation,pairContext:r,uniqueToA:$e(Ne(e.tokens,t.tokens)),uniqueToB:$e(Ne(t.tokens,e.tokens)),locA:e.profile.loc,locB:t.profile.loc}}function p4(e,t,n){switch(e){case"framework-route-pair":return{actionTier:"support",recommendation:"Framework route entries share routing scaffolding by design; consolidate only a repeated non-routing body, and keep each route file as the framework entry."};case"intercepting-route-pair":return{actionTier:t,recommendation:"Render one shared view component from both the intercepting route and its target route; the routes are meant to show the same content, not to duplicate its body."};case"ui-kit-pair":case"product":return{actionTier:t,recommendation:n}}}function f4(e,t,n){return!GE.test(e)||!GE.test(t)||!n.every(r=>g4.has(r))?null:"both components are loading placeholders sharing only skeleton primitives"}var GE=/(?:Skeleton|Loading|Placeholder|Fallback)(?:[A-Z][A-Za-z0-9]*)?$|^Loading[A-Z]/,g4=new Set(["Skeleton","Spinner","Loader","Loader2","Placeholder"]),h4="Loading placeholders mirror the surface they stand in for; share a skeleton primitive only if the covered layouts are themselves shared.";function y4(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 Un([{name:"component",count:t},{name:"shape",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{shape:4},reason:"shared JSX structure"}]).pass}function b4(e){return Hn({genericWords:v4,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:S4})}function S4(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 v4=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 ap(e,t={}){return cp(e,t).results}function cp(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=Ui(e),u=new qn,d=St(e).reactProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).filter(f=>l.roleOf(f.file)!=="test"?!0:(u.record("test-files",tn.testFiles),!1)).map(f=>({file:f.file,component:f.name,tokens:f.behaviorTokens,profile:f})),m=Zt(d,f=>f.tokens);return{results:en({profiles:d,limit:i,filePattern:a,focusFiles:c,candidateIndex:m,profile:{name:"react-hook-candidates"},compare:(f,g)=>{let h=l.pairContext(f.file,g.file),y=C4(f,g,n,r,h);return y?f.profile.kind!==g.profile.kind?(u.record("hook-component-pairs",tn.hookComponentPairs),null):h==="ui-kit-pair"?(u.record("ui-kit-pairs",tn.uiKitPairs),null):y:null},sort:fl}),exclusions:u.list()}}function C4(e,t,n,r,i){let o=It(e.tokens,t.tokens);if(o.size<r||!I4(o))return null;let s=ml(e.tokens,t.tokens);if(s<n)return null;let a=Q(o,"hook:"),c=Q(o,"react-hook:"),l=Q(o,"effect:"),u=Q(o,"state:"),d=Q(o,"request:"),m=Q(o,"handler:"),p=Q(o,"handler-verb:"),f=R4({sharedHooks:a,sharedReactHooks:c,sharedEffects:l,sharedState:u,sharedRequests:d,sharedHandlers:m,sharedHandlerVerbs:p}),g=gl(i),h=x4(i,f.actionTier,f.recommendation);return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:s,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:$e(o),sharedHooks:a,sharedReactHooks:c,sharedEffects:l,sharedState:u,sharedRequests:d,sharedHandlers:m,sharedHandlerVerbs:p,evidenceClass:f.evidenceClass,actionTier:h.actionTier,evidenceClassReasons:g?[g,...f.reasons]:f.reasons,recommendation:h.recommendation,unitKind:e.profile.kind==="hook"&&t.profile.kind==="hook"?"hook":"component",pairContext:i,uniqueToA:$e(Ne(e.tokens,t.tokens)),uniqueToB:$e(Ne(t.tokens,e.tokens)),reason:w4({sharedHooks:a,sharedReactHooks:c,sharedEffects:l,sharedState:u,sharedRequests:d,sharedHandlers:m,sharedHandlerVerbs:p}),locA:e.profile.loc,locB:t.profile.loc}}function x4(e,t,n){switch(e){case"framework-route-pair":return{actionTier:t,recommendation:n};case"intercepting-route-pair":return{actionTier:t,recommendation:"Render one shared view component from both the intercepting route and its target route instead of repeating the behavior in each body."};case"ui-kit-pair":case"product":return{actionTier:t,recommendation:n}}}function R4(e){return Hn({genericWords:P4,stripPrefixes:T4,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:E4})}function E4(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 I4(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 Un([{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 w4(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 P4=new Set(["add","apply","async","callback","cancel","change","clear","client","close","context","create","data","deferred","delete","dispatch","draft","edit","effect","error","fetch","field","filter","form","handle","has","id","infinite","is","item","items","load","loader","loading","memo","mutate","mutation","name","navigate","navigation","open","params","pathname","query","reducer","refresh","ref","remove","request","reset","resource","router","row","rows","save","saving","search","select","selected","selector","state","store","submit","suspense","toggle","transition","update","use","value"]),T4=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function L4(e,t={}){return lp(e,t).results}function lp(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,u=Ui(e),d=new qn;return{results:St(e).reactProfiles({scope:a,scanLimit:c}).filter(f=>f.kind==="component").filter(f=>!l||f.file.includes(l)||f.name.includes(l)).map(f=>M4(f,{minComponentLines:n,minFileLines:r,minJsxTokens:i,minBehaviorTokens:o})).filter(f=>f!==null).filter(f=>{let g=u.roleOf(f.file);return g==="test"?(d.record("test-files",tn.testFiles),!1):g==="ui-kit"?(d.record("ui-kit-files",tn.uiKitFiles),!1):!0}).sort((f,g)=>g.componentLines-f.componentLines||g.fileLines-f.fileLines||f.file.localeCompare(g.file)).slice(0,s),exclusions:d.list()}}function M4(e,t){let n=Math.max(1,Math.floor(t.minComponentLines/2)),r=pl(e,D4({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=F4(e),c=k4(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:N4(c,a),reasons:i,loc:e.loc}}function D4(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&&t.loc>=e.substantialComponentLines,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&&t.loc>=e.substantialComponentLines,reason:(t,n)=>`${n} behavior token(s)`}]}function F4(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=>_4.has(m))>=0,s=n.some(m=>A4.has(m));if(KE(r)||KE(e.name))return"component";let c=O4.has(r.toLowerCase()),l=/(?:Page|Route|Screen)$/.test(e.name),u=o&&/View$/.test(e.name),d=$4(s,r,e.name);return c||l||u||d?"route-page":"component"}function KE(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&WE.has(t.at(-1))?!0:[...WE].some(n=>e.endsWith(B4(n)))}function k4(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 N4(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 A4=new Set(["component","components","panel","panels","partial","partials"]),WE=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"]),_4=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),O4=new Set(["page","route","screen"]);function B4(e){return e.charAt(0).toUpperCase()+e.slice(1)}function $4(e,t,n){return!e&&t.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()===n.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()&&/(?:Page|Route|Screen|View)$/.test(t)}function Cs(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=j4(e,{scope:o,minTokens:r,scanLimit:s}),u=Zt(l,d=>d.tokens);return en({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-component-duplicates"},compare:(d,m)=>U4(d,m,n),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function j4(e,t){return St(e).vueProfiles({scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:H4(n)}))}function H4(e){return e.totalLines}function U4(e,t,n){let r=It(e.tokens,t.tokens);if(r.size<6||!q4(r))return null;let i=jn(e.tokens,t.tokens);if(i<n)return null;let o=Q(r,"component:"),s=Q(r,"prop:"),a=Q(r,"event:"),c=Q(r,"directive:"),l=Q(r,"slot:"),u=Q(r,"id:"),d=z4({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:$e(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:$e(Ne(e.tokens,t.tokens)),uniqueToB:$e(Ne(t.tokens,e.tokens)),locA:e.loc,locB:t.loc}}function q4(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 Un([{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 z4(e){return Hn({genericWords:K4,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:G4})}function G4(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 K4=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 xs(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=St(e).vueProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,tokens:d.behaviorTokens,profile:d})),u=Zt(l,d=>d.tokens);return en({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-composable-candidates"},compare:(d,m)=>W4(d,m,n,r),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function W4(e,t,n,r){let i=It(e.tokens,t.tokens);if(i.size<r||!Y4(i))return null;let o=ml(e.tokens,t.tokens);if(o<n)return null;let s=Q(i,"composable:"),a=Q(i,"store:"),c=Q(i,"reactivity:"),l=Q(i,"lifecycle:"),u=Q(i,"request:"),d=Q(i,"function:"),m=Q(i,"function-verb:"),p=Q(i,"template-binding:"),f=Q(i,"template-event:"),g=V4({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:f});return{fileA:e.file,fileB:t.file,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:$e(i),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p,sharedTemplateEvents:f,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:$e(Ne(e.tokens,t.tokens)),uniqueToB:$e(Ne(t.tokens,e.tokens)),reason:X4({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:p}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function V4(e){return Hn({genericWords:Q4,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:J4})}function J4(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 Y4(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:Z4(u)&&(a+=1);let c=t+n,l=c+r+i+o+a;return Un([{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 X4(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 Q4=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 Z4(e){return e.startsWith("function-verb:")||e.startsWith("template-binding:")||e.startsWith("template-event:")}function up(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 St(e).vueProfiles({scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>eX(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 eX(e,t){let n=pl(e,tX(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=nX(e.file),a=rX(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:iX(a,s),reasons:r,loc:c}}function tX(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 nX(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(r=>oX.has(r))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function rX(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 iX(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 oX=new Set(["landing","page","pages","route","routes","view","views"]);import{posix as qi}from"path";import{spawnSync as sX}from"child_process";import{createHash as aX}from"crypto";import{existsSync as cX}from"fs";import{dirname as VE,join as lX}from"path";import{fileURLToPath as uX}from"url";var XE=Hr("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),JE=rt({kind:"consumer-file-usage",invalidation:Re("consumer-file-usage"),serialize:IX,deserialize:wX});function yl(e,t){return{forDefinitions(n,r){return dX(e,t,n,r)}}}function QE(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 dX(e,t,n,r){let i=ZE(n.length),o=fe()?nt(e):null,s=o?mX(n,r,o):void 0,a=s?{workIdentity:s,workOutcome:"computed"}:{};return M("consumer-evidence.product",()=>{let c=M("consumer-evidence.provenance",()=>pX(e,t,n,r),()=>({...a,definitions:n.length,semantic:r.semantic,sourceFallback:r.sourceFallback!==!1})),l=new Map;i={...i,...c.counters};let u=fX(n,c.sources);return M("consumer-evidence.classify",()=>{let d=gX(e,n,c.sources,u);for(let m of n){let p=d.get(m.symbolId)??bX();i.realFiles+=p.partition.realConsumers.length,i.reexportOnlyFiles+=p.partition.barrelConsumers,i.importOnlyFiles+=p.partition.importOnlyConsumers,l.set(m.symbolId,{definition:m,files:p.files,...p.partition})}},()=>({...a,...u,realFiles:i.realFiles,reexportOnlyFiles:i.reexportOnlyFiles,importOnlyFiles:i.importOnlyFiles})),l},()=>({...a,...i}))}function mX(e,t,n){let r=aX("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 ZE(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function pX(e,t,n,r){let i=ZE(n.length),o=new Map;return dp(o,i,"indexed",t.crossFileCallerMap(n,{semantic:!1})),r.semantic&&dp(o,i,"semantic",gi(e,n)),r.sourceFallback!==!1&&dp(o,i,"source-fallback",t.sourceFallbackCallerFiles(n)),i.totalFiles=[...o.values()].reduce((s,a)=>s+a.size,0),{sources:o,counters:i}}function fX(e,t){return{definitions:e.length,consumerFiles:[...t.values()].reduce((n,r)=>n+r.size,0),nativeAttempted:!1,nativeUsed:!1,nativeReason:"not-attempted"}}function dp(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 gX(e,t,n,r){let i=NX(e,t,n,r);return i||hX(e,t,n)}function hX(e,t,n){let r=new Map;for(let i of t){let o=n.get(i.symbolId)??new Map;r.set(i.symbolId,yX(e,i,[...o.keys()],o))}return r}function yX(e,t,n,r=new Map){let i=[],o=0,s=0,a=A(t.symbol),c=[];for(let l of n){let u;PX(e,l,t.relativePath,a)?(o++,u="reexport-only"):SX(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 bX(){return{partition:{realConsumers:[],barrelConsumers:0,importOnlyConsumers:0},files:[]}}function SX(e,t,n){if(!n)return!1;let r=se(t);if(!r)return!1;let i=XE.get(e,t,()=>eI(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function eI(e,t,n){let r=on(e).forFile(t,{text:!0}).text;if(!r)return EX();let i=bt(e,t,r),o=JE.read(e,t,i);if(o)return o;let s=CX(on(e).forFile(t,{ast:!0}).ast,n);return JE.write(e,t,i,s),s}var vX=new Set(["identifier","type_identifier","property_identifier","field_identifier"]);function CX(e,t){let n=new Set,r=new Set;if(!e)return{importedLeaves:n,usedLeaves:r};let i=xX(t),o=e.walk(),s=0,a=!1;for(;!a;){let c=o.nodeType,l=i.has(c);if(l&&(s+=1),vX.has(c)&&(s>0?n:r).add(o.nodeText),o.gotoFirstChild())continue;l&&(s-=1);let u=RX(o,i,s);s=u.importDepth,a=u.done}return{importedLeaves:n,usedLeaves:r}}function xX(e){return e==="rust"?new Set(["use_declaration"]):e==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"])}function RX(e,t,n){for(;;){if(e.gotoNextSibling())return{importDepth:n,done:!1};if(!e.gotoParent())return{importDepth:n,done:!0};t.has(e.nodeType)&&(n-=1)}}function EX(){return{importedLeaves:new Set,usedLeaves:new Set}}function IX(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function wX(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 PX(e,t,n,r){if(!r)return!1;let i=on(e).forFile(t,{lines:!0,reexports:!0}),o=i.lines??[];if(o.length===0)return!1;let s=i.reexports??[];return tI(o,s,r)}function tI(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 TX="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY",LX="SCIP_QUERY_NATIVE_KERNELS_BIN",MX="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY_MIN_FILES",YE=1e3,DX=5e3,FX=64*1024*1024,hl;function kX(e){let t=process.env[TX]?.toLowerCase();if(t!=="1"&&t!=="true")return e.nativeReason=t==="0"||t==="false"?"disabled":"opt-in-required",null;if(e.consumerFiles<qX())return e.nativeReason="below-threshold",null;let n=zX();return n||(e.nativeReason="binary-missing",null)}function NX(e,t,n,r){let i=kX(r);if(!i)return null;r.nativeAttempted=!0;let o=AX(e,t,n),s=sX(i,["consumer-classify"],{input:JSON.stringify(o),encoding:"utf8",timeout:DX,maxBuffer:FX});if(s.status!==0||s.error)return r.nativeReason=s.error?`spawn-error:${s.error.message}`:`exit-${s.status??"null"}`,null;try{let a=JSON.parse(s.stdout),c=OX(a,t);return c?(r.nativeUsed=!0,r.nativeReason="used",c):(r.nativeReason="invalid-response",null)}catch{return r.nativeReason="invalid-json",null}}function AX(e,t,n){let r=new Map,i=[];for(let a of t){let c=A(a.symbol),u=[...(n.get(a.symbolId)??new Map).entries()].map(([d,m])=>{let p=r.get(d)??new Set;return c&&p.add(c),r.set(d,p),{file:d,sources:[...m]}});i.push({symbol_id:a.symbolId,leaf:c,consumer_files:u})}let o={},s={};for(let[a,c]of r){let l=se(a);if(l){let d=XE.get(e,a,()=>eI(e,a,l));o[a]={imported_leaves:[...d.importedLeaves],used_leaves:[...d.usedLeaves]}}let u=_X(e,a,c);u.length>0&&(s[a]=u)}return{definitions:i,file_usages:o,reexport_only_leaves:s}}function _X(e,t,n){if(n.size===0)return[];let r=on(e).forFile(t,{lines:!0,reexports:!0}),i=r.lines??[],o=r.reexports??[];return i.length===0||o.length===0?[]:[...n].filter(s=>tI(i,o,s))}function OX(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=BX(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 BX(e){if(!$X(e))return null;let t=e,n=[];for(let r of t.files){let i=jX(r);if(!i)return null;n.push(i)}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 $X(e){if(!e||typeof e!="object")return!1;let t=e;return 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)?!1:t.real_consumers.every(n=>typeof n=="string")}function jX(e){if(!e||typeof e!="object")return null;let t=e;return typeof t.file!="string"||!Array.isArray(t.sources)||!t.sources.every(HX)||!UX(t.classification)?null:{file:t.file,sources:t.sources,classification:t.classification}}function HX(e){return e==="indexed"||e==="semantic"||e==="source-fallback"}function UX(e){return e==="real"||e==="reexport-only"||e==="import-only"}function qX(){let e=process.env[MX];if(!e)return YE;let t=Number(e);return Number.isFinite(t)&&t>=0?t:YE}function zX(){if(hl!==void 0)return hl;let e=process.env[LX],t=process.platform==="win32"?"scip-query-kernels.exe":"scip-query-kernels";return hl=[...e?[e]:[],...GX().map(r=>lX(r,"target","release",t))].find(r=>cX(r))??null,hl}function GX(){let e=new Set,t=VE(uX(import.meta.url));for(let n=0;n<5;n++)e.add(t),t=VE(t);return[...e]}var KX=20,WX=1,VX=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"]]),JX=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),YX=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 XX(e,t={}){let n=fp(t.limit,KX),r=fp(t.minConsumers,WX),i=new N(e),o=i.fileDependencyGraph(),s=b5(q(e,{includeIgnored:!1})),a=C5(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?QX(e,i,t.target):ZX(e,t.scope,t.scanLimit)).map(u=>e5(e,i,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=r||t.target).sort(y5).slice(0,n)}function QX(e,t,n){let r=r5(e,n);if(r)return[sI(r)];let i=J(e,n);if(i.candidates.length>0)throw new Error(`Ambiguous symbol: ${n}. Use an exact symbol.`);let o=i.match;if(!o)return[];let s=t.definitionsForFile(o.relativePath).find(a=>a.symbolId===o.symbolId);return s?[i5(s)]:[{unit:{kind:"symbol",file:o.relativePath,shortName:L(o.symbol),symbol:o.symbol,startLine:o.startLine,endLine:o.endLine}}]}function ZX(e,t,n){let r=q(e,{scope:t,includeIgnored:!1}),i=fp(n,r.length);return r.slice(0,i).map(o=>sI(o))}function e5(e,t,n,r,i,o,s){let a=r.definition?t5(e,t,r.definition,i.semantic):n5(n,r.unit.file),c=r.definition?a.length>0?"symbol-observations":"none":a.length>0?"file-level":"none",l=r.unit.file,u=Nt(qi.dirname(l)),d=s5(a),m=o5(u),p=hp([...nI(u),...d?nI(d):[]]),f=a5(r.unit,u,d,a),g=l5(f,r.unit,u,d,a,o,s),h=f5(r.unit,c,d,a,u,g.whyNoSuggestedHome),y=g5(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,nearestCommonDirectory:d,boundaryMarkers:p,recommendedTier:f,suggestedHome:g.suggestedHome,destinationConfidence:g.confidence,whyNoSuggestedHome:g.whyNoSuggestedHome,counterevidence:h,reasons:y,recommendation:h5(f,g.suggestedHome,c)}}function t5(e,t,n,r){let i=QE(yl(e,t).forDefinitions([n],{semantic:r!==!1,sourceFallback:!0}));return dI(i.get(n.symbolId)??[])}function n5(e,t){let n=[];for(let[r,i]of e.entries())r!==t&&i.has(t)&&n.push(r);return dI(n)}function r5(e,t){let n=zs(t),r=q(e,{includeIgnored:!1}),i=r.find(s=>s===n);if(i)return i;let o=r.filter(s=>s.endsWith(`/${n}`));return o.length===1?o[0]:null}function i5(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:L(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function sI(e){return{unit:{kind:"file",file:e,shortName:qi.basename(e)}}}function o5(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:gp(i)})}return t}function nI(e){return e==="."?[]:aI(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function gp(e){return hp(aI(e).map(({marker:t})=>t))}function aI(e){let t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){let i=VX.get(t[r]);i&&n.push({marker:i,prefix:t.slice(0,r+1).join("/")})}return n}function s5(e){if(e.length===0)return null;let t=e.map(r=>Nt(qi.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 a5(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":c5(n,t):"no-observed-consumers"}function c5(e,t){return iI(e,"package")?"package-level-shared":iI(e,"app")?"app-level-shared":oI(e,["feature","domain","module"])||oI(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder"}function l5(e,t,n,r,i,o,s){let a=u5(e,r);if(a)return zn(a);let c=S5(t.file),l=d5(e,n,c,i,s);if(l)return l;let u=r;if(Nt(n)===Nt(u))return zn(`${n} is already the nearest common directory for its consumers.`);let d=m5(u,n,c,s);return d||p5(u,n,c,o,s)}function u5(e,t){return t?e==="no-observed-consumers"||e==="repository-level-review"?"The inferred owner is too broad or unsupported for an suggested destination.":null:"No shared consumer directory was observed in the current evidence."}function d5(e,t,n,r,i){if(e==="same-file"){let o=r[0]??null;return o?mp(o):zn("No same-file consumer path was available.")}if(e==="sibling-folder"&&r.length===1){let o=Nt(qi.dirname(r[0])),s=uI(t,n,o,i);return s?zn(s):mp(o)}return null}function m5(e,t,n,r){return R5(e)?cI(e,t,n,r,`Nearest shared owner ${e} is outside source root ${n}.`):null}function p5(e,t,n,r,i){if(e===".")return zn("The nearest common directory is the repository root.");let o=`${e}/shared`,s=cI(o,t,n,i,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||r.has(o)?s:zn(`${o} does not exist in the indexed project.`)}function cI(e,t,n,r,i){if(!lI(e,n))return zn(i);let o=uI(t,n,e,r);return o?zn(o):mp(e)}function mp(e){return{suggestedHome:e,confidence:"candidate",whyNoSuggestedHome:null}}function zn(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function f5(e,t,n,r,i,o){let s=["Path and observed-consumer heuristic; confirm conceptual ownership, complete consumers and behavior 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 directory 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 directory."),o&&s.push(`No suggested home: ${o}`),s}function g5(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 directory.`):s.push("No shared consumer directory was observed in the current evidence."),i?s.push(`Suggested home is ${i}.`):o&&s.push(`No suggested home: ${o}`),s}function h5(e,t,n){return e==="no-observed-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==="symbol-observations"?"symbol usage":"module import"} supports moving or extracting toward ${t}.`:"Review ownership manually before changing structure."}function y5(e,t){return rI(t)-rI(e)||e.candidatePath.localeCompare(t.candidatePath)}function rI(e){let t=e.consumerFiles.length*10;return e.consumerCoverage==="symbol-observations"&&(t+=5),e.suggestedHome&&(t+=3),e.recommendedTier==="repository-level-review"&&(t*=.1),e.recommendedTier==="no-observed-consumers"&&(t*=.05),t}function b5(e){let t=new Set(["."]);for(let n of e){let r=Nt(qi.dirname(n));for(;!t.has(r)&&(t.add(r),r!==".");)r=Nt(qi.dirname(r))}return t}function S5(e){let t=pp(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function lI(e,t){let n=Nt(e),r=Nt(t);return r==="."||n===r||n.startsWith(`${r}/`)}function v5(e,t,n){let r=pp(e),i=pp(t);return(lI(e,t)?r.slice(i.length):r).some(s=>n.has(s.toLowerCase()))}function uI(e,t,n,r){return Nt(e)===Nt(n)||!v5(e,t,r)?null:`${e} matches a protected directory-name marker; a move to ${n} needs human design.`}function C5(...e){let t=new Set(YX);for(let n of e)for(let r of n??[]){let i=x5(r);i&&t.add(i)}return t}function x5(e){let t=e.trim().toLowerCase();return t===""?null:t}function iI(e,t){return gp(e).includes(t)}function oI(e,t){let n=gp(e);return t.some(r=>n.includes(r))}function R5(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?JX.has(n):!1}function Nt(e){let t=zs(e);return t===""?".":t}function pp(e){let t=zs(e);return t==="."?[]:t.split("/").filter(Boolean)}function fp(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function dI(e){return hp([...e]).sort((t,n)=>t.localeCompare(n))}function hp(e){return[...new Set(e)]}function yp(e,t,n={}){return mI(e,t,n).rows}function E5(e,t,n={}){return mI(e,t,n)}function mI(e,t,n){let{maxDepth:r=5,scope:i}=n,s=r===Number.MAX_SAFE_INTEGER?null:500;if(!Number.isSafeInteger(r)||r<0)throw new RangeError("Impact depth must be a non-negative safe integer.");let a=J(e,t);if(a.candidates.length>0)throw new Error(`Ambiguous symbol: ${t}. Use an exact SCIP symbol or file:line.`);let c=a.match;if(!c)return{rows:[],coverage:{status:"incomplete",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:r,reachedDepth:0,perSymbolEvidenceLimit:s,remainingFrontierSymbols:0,reasons:["The requested symbol could not be resolved."]}};let l=[],u=new Set([c.symbolId]),d=new Set,m=[c],p=0,f=!1;for(let g=1;g<=r&&m.length!==0;g++){p=g;let h=w5(e,m,i,s);f||=h.bounded,m=P5(h.rows,g,u,d,l)}return l.sort((g,h)=>g.depth-h.depth||g.file.localeCompare(h.file)),{rows:l,coverage:I5(l,r,p,s,m.length,f)}}function I5(e,t,n,r,i,o){let s=i>0,a=[];s&&a.push(`${i} symbol(s) remain eligible beyond depth ${t}.`),o&&a.push(`At least one symbol had more than ${r} incoming evidence row(s).`);let c=e.filter(l=>l.symbol===l.file).length;return c>0&&a.push(`${c} consumer file(s) lack an exact owning symbol; further symbol propagation is unknown.`),a.length===0&&a.push("The discovered reverse evidence frontier was exhausted."),{status:c>0?"incomplete":s||o?"bounded":"accounted",edgeBasis:"reverse-static-call-or-reference-evidence",maxDepth:t,reachedDepth:n,perSymbolEvidenceLimit:r,remainingFrontierSymbols:i,reasons:a}}function w5(e,t,n,r){let i=Pn(e,t,{...r===null?{}:{limit:r+1},semanticEvidence:ie}),o=[],s=!1;for(let a of t){let c=i.get(a.symbolId)??[];r!==null&&c.length>r&&(s=!0);let l=r===null?c:c.slice(0,r);o.push(...T5(e,a,n,l))}return{rows:o,bounded:s}}function P5(e,t,n,r,i){let o=[];for(let s of e){let a=`${s.file}|${s.shortName}`;if(s.symbolId!==null){if(n.has(s.symbolId))continue;n.add(s.symbolId)}else if(r.has(a))continue;r.add(a),i.push({symbol:s.symbol,shortName:s.shortName,file:s.file,depth:t}),s.symbolId!==null&&s.symbolMatch&&o.push(s.symbolMatch)}return o}function T5(e,t,n,r){let i=r.filter(l=>!e.isIgnored(l.file)).filter(l=>!n||l.file.includes(n)),o=L5(e,t,n,new Set(i.map(l=>l.file))),s=[...i,...o],a=[],c=new Set;for(let l of s){let u=M5(e,t,l);!u||c.has(u.key)||(c.add(u.key),a.push(u.row))}return a}function L5(e,t,n,r){let i=[];for(let o of D5(e,t,n)){let s=Yr(e,o,t.symbol),a=D(e,o),c=new Set;for(let l of s??[]){let u=ir(a,l);u&&pI(u)&&c.add(u.symbol)}for(let l of c)i.push({symbol:l,file:o});c.size===0&&!r.has(o)&&i.push({symbol:o,file:o})}return i}function M5(e,t,n){let r=la(e,n.symbol);return r?r.symbolId===t.symbolId||e.isIgnored(r.relativePath)||!pI(r)?null:{key:`${r.symbolId}|${r.relativePath}`,row:{symbolId:r.symbolId,symbol:r.symbol,shortName:L(r.symbol),file:r.relativePath,symbolMatch:r}}:{key:`${n.file}|${n.symbol}`,row:{symbolId:null,symbol:n.symbol,shortName:L(n.symbol),file:n.file,symbolMatch:null}}}function D5(e,t,n){let r=n?"AND instr(consumer_d.relative_path, ?) > 0":"",i=[t.symbolId,t.documentId];return n&&i.push(n),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
|
|
270
|
+
FROM mentions m
|
|
271
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
272
|
+
JOIN documents consumer_d ON consumer_d.id = c.document_id
|
|
273
|
+
WHERE m.symbol_id = ?
|
|
274
|
+
AND m.role != 1
|
|
275
|
+
AND c.document_id != ?
|
|
276
|
+
${e.pathExclusionsFor("consumer_d")}
|
|
277
|
+
${r}`,...i).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function pI(e){if(e.symbol.startsWith("scip-clojure ")||se(e.relativePath)==="clojure")return!0;let t=vt(e.symbol);return t==="method"||t==="type"||e.symbol.endsWith("().")}function gI(e,t){let n=ee(t),r=[],i="complete";N5(e,n,r);let o=!1;try{o=fn(e,n),o&&Rn(r,"published-api","package manifest export");for(let s of MS(e,n))Rn(r,"operational-root",s)}catch(s){i="partial",Rn(r,"metadata-unavailable",`package metadata unavailable: ${fI(s)}`)}try{let s=te(e.config.projectRoot,n,{maxBytes:8388608,inputKind:"change-surface source"});k5(s)&&Rn(r,"operational-root","module contains a direct-execution process guard")}catch(s){i="partial",Rn(r,"metadata-unavailable",xe(s)?"indexed source file is unavailable on disk":`source metadata unavailable: ${fI(s)}`)}return{operationalRoot:r.some(s=>s.kind==="operational-root"),publishedApi:o,coverage:i,reasons:r}}function F5(e,t){let n=e.config.entryRoots;return n?n.files?.some(r=>ee(r)===t)?!0:n.pathPrefixes?.some(r=>t.startsWith(ee(r)))??!1:!1}function k5(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 Rn(e,t,n){e.some(r=>r.kind===t&&r.detail===n)||e.push({kind:t,detail:n})}function fI(e){return e instanceof Error?e.message:String(e)}function N5(e,t,n){let r=F(t);r==="entry"&&Rn(n,"operational-root","structural entrypoint path"),r==="worker"&&Rn(n,"operational-root","worker launch convention"),gn(t)&&Rn(n,"operational-root","framework-discovered entrypoint"),F5(e,t)&&Rn(n,"operational-root","configured entry root")}function bp(e,t,n={}){let r=Ht(e,t);if(!r)return null;let i=A5(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=new Set,a=_5(e,i.relative_path),c=gI(e,i.relative_path),l=n.semantic===!1?new Map:gi(e,a);for(let u of a){let d=O5(e,i,u,l.get(u.symbolId)??new Set);for(let g of d)s.add(g);let m=d.size,p=B5(m),f=[...c.reasons,...m>0?[{kind:"external-consumers",detail:`${m} external consumer${m===1?"":"s"}`}]:[]];o.push({symbol:u.symbol,shortName:L(u.symbol),startLine:u.startLine,endLine:u.endLine,externalConsumers:m,externalConsumerRiskLevel:p,riskLevel:$5(p,c),riskReasons:f})}return{file:i.relative_path,symbols:o,totalExternalConsumers:s.size,fileRisk:c}}function A5(e,t){return e.get(`SELECT id, relative_path FROM documents
|
|
278
|
+
WHERE relative_path = ?
|
|
279
|
+
${e.pathExclusionsFor("documents")}
|
|
280
|
+
LIMIT 1`,t)??null}function _5(e,t){return new N(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function O5(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
|
|
281
|
+
FROM mentions m
|
|
282
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
283
|
+
JOIN documents consumer_d ON consumer_d.id = c.document_id
|
|
284
|
+
WHERE m.symbol_id = ?
|
|
285
|
+
AND m.role != 1
|
|
286
|
+
AND c.document_id != ?`,n.symbolId,t.id);return new Set([...i.map(o=>o.relative_path).filter(o=>!e.isIgnored(o)),...[...r].filter(o=>o!==t.relative_path&&!e.isIgnored(o))])}function B5(e){return e>10?"high":e>0?"medium":"low"}function $5(e,t){return e==="high"?"high":e==="medium"||t.operationalRoot||t.publishedApi||t.coverage==="partial"?"medium":"low"}function j5(e,t={}){let{scope:n,minLoc:r=1,maxDepth:i=5,scanLimit:o}=t,s=new N(e),a=H5(e,n,r,o),c=new Sp;for(let S of a)c.add(S);let l=[],u=new Map;a.length>0&&l.push(hI(e,0,a,c));let d=a.map(S=>S.definition).filter(S=>S!==null),m=new Set(a.map(S=>S.symbol)),p=new Set,f=S=>{let I=s.calleeMap(S,{semantic:!1}),x=new Set(p);for(let E of S)for(let b of I.get(E.symbolId)??[])m.has(b.symbol)||x.add(b.symbol);return x},g=S=>{let I=[];for(let x of S){let E=U5(e,s,x);if(!E)continue;let b=z5(e,E,c);b.removable?(m.add(x),p.delete(x),u.delete(x),I.push(q5(E,"cascade"))):b.blockingFiles.length>0&&(p.add(x),u.set(x,{shortName:L(E.symbol),file:E.relativePath,blockingFiles:b.blockingFiles}))}return I};for(let S=1;S<=i&&d.length>0;S++){let I=g(f(d));if(I.length===0)break;for(let x of I)c.add(x);l.push(hI(e,S,I,c)),d=I.map(x=>x.definition).filter(x=>x!==null)}let h=l.reduce((S,I)=>S+I.loc,0),y=l.reduce((S,I)=>S+I.entries.length,0);return{batches:l,totalSymbols:y,totalLoc:h,blocked:[...u.values()]}}function H5(e,t,n,r){let i=Pr(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:r,semantic:!1}),o=[];for(let s of i.symbols)s.kind==="dead-code"&&(Ke(e,s.relativePath)||We(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:yI(e,s.symbol)}));return o}function U5(e,t,n){let r=yI(e,n);if(r&&!e.isIgnored(r.relativePath)&&!Ke(e,r.relativePath)&&!We(e,r.symbol,r.relativePath)&&t.fileKind(r.relativePath)!=="test"&&!_e(e,r.relativePath,r.startLine,"dead"))return r}function q5(e,t){return{symbol:e.symbol,shortName:L(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function yI(e,t){let n=e.get(`SELECT d.relative_path
|
|
287
|
+
FROM global_symbols gs
|
|
288
|
+
JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
289
|
+
JOIN documents d ON d.id = der.document_id
|
|
290
|
+
WHERE gs.symbol = ?
|
|
291
|
+
LIMIT 1`,t);return n?D(e,n.relative_path).find(r=>r.symbol===t)??null:null}function z5(e,t,n){let r=mo(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 hI(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=D(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 Sp=class{ranges=new Map;add(t){let n=this.ranges.get(t.file)??[];n.push({start:t.startLine,end:t.endLine}),this.ranges.set(t.file,n)}contains(t,n){let r=this.ranges.get(t);return r?r.some(i=>n>=i.start&&n<=i.end):!1}};import{execFileSync as Sl}from"child_process";import{existsSync as G5}from"fs";import{basename as bI}from"path";function bl(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 Ep="Unable to compute git diff.",K5={semanticConsumers:gi,sourceFallbackConsumers:Zo,semanticReadiness:Eb},Ip={resolveCommit:Xl,readBatch({projectRoot:e,resolvedBase:t,relativePaths:n}){let r=n.map(i=>`${t}:./${i}
|
|
292
|
+
`).join("");return Sl("git",["cat-file","--batch"],{cwd:e,input:r,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"]})}};function vl(e,t={}){let n=t.plan??zi(e,t);return n.note?W5(n.note,n.changedFileLines):n.changedFiles.length===0?V5(n.changedFileLines):Cl(n.changedFiles,[CI(e,n.changedFiles,n.changedFiles,n.changedRanges)],n.changedFileLines.filter(r=>!n.changedFiles.includes(r)))}function zi(e,t={}){let{base:n="HEAD"}=t;try{let r=Xl(e.config.projectRoot,n),i=J5(e.config.projectRoot,r),o=i.changedFileLines,s=t3(e,o),a=n3(e,i.changedRanges);return{changedFileLines:o,changedFiles:s,changedRanges:a,renamedFiles:Q5(e.config.projectRoot,r,s,i),note:o.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:Ep}}}function CI(e,t,n,r=[],i={}){let o=i.evidenceRuntime??K5,s=new N(e),a=new Set(n),c=bl(r),l=[],u=new Map,d=t.flatMap(b=>s.definitionsForFile(b)).filter(v3),m=d.filter(b=>a3(b,c)),p=l3(e,d,m,c),f=m3([...m,...p.definitions]).sort((b,v)=>b.relativePath.localeCompare(v.relativePath)||b.startLine-v.startLine),g=f.map(b=>b.symbolId),h=b3(e,g),y=f.length>0?o.semanticReadiness?.(e)??{ready:!0}:{ready:!0},S=y.ready?vI("semantic-consumers",f.length,()=>o.semanticConsumers(e,f)):{values:new Map,status:{tier:"semantic-consumers",state:"failed",attemptedSymbols:f.length,reason:y.reason}},I=S.values,x=vI("source-fallback-consumers",f.length,()=>o.sourceFallbackConsumers(e,f)),E=x.values;for(let b of f)g3(e,b,a,l,u,I.get(b.symbolId)??new Set,E.get(b.symbolId)??new Set,h.get(b.symbolId)??new Set);return{changedSymbols:l,consumerEntries:[...u.entries()].map(([b,v])=>({file:b,symbols:[...v].sort()})),attributionNotes:p.notes,evidenceTiers:[S.status,x.status]}}function Cl(e,t,n=[]){let r=new Map,i=t.flatMap(c=>c.changedSymbols),o=t.flatMap(c=>c.attributionNotes??[]),s=h3(t);for(let c of t)for(let l of c.consumerEntries){let u=r.get(l.file);u||(u=new Set,r.set(l.file,u));for(let d of l.symbols)u.add(d)}let a=S3(r);return{changedFiles:[...e],unindexedChangedFiles:[...n],changedSymbols:i,affectedConsumers:a,attributionNotes:o,evidenceTiers:s,summary:{totalChangedFiles:e.length,totalChangedSymbols:i.length,totalAffectedFiles:a.length,...n.length?{note:`${n.length} changed path(s) were omitted from symbol analysis because they are absent or excluded from this index. Reindex supported source or use review for current-source analysis.`}:{}}}}function W5(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:wI(),summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function V5(e){return{changedFiles:e,unindexedChangedFiles:e,changedSymbols:[],affectedConsumers:[],attributionNotes:[],evidenceTiers:wI(),summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function J5(e,t){let n=Sl("git",["diff","--relative","-z","--name-status","--find-renames",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864}),r=Sl("git",["ls-files","-z","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),i=Sl("git",["diff","--relative","--unified=0",t,"--"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),o=Z5(n);return{changedFileLines:[...new Set([...o.changedFiles,...r.split("\0").filter(Boolean)])],changedRanges:r3(i),renamedFiles:o.renamedFiles,deletedFiles:o.deletedFiles}}function Y5(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=wp(i);if(s.state==="unavailable")throw new Error(`Base content unavailable for ${o}: ${s.reason}`);return s.state==="present"?s.content:null}function wp(e,t=Ip){return RI(e.relativePath),Pp({projectRoot:e.projectRoot,base:e.base,relativePaths:[e.relativePath]},t).get(e.relativePath)??{state:"unavailable",reason:`Base-content lookup omitted ${e.relativePath}.`}}function Pp(e,t=Ip){for(let s of e.relativePaths)RI(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 vp(n,Cp(s))}let i;try{i=t.readBatch({projectRoot:e.projectRoot,resolvedBase:r,relativePaths:n})}catch(s){return vp(n,Cp(s))}let o;try{o=X5(i,n)}catch(s){return vp(n,`Malformed git cat-file batch output: ${Cp(s)}`)}return new Map(n.map(s=>{let a=o.get(s)??null;return[s,a===null?{state:"absent"}:{state:"present",content:a}]}))}function Tp(e,t=Ip){let n=Pp({projectRoot:e.projectRoot,base:e.base,relativePaths:e.preloadPaths??[]},t);return r=>(n.has(r)||n.set(r,wp({projectRoot:e.projectRoot,base:e.base,relativePath:r},t)),n.get(r)??{state:"unavailable",reason:`Base-content reader omitted ${r}.`})}function xI(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 RI(e){Qn(e)}function vp(e,t){return new Map(e.map(n=>[n,{state:"unavailable",reason:t}]))}function Cp(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 X5(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{objectType:a,size:c}=x3(s);if(r+c>e.length)throw new Error("git cat-file batch output ended before blob payload");let l=e.subarray(r,r+c);n.set(i,a==="blob"?l.toString("utf-8"):null),r+=c,e[r]===10&&(r+=1)}return n}function Q5(e,t,n,r){if(n.length===0)return[];let i=new Map,o=new Set;R3(r,n,i,o);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)||!G5(`${e}/${a}`))continue;let c=s.filter(d=>!o.has(d)).filter(d=>bI(d)===bI(a));if(c.length===0)continue;let l=te(e,a),u=c.map(d=>({from:d,to:a,similarity:e3(Y5({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 Z5(e){let t=new Set,n=new Map,r=new Set,i=e.split("\0");for(let o=0;o<i.length;){let s=i[o++],a=i[o++];if(!(!s||!a)){if(s.startsWith("R")||s.startsWith("C")){let c=i[o++];if(!c)throw new Error("Incomplete Git rename/copy record.");t.add(c),s.startsWith("R")&&n.set(c,{from:a,to:c,similarity:Number(s.slice(1))/100});continue}t.add(a),s.startsWith("D")&&r.add(a)}}return{changedFiles:[...t],renamedFiles:[...n.values()],deletedFiles:[...r]}}function e3(e,t){let n=new Set(SI(e)),r=new Set(SI(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 SI(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function t3(e,t){let n=EI(e),r=[];for(let i of t){let o=n(i);o&&!e.isIgnored(o)&&r.push(o)}return r}function n3(e,t){let n=EI(e),r=[];for(let i of t){let o=n(i.file);o&&!e.isIgnored(o)&&r.push({...i,file:o})}return s3(r)}function EI(e){let t=e.all(`SELECT relative_path FROM documents
|
|
293
|
+
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||null}}function r3(e){let t=[],n=null;for(let r of e.split(`
|
|
294
|
+
`)){if(r.startsWith("+++ ")){n=i3(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 i3(e){return e=o3(e),e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function o3(e){if(!e.startsWith('"')||!e.endsWith('"'))return e;let t={a:7,b:8,f:12,n:10,r:13,t:9,v:11,'"':34};t["\\"]=92;let n=e.slice(1,-1),r=[];for(let i=0;i<n.length;){if(n.charCodeAt(i)!==92){let a=String.fromCodePoint(n.codePointAt(i));r.push(...Buffer.from(a)),i+=a.length;continue}i+=1;let o=/^[0-7]{1,3}/u.exec(n.slice(i))?.[0];if(o){r.push(Number.parseInt(o,8)),i+=o.length;continue}let s=t[n[i++]];if(s===void 0)throw new Error("Unsupported escape in Git quoted path.");r.push(s)}return Buffer.from(r).toString("utf8")}function s3(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 a3(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(r=>Lp(e.startLine,e.endLine,r.startLine,r.endLine))}function c3(e,t,n){let r=new Map,i=[],o=II(e),s=p3(n);for(let a of t){let c=o.get(a.file)??[];if(c.some(d=>Lp(d.startLine,d.endLine,a.startLine,a.endLine)))continue;let l=s.get(a.file)??[],u=f3(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(xp(a,"ast-widened"));continue}}if(l.length===0){let d=[...c].filter(m=>m.startLine<=a.startLine).sort((m,p)=>p.startLine-m.startLine||m.endLine-p.endLine)[0];if(d){r.set(d.symbolId,d),i.push(xp(a,"nearest-preceding"));continue}}i.push(xp(a,"unattributed"))}return{definitions:[...r.values()],notes:i}}function l3(e,t,n,r){let i=II(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=>Lp(m.startLine,m.endLine,d.startLine,d.endLine))||o.push(d);o.some(d=>d.file===c)&&s.push(...u3(e,c))}return c3(t,o,s)}function u3(e,t){let n=_(e,t);return n?n.rootNode.namedChildren.filter(d3).map(r=>({file:t,startLine:r.startPosition.row,endLine:r.endPosition.row})).filter(r=>r.endLine>=r.startLine):[]}function d3(e){return e.endPosition.row<e.startPosition.row?!1:!new Set(["import_statement","comment"]).has(e.type)}function m3(e){let t=new Map;for(let n of e)t.set(n.symbolId,n);return[...t.values()]}function II(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 p3(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 f3(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 xp(e,t){return{file:e.file,startLine:e.startLine,endLine:e.endLine,method:t}}function Lp(e,t,n,r){return e<=r&&n<=t}function g3(e,t,n,r,i,o,s,a){let c=new Set([...a,...o,...s].filter(u=>!e.isIgnored(u))).size;if(!C3(t,c))return;let l=L(t.symbol);r.push({symbol:t.symbol,shortName:l,file:t.relativePath,startLine:t.startLine,endLine:t.endLine,fanIn:c});for(let u of a)Rp(e,n,i,u,l);for(let u of o)Rp(e,n,i,u,l);for(let u of s)Rp(e,n,i,u,l)}function vI(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:y3(r)}}}}function h3(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 wI(){return[{tier:"semantic-consumers",state:"complete",attemptedSymbols:0},{tier:"source-fallback-consumers",state:"complete",attemptedSymbols:0}]}function y3(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 b3(e,t){if(t.length===0)return new Map;let n=e.all(`SELECT DISTINCT m.symbol_id, ref_d.relative_path
|
|
295
|
+
FROM mentions m
|
|
296
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
297
|
+
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
298
|
+
WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
|
|
299
|
+
AND m.role != 1
|
|
300
|
+
${e.pathExclusionsFor("ref_d")}`,...t),r=new Map;for(let i of n){let o=r.get(i.symbol_id);o||(o=new Set,r.set(i.symbol_id,o)),o.add(i.relative_path)}return r}function Rp(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 S3(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function v3(e){return!(he(e.symbol)||e.parentTypeName!==null&&!Xe(e.symbol))}function C3(e,t){return Xe(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}function x3(e){let t=/^[0-9a-f]+ ([^ ]+) (\d+)$/.exec(e);if(!t)throw new Error(`unexpected git cat-file batch header: ${e}`);let[,n,r]=t,i=Number(r);if(!Number.isFinite(i)||i<0)throw new Error(`unexpected git cat-file batch size: ${e}`);return{objectType:n,size:i}}function R3(e,t,n,r){for(let i of e.renamedFiles)t.includes(i.to)&&(n.set(i.to,i),r.add(i.from))}function E3(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??zi(e,{base:n}),d={available:u.note!==Ep,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 N(e),p=new Set(u.changedFiles),f=new Map(u.renamedFiles.map(C=>[C.to,C.from])),g=I3(e,t,u,n),h=F3(m,p,f,g);if(h.unavailable)return d.available=!1,d.note=`Base content unavailable: ${h.unavailable.reason}`,d;if(h.definitions.length===0)return d;let y=h.definitions.slice(0,s);h.definitions.length>s&&(d.note=`helper scoring capped at ${s} of ${h.definitions.length} new symbols`);let S=m.calleeMap(y,{semantic:l}),I=y.map(C=>({def:C,callees:dl((S.get(C.symbolId)??[]).map(R=>R.symbol))})),x=Hi(e),E,v={db:e,result:d,changed:p,minCallees:i,minContainment:r,minSiteCoverage:o,getCandidateIndex:()=>(E??=x.calleeIndex({minCallees:Math.min(3,i),scanLimit:c,semantic:l}),E)};for(let{def:C,callees:R}of I)w3(C,R,v);return d.findings.sort((C,R)=>(R.leftovers[0]?.containment??0)-(C.leftovers[0]?.containment??0)||C.helperFile.localeCompare(R.helperFile)),d.findings=d.findings.slice(0,a),d}function I3(e,t,n,r){if(t.baseContentAt&&t.baseContentResultAt)throw new Error("Specify only one of baseContentAt or baseContentResultAt.");return t.baseContentResultAt?t.baseContentResultAt:t.baseContentAt?A3(t.baseContentAt):Tp({projectRoot:e.config.projectRoot,base:r,preloadPaths:xI(n)})}function w3(e,t,n){let{db:r,result:i,changed:o,minCallees:s,minContainment:a,minSiteCoverage:c,getCandidateIndex:l}=n,u=L(e.symbol);if(t.size<s){i.skipped.push({helperShortName:u,helperFile:e.relativePath,reason:`fewer than ${s} meaningful callees \u2014 too small to score`});return}let d=l(),m=D3(t,d);if(m===0){i.skipped.push({helperShortName:u,helperFile:e.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});return}let p=_3(r,e.symbolId);if(p.length===0){i.skipped.push({helperShortName:u,helperFile:e.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});return}i.helpersChecked+=1;let f=P3({candidateIndex:d,changed:o,helperCallees:t,helperFile:e.relativePath,helperSymbol:e.symbol,minContainment:a,minSiteCoverage:c,migratedFiles:p});f.length!==0&&(f.sort((g,h)=>PI(h.migrationScope)-PI(g.migrationScope)||h.containment-g.containment||h.siteCoverage-g.siteCoverage||g.file.localeCompare(h.file)),i.findings.push({helperSymbol:e.symbol,helperShortName:u,helperFile:e.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:t.size,specificHelperCalleeCount:m,migratedFiles:p.sort(),leftovers:f}))}function P3(e){let t=[],n=T3(e.helperSymbol,e.helperFile,e.migratedFiles),r=O3(e.candidateIndex,e.helperCallees);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=hE(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=L3(n,o.symbol,o.file);t.push({symbol:o.symbol,shortName:L(o.symbol),file:o.file,...l,containment:s,siteCoverage:c,uniqueSiteCalleeCount:Math.max(0,o.callees.size-a.length),sharedCallees:a.map(L).sort()})}return t}function PI(e){return e==="shared-vocabulary"?2:e==="unknown"?1:0}function T3(e,t,n){let r=new Set([...Mp(t),...Dp(A(e))]);for(let i of n)for(let o of Mp(i))r.add(o);return r}function L3(e,t,n){let r=new Set([...Mp(n),...Dp(A(t))]);if(e.size===0||r.size===0)return{migrationScope:"unknown",migrationScopeReasons:["insufficient path/name tokens to compare vocabulary"]};let i=[...r].filter(o=>e.has(o)).sort();return i.length>0?{migrationScope:"shared-vocabulary",migrationScopeReasons:[`shares path/name token(s): ${i.join(", ")}`]}:{migrationScope:"distinct-vocabulary",migrationScopeReasons:["no path/name tokens shared with the helper or already migrated files"]}}var M3=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 Mp(e){return Dp(e.replace(/\.[^.]+$/,""))}function Dp(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!M3.has(t))}function D3(e,t){let n=0;for(let r of e)(t.docFreq.get(r)??0)<=t.ubiquityThreshold&&(n+=1);return n}function F3(e,t,n,r){let i=[],o=new Map;for(let s of e.productionCallableDefinitions({files:[...t],requireFunctionLikeSymbol:!0})){if(!t.has(s.relativePath))continue;let a=n.get(s.relativePath)??s.relativePath,c=r(a);if(c.state==="unavailable")return{definitions:[],unavailable:c};if(c.state==="absent"){i.push(s);continue}let l=k3(s.leaf,a,c.content,o);if("unavailable"in l)return{definitions:[],unavailable:l.unavailable};l.exists||i.push(s)}return{definitions:i}}function k3(e,t,n,r){if(!/\.[cm]?[jt]sx?$/i.test(t))return{exists:new RegExp(`\\b${Ge(e)}\\b`).test(n)};let i=N3(t,n,r);return"unavailable"in i?i:{exists:i.names.has(e)}}function N3(e,t,n){let r=n.get(e);if(!r){let i=ot(e,t);if(i.errors.length>0)return{unavailable:{state:"unavailable",reason:i.errors.join("; ")}};r=new Set(i.functions.map(o=>o.name.split(".").at(-1))),n.set(e,r)}return{names:r}}function A3(e){return t=>{let n=e(t);return n===null?{state:"absent"}:{state:"present",content:n}}}function _3(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
|
|
301
|
+
FROM mentions m
|
|
302
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
303
|
+
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
304
|
+
WHERE m.symbol_id = ?
|
|
305
|
+
AND m.role != 1
|
|
306
|
+
${e.pathExclusionsFor("ref_d")}`,t).map(r=>r.relative_path)}function O3(e,t){let n=new Set;for(let r of t)for(let i of e.candidateIndexesByCallee.get(r)??[])n.add(i);return n}function B3(e,t){return t==="config-code"||t==="doc-code"||t==="generated-artifact"||t==="schema-script"?{actionTier:"signal",tierReason:`${t} partner: configuration, documentation, schema, and generated files change alongside many sources`}:e.focusedTogether===0?{actionTier:"signal",tierReason:"every shared commit was a broad sweep; no focused change touched both files"}:e.recency==="stale"&&e.focusedTogether<=2?{actionTier:"signal",tierReason:"at most two focused co-changes, none of them recent"}:{actionTier:"direct",tierReason:`${e.focusedTogether} focused co-change(s)`}}var TI=/(?:^|\/)(?: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 Rs(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=kt(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:[]};if(o===0)return{available:!0,commitsAnalyzed:c.commits.length,findings:[]};let d=t===void 0?u:u.filter(S=>S.fileA.includes(t)||S.fileB.includes(t)),m=typeof n.scanLimit=="number"?d.slice(0,n.scanLimit):d,p=Fe(e),f=kI(e),g=K3(e,p,f),h=n.includeLinked===!0||l,y=$3(e,m,l,h,g,o);return{available:!0,commitsAnalyzed:c.commits.length,findings:y}}function $3(e,t,n,r,i,o){let s=[];for(let a of t){let c=j3(e,a,n,r,i);if(c&&(s.push(c),s.length>=o))break}return s}function j3(e,t,n,r,i){if(!H3(e,t)||!n&&U3(t.fileA,t.fileB))return null;let o=i(t.fileA,t.fileB);if(!r&&o)return null;let s=q3(t.fileA,t.fileB),a=G3(t,s,o);return{...t,structurallyLinked:o,partnerClass:s.partnerClass,partnerClassReasons:s.reasons,...B3(t,s.partnerClass),...a?{declaredCouplingSuggestion:a}:{}}}function H3(e,t){return!(TI.test(t.fileA)||TI.test(t.fileB)||!LI(e,t.fileA)||!LI(e,t.fileB))}function U3(e,t){return!!(F(e)==="test"||F(t)==="test"||Y3(e,t)||V3(e,t))}function LI(e,t){return Ae(e.config.projectRoot,t)}function q3(e,t){let n=DI(e),r=DI(t),i=[],o=a=>{i.includes(a)||i.push(a)},s=(a,c)=>n.tags.has(a)&&r.tags.has(c)||n.tags.has(c)&&r.tags.has(a);return n.tags.has("generated")||r.tags.has("generated")?(o("one side is a generated artifact (migration journal, snapshot, or codegen output) that a tool rewrites whenever its source changes"),{partnerClass:"generated-artifact",reasons:i}):s("doc","code")?(o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:i}):n.tags.has("test")||r.tags.has("test")?(o("one side is classified as a test file"),{partnerClass:"test-code",reasons:i}):s("schema","script")?(o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:i}):s("model","view")?(o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:i}):s("config","code")?(o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:i}):z3(e,t,n,r,i,o)}function z3(e,t,n,r,i,o){let s=aQ(n.tokens,r.tokens).filter(a=>!oQ.has(a));return FI(e,t)||s.length>=2?(o(FI(e,t)?"both files live in the same directory":`files share feature tokens: ${s.slice(0,4).join(", ")}`),{partnerClass:"same-feature",reasons:i}):(o("no specific relationship pattern matched"),{partnerClass:"unknown",reasons:i})}function G3(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!iQ.has(t.partnerClass))return;let r=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${cQ(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 K3(e,t=Fe(e),n=kI(e)){return(r,i)=>X3(t,n,r,i)}var W3=/(?:^|\/)(?:locales|i18n)\//i;function MI(e){return W3.test(e)}function V3(e,t){return MI(e)&&MI(t)?!0:J3(e,t)}function J3(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 Y3(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 kI(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function X3(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 Q3=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,Z3=/(?:^|\/)(?:\.[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,eQ=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,tQ=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)(?![^/]*\.script\.[cm]?[jt]sx?$)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,nQ=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,rQ=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,iQ=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),oQ=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 DI(e){let t=e.replace(/\\/g,"/"),n=new Set;return Vc(t)&&n.add("generated"),lQ(t,n),F(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:sQ(t)}}function FI(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 sQ(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 aQ(e,t){let n=new Set(t);return[...new Set(e.filter(r=>n.has(r)))].sort()}function cQ(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}function lQ(e,t){Q3.test(e)&&t.add("doc"),Z3.test(e)&&t.add("config"),eQ.test(e)&&t.add("schema"),tQ.test(e)&&t.add("script"),nQ.test(e)&&t.add("model"),rQ.test(e)&&t.add("view")}function El(e,t){let n=uQ(e,t)??mQ(e,t)??pQ(e,t)??gQ(e,t);return hQ(e,n,t)}function uQ(e,t){let n=-1,r=null;for(let i=0;i<=t;i+=1){let o=Fp(e[i]??"");o&&(r===null?(r=o,n=i):o===r&&(r=null,n=-1))}return r===null||n<0?null:{start:n,end:dQ(e,t,r)}}function dQ(e,t,n){for(let r=t+1;r<e.length;r+=1)if(Fp(e[r]??"")===n)return r+1;return e.length}function Fp(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function mQ(e,t){if(!xl(e[t]??""))return null;let n=t;for(;n>0&&xl(e[n-1]??"");)n-=1;let r=t+1;for(;r<e.length&&xl(e[r]??"");)r+=1;return{start:n,end:r}}function xl(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function pQ(e,t){let n=t;for(;n>=0;){let i=e[n]??"";if(Rl(i)!==null)break;if(kp(i)!==null)return null;n-=1}if(n<0)return null;let r=Rl(e[n]??"");return r===null?null:{start:n,end:fQ(e,n,r)}}function fQ(e,t,n){let r=t+1;for(;r<e.length;){let i=e[r]??"",o=Rl(i);if(o!==null){if(o<=n)break;r+=1;continue}if(kp(i)!==null)break;r+=1}return r}function Rl(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function gQ(e,t){let n=e[t]??"";if(AI(n)||n.trim().length===0)return{start:t,end:t+1};let r=t;for(;r>0&&NI(e[r-1]??"");)r-=1;let i=t+1;for(;i<e.length&&NI(e[i]??"");)i+=1;return{start:r,end:i}}function NI(e){return kp(e)===null}function kp(e){return e.trim().length===0?"blank":AI(e)?"heading":Fp(e)?"fence":xl(e)?"table":Rl(e)!==null?"list":null}function AI(e){return/^#{1,6}\s+/.test(e.trim())}function hQ(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(`
|
|
307
|
+
`).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function Dr(e,t){return t.filter(n=>e.includes(n))}var yQ=/<!--\s*scip-query:\s*snapshot\s*-->/i;function _I(e,t){if((e.config.docs?.snapshotPaths??[]).some(i=>Ft(i,t)))return!0;let r=H(e,t);return r.length>0&&yQ.test(r)}var OI={classifyCitation:SQ,citationContexts:vQ,citationKindLabel:xQ,citationRemediation:RQ,referenceTargets:EQ,hasLineAnchoredCitation:bQ};function bQ(e){return e.some(t=>(t.lineReferences?.length??0)>0)}function SQ(e){let t=e.join(`
|
|
308
|
+
`).toLowerCase(),n=[],r=Dr(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=Dr(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=Dr(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 vQ(e,t,n){let r=H(e,t);if(!r&&!Ae(e.config.projectRoot,t))return[];let i=r.split(/\r?\n/),o=n.flatMap(CQ),s=[];for(let a=0;a<i.length;a+=1){let c=i[a]??"";o.some(l=>c.includes(l))&&s.push(El(i,a))}return s}function CQ(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 xQ(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 RQ(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 EQ(e,t,n){let r=bl(n),i=new Set;for(let o of t)IQ(e,o,r.get(o)??[])&&i.add(o);return i}function IQ(e,t,n){if(!wQ.test(t)||!Ae(e.config.projectRoot,t))return!0;if(n.length===0)return!1;let r=te(e.config.projectRoot,t,{inputKind:"changed source file"}).split(/\r?\n/),i=PQ(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 wQ=/\.(?:[cm]?[jt]sx?)$/i;function PQ(e){let t=new Set,n=!1;for(let r=0;r<e.length;r+=1){let i=e[r].trim();!n&&TQ(i)&&(n=!0),n&&(t.add(r),i.endsWith(";")&&(n=!1))}return t}function TQ(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}var BI=rt({kind:"doc-path-evidence",invalidation:Re("doc-path-evidence"),serialize:zQ,deserialize:GQ}),Es=/\.(?:md|mdx|rst|txt)$/i;function LQ(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var MQ=3,DQ=/([A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6})(?::([1-9][0-9]*))?\b/g;function FQ(e,t={}){let{doc:n,limit:r=20,minCoupling:i=MQ,includeSnapshotExcluded:o=!1}=t,s=BQ(e,t.historyMode??"bounded");if(!s)return{available:!1,commitsAnalyzed:0,docsScanned:0,findings:[]};let a=[],c=0;for(let l of s.docFiles){let u=kQ(e,l,n,o);if(u===null)continue;c+=1;let d=NQ(e,s,l,u,i);d&&a.push(d)}return a.sort((l,u)=>u.staleness-l.staleness),{available:!0,commitsAnalyzed:s.historyCommitCount,docsScanned:c,findings:a.slice(0,r)}}function kQ(e,t,n,r){if(n!==void 0&&!t.includes(n)||n===void 0&&!$Q(e,t)||n!==void 0&&!Ae(e.config.projectRoot,t))return null;let i=_I(e,t);return i&&!r?null:i}function NQ(e,t,n,r,i){let{value:o,estimated:s}=AQ(e,n,t.changeTimes.get(n)),a=_Q(e,n),c=new Map,{resolved:l,broken:u,citations:d}=HQ(e,n,t.tracked,t.trackedBySuffix,t.everSeenInHistory),m=new Map(d.map(h=>[h.file,h])),p=()=>{for(let h of l){if(h===n||Es.test(h))continue;let y=(t.changeTimes.get(h)??[]).filter(I=>I>o).length;if(y===0)continue;let S=m.get(h);c.set(h,{file:h,evidence:"reference",coChanges:0,changesSinceDocUpdate:y,...Np("reference",a,S?.contexts),citationContexts:S?.contexts,citedLines:S?.lineReferences})}},f=()=>{for(let[h,y]of t.coupling.get(n)??[]){if(y<i||!t.tracked.has(h))continue;let S=(t.changeTimes.get(h)??[]).filter(x=>x>o).length;if(S===0)continue;let I=c.get(h);I?(I.evidence="both",I.coChanges=y,Object.assign(I,Np("both",a,I.citationContexts))):c.set(h,{file:h,evidence:"co-change",coChanges:y,changesSinceDocUpdate:S,...Np("co-change",a)})}};if(p(),f(),c.size===0&&u.length===0)return null;let g=[...c.values()].sort((h,y)=>y.changesSinceDocUpdate-h.changesSinceDocUpdate);return{doc:n,docLastChangedAt:o,staleness:g.reduce((h,y)=>h+y.changesSinceDocUpdate,0)+u.length*10,subjects:g,brokenReferences:u,...r?{snapshotExcluded:!0}:{},...s?{docLastChangedAtEstimated:!0}:{}}}function AQ(e,t,n){if(n&&n.length>0)return{value:Math.max(...n),estimated:!1};try{return{value:Math.floor(Vs(e.config.projectRoot,t).mtimeMs/1e3),estimated:!0}}catch(r){if(Ae(e.config.projectRoot,t))throw r;return{value:0,estimated:!1}}}function _Q(e,t){let n=H(e,t).slice(0,6e3);if(!n)return{docIntent:"unknown",reasons:["doc text unavailable"]};let r=`${t}
|
|
309
|
+
${n}`.toLowerCase(),i=Dr(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=Dr(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 Np(e,t,n=[]){let r=e==="co-change"||n.length===0?null:OI.classifyCitation(n);return{actionTier:OQ(e,t.docIntent,r?.actionTier),docIntent:t.docIntent,docIntentReasons:t.reasons,...r?{citationKind:r.citationKind,citationKindReasons:r.reasons}:{}}}function OQ(e,t,n){return t==="historical-note"?"support":n||(e==="co-change"?"signal":"direct")}function BQ(e,t){let n=kt(e,{historyMode:t}),r=n.commitHistory();if(!r)return null;let i=n.trackedFiles();if(!i)return null;let 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=>Es.test(m)),d=l.filter(m=>!Es.test(m));for(let m of l){a.add(m);let p=o.get(m)??[];p.push(c.timestamp),o.set(m,p)}for(let m of u){let p=s.get(m);p||(p=new Map,s.set(m,p));for(let f of d)p.set(f,(p.get(f)??0)+1)}}return{changeTimes:o,coupling:s,docFiles:[...i].filter(c=>Es.test(c)),everSeenInHistory:a,historyCommitCount:r.commits.length,tracked:i,trackedBySuffix:jQ(i)}}function $Q(e,t){return Es.test(t)&&!LQ(t)&&Ae(e.config.projectRoot,t)}function jQ(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 HQ(e,t,n,r,i){let o=new Set,s=new Set,a=UQ(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let c=a.candidates,l=a.contextsByCandidate,u=a.lineReferencesByCandidate,d=new Map,m=new Map,p=(f,g)=>{let h=l.get(g);if(h&&h.length>0){let S=d.get(f)??[];S.push(...h),d.set(f,$I(S).slice(0,3))}let y=u.get(g);y&&y.length>0&&m.set(f,Ap([...m.get(f)??[],...y]))};for(let f of c){if(n.has(f)){o.add(f),p(f,f);continue}let g=r.get(f);if(g&&g.length===1){o.add(g[0]),p(g[0],f);continue}g&&g.length>1||i.has(f)&&s.add(f)}return{resolved:o,broken:[...s],citations:[...d].map(([f,g])=>({file:f,contexts:g,lineReferences:m.get(f)}))}}function UQ(e,t,n){let r=n;if(r===void 0&&(r=H(e,t),!r&&!Ae(e.config.projectRoot,t)))return null;let i=bt(e,t,r),o=BI.read(e,t,i);if(o)return o;let s=qQ(r);return BI.write(e,t,i,s),s}function qQ(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]??"";JQ(t,o,s,n,r,i)}return{candidates:[...n],contextsByCandidate:r,lineReferencesByCandidate:i}}function zQ(e){let t={candidates:e.candidates,contextsByCandidate:[...e.contextsByCandidate.entries()],lineReferencesByCandidate:[...e.lineReferencesByCandidate.entries()]};return JSON.stringify(t)}function GQ(e){try{let t=JSON.parse(e);if(!Qf(t))return null;let n=io(t.candidates),r=WQ(t.contextsByCandidate),i=KQ(t.lineReferencesByCandidate);return!n||!r?null:{candidates:n,contextsByCandidate:new Map(r),lineReferencesByCandidate:new Map(i??[])}}catch{return null}}function KQ(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=YQ(n[1]);if(!r)return null;t.push([n[0],Ap(r)])}return t}function WQ(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=io(n[1]);if(!r)return null;t.push([n[0],r])}return t}function $I(e){let t=[];for(let n of new Set(e))t.some(r=>VQ(r,n))||t.push(n);return t}function Ap(e){return[...new Set(e)].sort((t,n)=>t-n)}function VQ(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}function JQ(e,t,n,r,i,o){for(let s of n.matchAll(DQ)){let a=(s[1]??"").replace(/^\.?\//,"");if(a.length===0)continue;r.add(a);let c=s[2]?Number(s[2]):null;c!==null&&Number.isSafeInteger(c)&&o.set(a,Ap([...o.get(a)??[],c]));let l=El(e,t);if(l.length===0)continue;let u=i.get(a)??[];u.push(l),i.set(a,$I(u).slice(0,3))}}function YQ(e){let t=[];for(let n of e){if(typeof n!="number"||!Number.isSafeInteger(n))return null;t.push(n)}return t}import{ts as Il}from"@ts-morph/common";var XQ=new Set(pa());function QQ(e,t={}){let{includeHomonyms:n=!1,limit:r}=t,i=wl(e,t).filter(o=>o.relationship==="divergent"||n&&o.relationship==="homonym");return r?i.slice(0,r):i}function wl(e,t={}){let{scope:n,minSimilarity:r=.3,scanLimit:i}=t,o=i6(e,{scope:n,scanLimit:i});return qI(o,{minSimilarity:r,isDelegatePair:A6(e)}).filter(s=>!s.members.some(a=>_e(e,a.file,a.startLine,"twin")))}function ZQ(e,t){let n=new Set(e.filter(r=>e.some(i=>i!==r&&i.file!==r.file&&t?.(r,i,e))).map(r=>r.symbol));return e.filter(r=>!n.has(r.symbol))}function e6(e,t,n,r){return!(e.file===t.file||!w6(e,t)||r?.(e,t,n)||r?.(t,e,n)||jI(e,t)||jI(t,e))}function t6(e,t){let n=null,r=!1,i=!1,o=new Set;for(let s=0;s<e.length;s+=1)for(let a=s+1;a<e.length;a+=1){let c=e[s],l=e[a];if(!e6(c,l,e,t))continue;if(r=!0,o.add(c.symbol),o.add(l.symbol),c.normalizedBody===l.normalizedBody){i=!0;continue}let u=f6(c.tokens,l.tokens);(!n||u>n.similarity)&&(n={a:c,b:l,similarity:u})}return{bestNonIdentical:n,hasCrossFilePair:r,hasIdenticalPair:i,participatingSymbols:o}}function qI(e,t={}){let n=t.minSimilarity??.3,r=t.isDelegatePair,i=e.filter(u=>!ZI(u.leaf)&&!b6(u.leaf)&&!GI(u.symbol,u.leaf)&&!KI(u.file,u.leaf)&&F(u.file)!=="test"&&!ke(u.symbol)&&!WI(u.symbol)&&!VI(u.symbol,u.leaf)),{recordsByLeaf:o,recordOrder:s}=M("twin-drift.group-by-leaf",()=>n6(i),()=>({records:i.length})),a=M("twin-drift.cluster-leaf-names",()=>zI([...o.keys()]),()=>({leaves:o.size})),c=u=>{let d=r6(u,o,s),m=ZQ(d,r);if(m.length<2||new Set(m.map(I=>I.file)).size<2)return null;let{bestNonIdentical:p,hasCrossFilePair:f,hasIdenticalPair:g,participatingSymbols:h}=t6(m,r);if(!f)return null;let y=m.filter(I=>h.has(I.symbol)).sort((I,x)=>I.file.localeCompare(x.file)||I.startLine-x.startLine).map(p6);if(!p)return{leaf:UI(u),relationship:g?"identical":"homonym",maxDivergence:0,members:y};let S=p.similarity>=n?"divergent":"homonym";return{leaf:UI(u),relationship:S,maxDivergence:Math.round((1-p.similarity)*1e3)/1e3,members:y,...S==="divergent"?{firstDivergentTokens:g6(p.a.tokens,p.b.tokens)}:{}}};return M("twin-drift.compare-clusters",()=>{let u=[];for(let d of a){let m=c(d);m&&u.push(m)}return u},()=>({clusters:a.length,records:i.length})).sort((u,d)=>d.members.length-u.members.length||d.maxDivergence-u.maxDivergence||u.leaf.localeCompare(d.leaf))}function n6(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 r6(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 i6(e,t){let n=M("twin-drift.load-definitions",()=>Pe(e,{scope:t.scope}).filter(o=>o6(o)&&!e.isIgnored(o.relativePath)).filter(o=>!Sr(o.relativePath)));M("twin-drift.sort-definitions",()=>n.sort((o,s)=>o.relativePath.localeCompare(s.relativePath)||o.startLine-s.startLine),()=>({definitions:n.length}));let r=ge(n,t.scanLimit),i=M("twin-drift.select-candidates",()=>s6(r),()=>({scanned:r.length}));return M("twin-drift.build-records",()=>{let o=[];for(let s of i){let a=a6(e,s);a&&o.push(a)}return o},()=>({candidates:i.length,scanned:r.length}))}function o6(e){return e.isFunctionLike?e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&XQ.has(e.kind):!0:!1}function s6(e){let t=e.filter(o=>o.leaf&&!ZI(o.leaf)&&!GI(o.symbol,o.leaf)&&!KI(o.relativePath,o.leaf)&&!ke(o.symbol)&&!WI(o.symbol)&&!VI(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=zI([...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=>F(a.relativePath)==="test"))for(let a of s)i.add(a)}return e.filter(o=>i.has(o))}function a6(e,t){if(!t.leaf)return null;let n=tt(e,t);if(!n||!Xe(t.symbol)&&!u6(n,t.leaf)||c6(n,t.leaf))return null;let r=Qt(n),i=tr(r),o=ll(n);if(!o||o.length<8)return null;let s=d6(r,t.relativePath);return s.length===0?null:{leaf:t.leaf,symbol:t.symbol,shortName:L(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:oe(t),normalizedBody:o,tokens:s,isThinForwarder:_p(i),forwardTargetLeaf:l6(i)}}function c6(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=e.split(`
|
|
310
|
+
`).slice(0,2).join(`
|
|
311
|
+
`);return new RegExp(`\\b(?:abstract|override)\\b[^\\n]*\\b${n}\\s*[(<]`).test(r)}function l6(e){if(!_p(e))return null;let t=XI(e.trim()),n=YI(t[t.length-1]),r=/^([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/.exec(n)?.[1];return r?r.split(".").pop()??null:null}function jI(e,t){let n=e.forwardTargetLeaf;return typeof n=="string"&&n!==e.leaf&&n!==t.leaf&&!t.isThinForwarder}function u6(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)}function d6(e,t){if(!/\.[cm]?[jt]sx?$/i.test(t))return e.match(m6)??[];let n=Il.createScanner(Il.ScriptTarget.Latest,!0,Il.LanguageVariant.Standard,e),r=[];for(;n.scan()!==Il.SyntaxKind.EndOfFileToken;)r.push(n.getTokenText());return r}var m6=/[A-Za-z_$][A-Za-z0-9_$]*|\d+(?:\.\d+)?|[^\sA-Za-z0-9_$]/g;function p6(e){return{symbol:e.symbol,shortName:e.shortName,file:e.file,startLine:e.startLine,endLine:e.endLine,loc:e.loc}}function f6(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 g6(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 zI(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)h6(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 h6(e,t){return e===t||e.toLowerCase()===t.toLowerCase()?!0:e.length<8||t.length<8||Math.abs(e.length-t.length)>2||$6(e,t)||y6(e.toLowerCase(),t.toLowerCase())/Math.max(e.length,t.length)<.8?!1:P6(e.toLowerCase(),t.toLowerCase(),2)}function y6(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;return r}function b6(e){return/^[A-Z][A-Z0-9_]*$/.test(e)||/^__[^_].*__$/.test(e)||S6.has(e.toLowerCase())}var S6=new Set(["main","row"]),v6=new Set(["close","connect","count","create","delete","destroy","disconnect","dispose","execute","exists","find","findAll","findById","findOne","get","getAll","getById","handle","init","initialize","list","load","open","patch","process","read","remove","reset","run","save","shutdown","start","stop","toJSON","toString","update","upsert"]),C6=/#(?:`[^`]+`|[^#/`]+)\(\)\.$/,x6=/^(?:get|find|list|load|fetch|count|delete|remove|update|upsert)(?:By|For)[A-Z]\w*$/;function GI(e,t){return(v6.has(t)||x6.test(t))&&C6.test(e)}var R6=/^(?:handler|handle(?:Get|Post|Put|Patch|Delete|Options|Head|Request)|(?:get|post|put|patch|delete|options|head|route|request)Handler|generateMetadata|generateStaticParams|generateViewport|generateSitemaps|loader|action|clientLoader|clientAction|middleware|config|default|load|actions|[A-Z][A-Za-z0-9]*(?:Page|Layout|Loading|Template|Route|Screen))$/;function KI(e,t){return R6.test(t)&&gn(e.replace(/\\/g,"/"))}var E6=new Set(["app","component","components","feature","features","impl","index","lib","route","routes","shared","src","tsx","typescript","ui"]);function WI(e){return e.startsWith("rust-analyzer ")&&/\/(?:tests?|benches?)\//.test(e)}var I6=new Set(["default","new","reset"]);function VI(e,t){return e.startsWith("rust-analyzer ")&&I6.has(t.toLowerCase())}function w6(e,t){if(e.leaf.toLowerCase()!==t.leaf.toLowerCase()||e.leaf.length>4)return!0;let n=HI(e);return[...HI(t)].some(r=>n.has(r))}function HI(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&&!E6.has(n)))}function P6(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 JI(e){return _p(tr(Qt(e)))}function _p(e){let t=e.trim();if(!t||T6.test(t))return!1;let n=XI(t);return n.length===0||n.length>2?!1:M6(n[n.length-1])}var T6=/\b(?:if|else|for|while|switch|try|catch|do)\b/,L6=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^[\]]*\])*\((?:[^()]|\([^()]*\))*\)$/;function M6(e){return L6.test(YI(e))}function YI(e){return D6(e.trim().replace(/^return\s+/,"").replace(/^await\s+/,"").replace(/;\s*$/,"").trim())}function D6(e){let t=e.indexOf("<");if(t<0||!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(e.slice(0,t)))return e;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 e[r+1]==="("?e.slice(0,t)+e.slice(r+1):e}return e}var F6=new Set(["(","[","{"]),k6=new Set([")","]","}"]);function XI(e){let t=[],n=0,r="";for(let i of e){if(F6.has(i)?n+=1:k6.has(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 N6=3;function A6(e){let t=new Map;return(n,r,i)=>{let o=`${n.symbol}\0${r.symbol}`,s=t.get(o);if(s!==void 0)return s;let a=QI(e,n,r,i,N6,new Set);return t.set(o,a),a}}function QI(e,t,n,r,i,o){if(i<=0||o.has(t.symbol))return!1;o.add(t.symbol);let s=V(e,t.file),a=_6(e,t,n,s);if(a.length===0)return!1;if(O6(e,a,s,n.file))return!0;let c=B6(e,s,n.leaf);return[...c].some(l=>ze(l,n.file))?!0:r.some(l=>l.symbol===t.symbol||l.symbol===n.symbol||!l.isThinForwarder||![...c].some(u=>ze(u,l.file))?!1:QI(e,l,n,r,i-1,o))}function _6(e,t,n,r){let i=new Set;for(let o of r)o.importedName===n.leaf&&o.localName&&o.localName!==n.leaf&&i.add(o.localName);return i.size===0&&i.add(n.leaf),(rr(e,t.file)??[]).filter(o=>o.line>=t.startLine&&o.line<=t.endLine&&i.has(o.calleeLeaf))}function O6(e,t,n,r){for(let i of t){if(!i.calleeQualifier)continue;let o=n.find(s=>s.localName===i.calleeQualifier&&s.sourcePath);if(o?.sourcePath){if(ze(o.sourcePath,r))return!0;for(let s of V(e,o.sourcePath))if(s.sourcePath&&ze(s.sourcePath,r))return!0}}return!1}function B6(e,t,n){let r=new Set(t.filter(i=>i.sourcePath&&(i.kind!=="namespace"||i.usedMembers.includes(n))).map(i=>i.sourcePath));for(let i of[...r])for(let o of Ot(e,i))o.sourcePath&&r.add(o.sourcePath);return r}function ZI(e){return e.startsWith("<")&&e.endsWith(">")}function UI(e){return[...e].sort()[0]}function $6(e,t){let[n,r]=e.length<=t.length?[e,t]:[t,e];return!!(r.length>n.length&&r.startsWith(n)&&/^[A-Z]/.test(r.slice(n.length)))}import{basename as nw,extname as rw}from"path";function Gi(e){let t=j6(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=ge(o,e.scanLimit),a=e.orderScanned?[...s].sort(e.orderScanned):s;t={pipeline:e.profile?.name,loadedCandidates:r.length,filteredCandidates:i.length,scannedCandidates:a.length,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:a.length<i.length,resultLimitApplied:!1};let c=e.prepare?.(a)??void 0,l=[];for(let d of a){t.evaluatedCandidates+=1;let m=e.evaluate(d,c);m&&l.push(m),e.onProgress?.({evaluated:t.evaluatedCandidates,scanned:a.length,matched:l.length})}t.matchedResults=l.length,e.orderResults&&l.sort(e.orderResults);let u=typeof e.limit=="number"?l.slice(0,e.limit):l;return t.emittedResults=u.length,t.resultLimitApplied=u.length<l.length,e.onProfile?.({...t}),u};return e.profile?M(`candidate-pipeline:${e.profile.name}`,n,()=>({...H6(e.profile?.metadata),...t})):n()}function j6(e){return{pipeline:e,loadedCandidates:0,filteredCandidates:0,scannedCandidates:0,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:!1,resultLimitApplied:!1}}function H6(e){return typeof e=="function"?e():e??{}}function ew(e,t,n,r,i,o){let s=new Set;z6(e,t,n,r)&&s.add(i);let a=U6(o);for(let c of o)c.value&&q6(s,c.label,c.value,a);return[...s].slice(0,6)}function U6(e){let t={self:new Set,other:new Set},n=0;for(let r of e)if(!(!r.side||!r.value)){n+=1;for(let i of tw(r.value))t[r.side].add(i)}return n===0||t.self.size===0||t.other.size===0?new Set:new Set([...t.self].filter(r=>t.other.has(r)))}function q6(e,t,n,r){let i=tw(n);t.endsWith("name")&&G6(i)&&e.add(`${t} has type-guard boundary shape`);for(let o of i){if(r.has(o))continue;let s=K6.get(o);s&&e.add(`${t} has ${s} term: ${o}`)}}function z6(e,t,n,r){if(n<=0)return!1;let i=j(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(zr(s)===r)return!0;if(!J6(s))return!1}}return!1}function tw(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 G6(e){return e.some(t=>W6.has(t))&&e.some(t=>V6.has(t))}var K6=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"]]),W6=new Set(["can","has","is","should"]),V6=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function J6(e){return["//","*","/*","@","#"].some(t=>e.startsWith(t))}function Is(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new N(e),a=Gi({candidates:()=>nZ(e,s,n,r),orderCandidates:dv,scanLimit:o,profile:{name:"passthrough-candidates"},prepare:c=>s.calleeMap(c,{semantic:t?.semantic!==!1}),evaluate:(c,l)=>X6(e,c,l.get(c.symbolId)??[]),orderResults:(c,l)=>c.loc-l.loc||c.file.localeCompare(l.file)});return Y6(a).slice(0,i===void 0?a.length:i)}var Op=3;function Y6(e){let t=new Map,n=new Map;for(let r of e){if(r.file===r.forwardsToFile)continue;let i=`${r.file}\0${r.forwardsToFile}`;t.set(i,(t.get(i)??0)+1);let o=ea(r.symbol),s=ea(r.forwardsTo);if(!o||!s||o===s)continue;let a=`${r.file}\0${o}`;n.set(a,(n.get(a)??0)+1)}return e.map(r=>{let i=t.get(`${r.file}\0${r.forwardsToFile}`)??0,o=ea(r.symbol),s=o?n.get(`${r.file}\0${o}`)??0:0;if(i<Op&&s<Op)return r;let a=i>=Op?`facade: ${i} sibling forwards from this file to ${r.forwardsToFile}`:`facade: ${s} methods of ${o} forward to members of its collaborators`,c=[...r.boundaryEvidence,a];return{...r,boundaryEvidence:c,actionTier:"signal",recommendation:iw("signal",c,r.publicFacadeEvidence)}})}function X6(e,t,n){let r=tZ(n);if(r.size!==1||!ag(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0],o=Q6(e,t,i),s=Z6(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:L(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:oe(t),forwardsTo:i.symbol,forwardsToShort:L(i.symbol),forwardsToFile:i.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:iw(a,o,s)}}function Q6(e,t,n){return ew(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:au(t.symbol),side:"self"},{label:"callee name",value:au(n.symbol),side:"other"},{label:"passthrough module",value:nw(t.relativePath,rw(t.relativePath)),side:"self"},{label:"callee module",value:nw(n.file,rw(n.file)),side:"other"}])}function iw(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(eZ);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 Z6(e,t){return Pt(e,t)?fn(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:We(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function eZ(e){return e.includes("public surface")}function tZ(e){let t=e.some(r=>be(r.symbol))?e.filter(r=>be(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function nZ(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:3,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0}).filter(i=>!cg(e,i)).filter(i=>!_e(e,i.relativePath,i.startLine,"passthrough"))}var ow={caller:3,"entry-surface":2,rooted:1},rZ=/not\s*yet\s*implement|not\s*implement|unimplement|\bnyi\b|\btodo\b|\bstub\b|not\s*supported|coming\s*soon/i,iZ=/^throw\s+new\s+[\w.]*Error\s*\(([\s\S]*)\)\s*;?$/,oZ=/^return(\s+(null|undefined|false|0|''|""|``|\[\]|\{\}))?\s*;?$/,sZ=/\/\/\s*TODO\b|\/\*\s*TODO\b/i,aZ=/(?:=>|\))\s*(?::\s*[^{;=]+)?\s*\{\s*\}\s*;?\s*$/;function cZ(e,t={}){let{scope:n,limit:r=30,scanLimit:i,semantic:o=!0}=t,s=new N(e),a=ge(s.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),c=[];for(let d of a){let m=uZ(e,d);m&&c.push(m)}if(c.length===0)return[];let l=yl(e,s).forDefinitions(c.map(d=>d.def),{semantic:o}),u=[];for(let d of c){let p=l.get(d.def.symbolId)?.realConsumers.length??0,f=lZ(e,d.def,p);f&&u.push({symbol:d.def.symbol,shortName:L(d.def.symbol),file:d.def.relativePath,startLine:d.def.startLine,endLine:d.def.endLine,loc:oe(d.def),stubKind:d.stubKind,reachability:f,callerFanIn:p,stubText:d.stubText})}return u.sort((d,m)=>ow[m.reachability]-ow[d.reachability]||m.callerFanIn-d.callerFanIn||d.file.localeCompare(m.file)||d.startLine-m.startLine),r?u.slice(0,r):u}function lZ(e,t,n){return n>0?"caller":We(e,t.symbol,t.relativePath)?"rooted":Ke(e,t.relativePath)?"entry-surface":null}function uZ(e,t){let n=tt(e,t);if(!n)return null;let r=Qt(n),i=r.trim();if(i==="")return!gZ(n)||!Pt(e,t)?null:{def:t,stubKind:"empty-body",stubText:"(empty body)"};let o=so(r),s=tr(r),a=pZ(o,s);if(a.length!==1)return null;let c=a[0];return fZ(c)?{def:t,stubKind:"throw-stub",stubText:c.trim()}:sZ.test(r)&&oZ.test(c.trim())?{def:t,stubKind:"todo-return-default",stubText:i}:null}var dZ=new Set(["(","[","{"]),mZ=new Set([")","]","}"]);function pZ(e,t){let n=[],r=0,i="";for(let o=0;o<t.length;o+=1){let s=t[o];if(dZ.has(s)?r+=1:mZ.has(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 fZ(e){let t=iZ.exec(e.trim());return t?rZ.test(t[1]??""):!1}function gZ(e){return aZ.test(e.trimEnd())}var hZ=/^(?:validate|verify|check|assert)(?:[A-Z].*)?$/,yZ=/^(?:is|has)(?:[A-Z].*)?$/,bZ=/[{,]\s*(?:ok|success|valid|isValid)\s*:\s*false\b/,Bp=/\breturn\b/g,SZ=/\bfunction\b|=>|\)\s*(?::\s*[^{;=]+)?\s*\{/,vZ=/\.(?:addIssue|push)\s*\(/;function CZ(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new N(e),s=ge(o.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),a=[];for(let c of s){let l=RZ(e,c);l&&a.push({symbol:c.symbol,shortName:L(c.symbol),file:c.relativePath,startLine:c.startLine,endLine:c.endLine,loc:oe(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 xZ(e){return hZ.test(e)?"imperative":yZ.test(e)?"predicate":null}function RZ(e,t){let n=xZ(t.leaf);if(!n||Qc(e,t))return null;let r=tt(e,t);if(!NZ(r))return null;let i=z(e,t.relativePath)?.callables.find(s=>s.startLine===t.startLine&&s.endLine===t.endLine);if(n==="predicate"&&i?.paramCount===0)return null;if(JI(r)){let s=kZ(e,t);return!s||sw(s.body,s.snippet)?null:{nameKind:n,resolvedVia:"one-hop-delegate",delegateTarget:s.shortName}}let o=Qt(r);return sw(o,r)?null:{nameKind:n,resolvedVia:"direct"}}var EZ=new Set(["if","for","while","switch","catch","function"]);function IZ(e){let t=so(e);for(let n of t.matchAll(/\b([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/g))if(!EZ.has(n[1]))return!0;return!1}function wZ(e){let t=e.indexOf("=>");return t===-1?!1:!/^\s*\{/.test(e.slice(t+2))}function PZ(e,t){let n=so(e);return/\bthrow\b/.test(n)||/\.reject\s*\(/.test(n)||bZ.test(n)||vZ.test(n)?!0:TZ(n,t)}function TZ(e,t){let n=FZ(e);if(t&&n.length===0){let r=e.trim();return r!==""&&r!=="true"}for(let r of n)if(r!==""&&r!=="true")return!0;return!1}var LZ=new Set(["(","[","{"]),MZ=new Set([")","]","}"]);function DZ(e,t){let n=0,r=e.length;for(let i=t;i<e.length;i+=1){let o=e[i];if(LZ.has(o))n+=1;else if(MZ.has(o)){if(n===0){r=i;break}n-=1}else if(o===";"&&n===0){r=i;break}}return r}function FZ(e){let t=[];Bp.lastIndex=0;let n;for(;n=Bp.exec(e);){let r=n.index+n[0].length,i=DZ(e,r);t.push(e.slice(r,i).trim()),Bp.lastIndex=i}return t}function kZ(e,t){let n=jt(e,t,{callableOnly:!0,limit:3,semanticEvidence:ie}),r=[...new Set(n.map(c=>c.symbol))].filter(c=>c!==t.symbol);if(r.length!==1)return null;let o=J(e,r[0]).match;if(!o)return null;let s=D(e,o.relativePath).find(c=>c.symbolId===o.symbolId);if(!s)return null;let a=tt(e,s);return a?{body:Qt(a),snippet:a,shortName:L(s.symbol)}:null}function sw(e,t){return PZ(e,wZ(t))||IZ(e)}function NZ(e){return!!e&&SZ.test(e)}import{ts as dt}from"@ts-morph/common";var AZ=60;function _Z(e,t={}){let{scope:n,limit:r=30,scanLimit:i,rotDays:o=AZ}=t,s=ge(Kr(e,{extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs"]}).filter(u=>F(u)==="test").filter(u=>!n||u.includes(n)).filter(u=>!e.isIgnored(u)).sort(),i),a=[],c=[],l=[];for(let u of s)OZ(e,u,o,{assertionFree:a,skipped:c,mockEcho:l});return{assertionFree:r?a.slice(0,r):a,skipped:r?c.slice(0,r):c,mockEcho:r?l.slice(0,r):l}}function OZ(e,t,n,r){let{assertionFree:i,skipped:o,mockEcho:s}=r,a=H(e,t);if(!a)return;let c=tg(a),l=zZ(a);for(let d of JZ(c,l))l.add(d);let u=BZ(a,t);for(let d of u){if(d.skip){o.push(n8(e,t,d,n));continue}if(d.kind==="describe")continue;let m=cw(a,d.argsStart),p=c.slice(d.argsStart,d.callEnd),f=a.slice(d.argsStart,d.callEnd);lw(p,l)||i.push({file:t,startLine:ws(a,d.callStart),endLine:ws(a,d.callEnd),title:m,severity:/\bawait\b/.test(p)?"low":"high"});let g=ZZ(p,f);g&&s.push({file:t,startLine:ws(a,d.callStart),endLine:ws(a,d.callEnd),title:m,echoedValue:g})}}function BZ(e,t){let n=[],r=dt.createSourceFile(t,e,dt.ScriptTarget.Latest,!0);function i(o){if(dt.isCallExpression(o)){let s=$Z(o,r);s&&n.push(s)}dt.forEachChild(o,i)}return i(r),n}function $Z(e,t){let n=jZ(e.expression);if(!n)return;let{kind:r,skip:i,skipKind:o}=n,s=e.arguments.at(-1);if(!(!i&&!HZ(s)))return{kind:r,skip:i,skipKind:o,callStart:e.getStart(t),argsStart:e.arguments.pos,callEnd:e.end}}function jZ(e){let t=e,n;if(dt.isPropertyAccessExpression(e)&&(t=e.expression,n=e.name.text),!dt.isIdentifier(t))return;let r=/^(x?)(it|test|describe)$/.exec(t.text);if(!r||n!==void 0&&!["skip","only","todo"].includes(n))return;let i=!!r[1]||n==="skip"||n==="todo";return{kind:r[2],skip:i,skipKind:n==="todo"?"todo":"skip"}}function HZ(e){return e!==void 0&&(dt.isArrowFunction(e)||dt.isFunctionExpression(e))}function Pl(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 ws(e,t){let n=0;for(let r=0;r<t&&r<e.length;r+=1)e[r]===`
|
|
312
|
+
`&&(n+=1);return n}function cw(e,t){let n=e.slice(t,t+400),r=/^\s*(['"`])((?:\\.|(?!\1)[\s\S])*)\1/.exec(n);return r?r[2]:"(anonymous)"}var UZ=new Set(["vitest","chai","jest","@jest/globals","assert","node:assert","node:assert/strict","assert/strict","uvu/assert","expect","chai-as-promised"]),aw=new Set(["expect","assert","expectTypeOf","assertType","should"]),qZ=new Set(["vitest","jest","@jest/globals","chai","chai-as-promised"]);function zZ(e){let t=new Set(["expect","assert"]),n=dt.createSourceFile("assertion-vocabulary.ts",e,dt.ScriptTarget.Latest,!0);for(let r of n.statements){if(!dt.isImportDeclaration(r)||!dt.isStringLiteral(r.moduleSpecifier))continue;let i=r.moduleSpecifier.text,o=r.importClause;if(!(!UZ.has(i)||!o||o.isTypeOnly))for(let s of GZ(o,qZ.has(i)))t.add(s)}return t}function GZ(e,t){let n=[],r=o=>{if(t)for(let s of aw)n.push(`${o}.${s}`);else n.push(o)};e.name&&r(e.name.text);let i=e.namedBindings;if(!i)return n;if(dt.isNamespaceImport(i))return r(i.name.text),n;for(let o of i.elements){if(o.isTypeOnly)continue;let s=(o.propertyName??o.name).text;t&&!aw.has(s)||["AssertionError","CallTracker"].includes(s)||n.push(o.name.text)}return n}function lw(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(`(?<![\\w$.])${r}\\s*(?:<[^<>]*>)?\\s*[.(]`).test(e))return!0}return!1}var KZ=/\bfunction\s+(\w+)\s*\(/g,WZ=/\b(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/g,VZ=60;function JZ(e,t){let n=new Set;for(let r of[KZ,WZ]){r.lastIndex=0;let i;for(;i=r.exec(e);){let o=i[1],s=i.index+i[0].length-1,a=Pl(e,s),c=e.indexOf("{",a+1);if(c===-1||c-a>VZ)continue;let l=YZ(e,c),u=e.slice(c+1,l);lw(u,t)&&n.add(o)}}return n}function YZ(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 XZ=/\bmock(?:ReturnValue|ResolvedValue)(?:Once)?\s*\(/g,$p=/\bexpect\s*\(/g,QZ=/^\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(/,uw=/^(?:-?\d+(?:\.\d+)?|(['"`]).+\1)$/;function ZZ(e,t){let n=e8(e,t,XZ);if(n.length===0)return null;let r=t8(e,t);for(let i of r)if(n.includes(i))return i;return null}function e8(e,t,n){let r=[];n.lastIndex=0;let i;for(;i=n.exec(e);){let o=i.index+i[0].length-1,s=Pl(e,o),a=t.slice(o+1,s).trim();uw.test(a)&&r.push(a),n.lastIndex=s+1}return r}function t8(e,t){let n=[];$p.lastIndex=0;let r;for(;r=$p.exec(e);){let i=r.index+r[0].length-1,o=Pl(e,i),s=e.slice(o+1),a=QZ.exec(s);if($p.lastIndex=o+1,!a)continue;let c=o+1+a[0].length-1,l=Pl(e,c),u=t.slice(c+1,l).trim();uw.test(u)&&n.push(u)}return n}function n8(e,t,n,r){let i=H(e,t),o=cw(i,n.argsStart),s=ws(i,n.callStart),a=r8(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 r8(e,t,n){let r=n+1;try{let i=et(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 i8=.7,dw=.62,mw=.45;function o8(e,t={}){let{windowCommits:n=100,limit:r=30,scope:i,scanLimit:o}=t,s=kt(e,{historyMode:t.historyMode}).fileAddRecords();if(!s)return{available:!1,windowCommits:n,findings:[]};if(r<=0)return{available:!0,windowCommits:n,findings:[]};let a=f8(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let l=s8(e,{limit:r,minSimilarity:t.minSimilarity,scanLimit:o,scope:i,semantic:t.semantic,focusFiles:a}).map(d=>g8(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(h8);return{available:!0,windowCommits:n,findings:u,rootCauseGroups:y8(u)}}function s8(e,t){let n=S8(t.limit),r=[...a8(e,{scope:t.scope,minSimilarity:t.minSimilarity??i8,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],i=Qs(e,{scope:t.scope});return i.react&&r.push(...c8(e,{scope:t.scope,minSimilarity:t.minSimilarity??dw,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...l8(e,{scope:t.scope,minSimilarity:t.minSimilarity??mw,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i.vue&&r.push(...m8(e,{scope:t.scope,minSimilarity:t.minSimilarity??dw,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...p8(e,{scope:t.scope,minSimilarity:t.minSimilarity??mw,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r}function a8(e,t){return vs(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles}).filter(n=>!ke(n.symbolA)&&!ke(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 c8(e,t){return Ll(e,t,{query:op,domain:"react-component",basis:"jsx-structure",symbolA:n=>n.componentA,symbolB:n=>n.componentB,evidenceBuckets:n=>[["component",n.sharedComponents],["tag",n.sharedNativeTags],["prop",n.sharedProps],["event",n.sharedEvents],["binding",n.sharedBindings]]})}function Ll(e,t,n){return n.query(e,t).filter(r=>r.fileA!==r.fileB).filter(r=>n.acceptPair?.(r)??!0).map(r=>({domain:n.domain,basis:n.basis,symbolA:n.symbolA(r),fileA:r.fileA,symbolB:n.symbolB(r),fileB:r.fileB,similarity:r.similarity,sharedEvidence:v8(...n.evidenceBuckets(r)),sharedCallees:[]}))}function l8(e,t){return Ll(e,t,{query:ap,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,acceptPair:d8,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 u8=new Set(["useCallback","useEffect","useLayoutEffect","useMemo","useMutation","useQueries","useQuery","useQueryClient","useReducer","useRef","useState"]);function d8(e){return e.sharedHooks.some(t=>!u8.has(t))||e.sharedState.length>0||e.sharedHandlers.length>0||e.sharedHandlerVerbs.length>=2}function m8(e,t){return Ll(e,t,{query:Cs,domain:"vue-component",basis:"vue-template",symbolA:n=>Tl(n.fileA),symbolB:n=>Tl(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function p8(e,t){return Ll(e,t,{query:xs,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>Tl(n.fileA),symbolB:n=>Tl(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 f8(e,t){let n=new Set;for(let[r,i]of e)i.commitsAgo<=t&&n.add(r);return n}function pw(e,t){return e.get(t)?.commitsAgo??null}function fw(e,t){return e!==null&&e<=t}function g8(e,t,n){let r=pw(t,e.fileA),i=pw(t,e.fileB),o=fw(r,n),s=fw(i,n);if(!o&&!s)return null;let a=o&&s,c=a?(r??0)<=(i??0):o,l={symbol:e.symbolA,file:e.fileA,age:r},u={symbol:e.symbolB,file:e.fileB,age:i},[d,m]=c?[l,u]:[u,l];return{kind:a?"twin":"echo",domain:e.domain,basis:e.basis,echoSymbol:d.symbol,echoFile:d.file,echoAgeCommits:d.age??0,establishedSymbol:m.symbol,establishedFile:m.file,establishedAgeCommits:m.age,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}function h8(e){let t=gw(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function gw(e){if(e.kind==="echo")return["echo",e.domain,e.basis,e.establishedFile,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 y8(e){let t=new Map;for(let[n,r]of e.entries()){let i=r.rootCauseKey??gw(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:b8(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 b8(e){return e.kind==="echo"?"Review the established side once; confirm behavior, contracts, and ownership before consolidating these candidates.":"Compare these recently added files; confirm shared behavior and ownership before considering consolidation."}function S8(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function v8(...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 Tl(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var C8=X("suppression-inventory",{clearGroups:["whole-project","source-file"]});function Ml(e){let t=C8.get(e,()=>x8(e)),n={total:t.total,byCategory:{...t.byCategory},byFile:new Map(t.byFile)},r=Date.now();for(let i of e.config.suppressions??[])i.expiresAt&&Date.parse(i.expiresAt)<=r||(n.total+=1,i.file&&n.byFile.set(i.file,(n.byFile.get(i.file)??0)+1),n.byCategory[hw(i.check)]+=1);return n}function x8(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 Kr(e)){let o=H(e,i);!o||!o.includes("scip-query")||(r+=R8(o,i,t,n))}return{total:r,byCategory:t,byFile:n}}function R8(e,t,n,r){let i=0;for(let o of e.split(/\r?\n/)){let s=zr(o);if(s===null)continue;i+=1,r.set(t,(r.get(t)??0)+1);let a=hw(s);n[a]+=1}return i}var E8=["dead","stale","wrapper","passthrough","drift","extract","similar","twin"],I8=new Map([["dead-code","dead"],["new-dead","dead"],["twin-drift","twin"],["similar-files","similar"],["similar-signatures","similar"],["recent-duplicates","similar"],["duplicate-bodies","similar"],["duplication","similar"],["passthrough-candidates","passthrough"],["slice-cohesion","extract"]]);function hw(e){let t=e?.toLowerCase()??"";return E8.find(n=>n===t)??I8.get(t)??"uncategorized"}function jp(e,t,n={}){let r=J(e,t);if(r.candidates.length>0)throw new Error(`Ambiguous symbol: ${t}. Use an exact SCIP symbol or file:line.`);let i=r.match;if(!i)return null;let o=w8(e,i),s=i.endLine-i.startLine+1,a=new N(e).callableCallees(i,n),c=a.filter(d=>d.evidenceStrength==="exact"),l=new Set(c.map(d=>d.symbol)),u=new Set(a.filter(d=>!l.has(d.symbol)).map(d=>d.symbol));return{symbol:i.symbol,shortName:L(i.symbol),relativePath:i.relativePath,startLine:i.startLine,endLine:i.endLine,loc:s,branches:o.branches,estimateBasis:o.estimateBasis,metricRules:o.metricRules??`${o.estimateBasis}-estimate-v1`,cyclomaticEstimate:o.branches+1,calleeCount:l.size,candidateCalleeCount:u.size,fanIn:el(e,i.symbolId),fanOut:M8(c,i.relativePath)}}function w8(e,t){yw(e,t.relativePath,t.startLine,t.endLine);let n=T8(t,P8(e,t.relativePath));if(n)return n;let r=_(e,t.relativePath);if(r){let i=Gr(r.rootNode,t.startLine,t.endLine);if(i)return{branches:D8(i),estimateBasis:"ast"}}return{branches:F8(yw(e,t.relativePath,t.startLine,t.endLine),L8(e,t.relativePath)),estimateBasis:"regex-fallback"}}function P8(e,t){if(!/\.[cm]?[jt]sx?$/i.test(t))return[];try{return ot(t,te(e.config.projectRoot,t)).functions}catch(n){if(!xe(n))throw n;return[]}}function T8(e,t){let n=A(e.symbol),r=t.filter(i=>i.startLine-1>=e.startLine&&i.endLine-1<=e.endLine&&i.name.split(".").at(-1)?.replace(/^(get|set) /,"")===n);if(r.length===1)return{branches:r[0].cyclomatic-1,estimateBasis:"ast",metricRules:fa}}function L8(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function yw(e,t,n,r){let i=te(e.config.projectRoot,t,{inputKind:"indexed source file"}).split(`
|
|
313
|
+
`),o=i.slice(n,r+1).join(`
|
|
314
|
+
`);if(n<0||r<n||r>=i.length||!o.trim())throw new Error(`Current source does not cover the indexed definition in ${t}. Reindex before measuring complexity.`);return o}function M8(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function D8(e){let t=0;return ig(e,n=>{t+=og(n)}),t}function F8(e,t){let n=tr(e),r=0;return r+=Ps(n,[/\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]),t==="python"?r+=Ps(n,[/\belif\b/g,/\bexcept\b/g,/\bfinally\b/g]):t==="rust"?r+=Ps(n,[/\bmatch\b/g,/=>/g,/\bloop\b/g]):t==="ruby"?r+=Ps(n,[/\belsif\b/g,/\bunless\b/g,/\brescue\b/g,/\bwhen\b/g]):t==="go"&&(r+=Ps(n,[/\bselect\b/g,/\bdefer\b/g])),r}function Ps(e,t){let n=0;for(let r of t){let i=e.match(r);i&&(n+=i.length)}return n}function bw(e){let t=new Set(e.filter(n=>n.definition?.isFunctionLike).map(n=>`${n.role}:${n.definition.relativePath}`));return e.flatMap(n=>n.definition?!n.definition.isFunctionLike&&t.has(`${n.role}:${n.definition.relativePath}`)?[]:[{definition:n.definition,role:n.role}]:[])}var Cw=6,Fl=10,Up=3,qp=8,k8=.7,xw=24,Hp=200,Rw=12,Ew=80,Iw=600;function N8(e,t,n={}){let r=n.impactDepth??3,i=n.semantic,o=e9(t)?j8(e,t):null,s=o?o.primary?.symbol??null:t,{traceResult:a,callGraphResult:c,complexityResult:l,affectedResults:u,reuseCandidates:d,targetSymbol:m,affectedConsumerReuse:p}=B8(e,s,n,r),f=Ve("change-surface",t,()=>bp(e,t,{semantic:i}),b=>({symbols:b?.symbols.length??0,externalConsumers:b?.totalExternalConsumers??0})),g=Ve("system",t,()=>Nm(e,t),b=>({files:b.files.length,symbols:b.symbols.length})),{depsResults:h,rdepsResults:y}=A8(e,t,g),S=Ve("surface",t,()=>Am(e,t),b=>({consumers:b.length})),I=_8(a,c,l,u,f,h,y,g,S),x=O8(o,a,I),E=f?.file??a.definitions[0]?.relativePath??null;return{target:t,...o?.primary?{primaryCallable:{symbol:o.primary.symbol,shortName:A(o.primary.symbol),file:o.primary.relativePath}}:{},matched:I,history:Ve("history",E??t,()=>Z8(e,E,n.gitHead)),trace:$8(a),callGraph:c,complexity:l,affected:u,changeSurface:f,deps:h,rdeps:y,system:g,surface:S,reuseCandidates:d,affectedConsumerReuse:p,sourcePacket:H8(e,m,a,p,d),warnings:x}}function A8(e,t,n){let r=n.files.length===1,i=Ve("deps",t,()=>r?n.dependsOn.map(s=>({relativePath:s,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):Yo(e,t),s=>({files:s.length,reusedSystem:r})),o=Ve("rdeps",t,()=>r?n.dependedOnBy.map(s=>({relativePath:s,edgeBasis:"symbol-references",evidence:"cross-file SCIP references plus resolved source imports"})):Xo(e,t),s=>({files:s.length,reusedSystem:r}));return{depsResults:i,rdepsResults:o}}function _8(e,t,n,r,i,o,s,a,c){return{symbol:e.definitions.length>0||e.referencedBy.length>0||t!==null||n!==null||r.length>0,file:i!==null||o.length>0||s.length>0,module:a.files.length>0||a.symbols.length>0||c.length>0}}function O8(e,t,n){let r=[];e&&!e.primary&&e.callableCount>1&&r.push(`File target has ${e.callableCount} callable symbols; use one callable name for compiler-resolved relationships.`);let i=[...new Set(t.referencedBy.map(o=>o.relativePath))];return i.length>0&&i.every(o=>F(o)==="test")&&r.push("Only test references were found for this target. For replacement or retirement work, map the currently wired owner or one production entry point before planning; this target does not describe the live affected surface."),!n.symbol&&!n.file&&!n.module&&r.push("No symbol, file, or module matched target."),r}function B8(e,t,n,r){let i=n.semantic,o=t?Ve("trace",t,()=>pv(e,t,{semantic:i,referenceContext:Rw}),m=>({definitions:m.definitions.length,references:m.referencedBy.length})):{definitions:[],referencedBy:[],claimSupport:null},s=t?Ve("call-graph",t,()=>Jo(e,t,{semantic:i}),m=>({callers:m?.callers.length??0,callees:m?.callees.length??0})):null,a=t?Ve("complexity",t,()=>jp(e,t,{semantic:i}),m=>({callees:m?.calleeCount??0})):null,c=t?Ve("affected",t,()=>yp(e,t,{maxDepth:r,scope:n.scope}),m=>({maxDepth:r,affectedSymbols:m.length})):[],l=t?Ve("reuse-candidates",t,()=>Ss(e,t,{minSimilarity:.4,limit:5,semantic:i,sourceCandidateMode:"target-pruned"}),m=>({candidates:m.length,direct:m.filter(p=>p.actionTier==="direct").length})):[],u=t?Bt(e,t)?.symbol??null:null,d=t?Ve("affected-consumer-reuse",t,()=>W8(o,u,m=>Ss(e,m,{minSimilarity:.4,limit:Fl,semantic:i,sourceCandidateMode:"target-pruned"}),{consumerLimit:Cw,perConsumerSearchLimit:Fl,perConsumerCandidateLimit:Up,candidateLimit:qp}),m=>({totalConsumers:m.coverage.totalConsumers,analyzedConsumers:m.coverage.analyzedConsumers,candidates:m.candidates.length})):Q8();return{traceResult:o,callGraphResult:s,complexityResult:a,affectedResults:c,reuseCandidates:l,targetSymbol:u,affectedConsumerReuse:d}}function $8(e){return{definitions:e.definitions,referencedBy:e.referencedBy.map(t=>({relativePath:t.relativePath,line:t.line,enclosingSymbol:t.enclosingSymbol,enclosingShort:t.enclosingShort}))}}function j8(e,t){let n=ar(e,t);if(n.length!==1)return{primary:null,callableCount:0};let r=D(e,n[0]).filter(s=>s.isFunctionLike),i=r.filter(s=>s.enclosingSymbol===null),o=i.length>0?i:r;return{primary:o.length===1?o[0]:null,callableCount:o.length}}function H8(e,t,n,r,i){let o=[...t?[{definition:Sw(e,t),role:"target"}]:[],...[...r.candidates.map(u=>u.candidate),...i].map(u=>({definition:Sw(e,u.symbolB),role:"reuse-candidate"}))],s=U8(e,o),a=G8(n),c=[...[...s.values()].filter(u=>u.role==="target"),...a.values(),...[...s.values()].filter(u=>u.role==="reuse-candidate")],l=K8(c);return{slices:l,candidateSlices:c.length,omittedSlices:Math.max(0,c.length-l.length),maxSlices:xw,maxLinesPerSlice:Hp,maxTotalLines:Iw,targetLineLimit:Hp,consumerContextLines:Rw,reuseLineLimit:Ew}}function U8(e,t){let n=new Map;for(let r of bw(t)){if(n.has(r.definition.symbol))continue;let i=q8(e,r);i&&n.set(r.definition.symbol,i)}return n}function q8(e,t){let n=t.role==="target"?Hp:Ew,r=t.definition.endLine<=t.definition.startLine?Ln(e,t.definition.relativePath,t.definition.startLine,n):null,i=r?.unitType?r.source:tt(e,t.definition);if(!i)return null;let o=i.split(`
|
|
315
|
+
`),s=Math.min(o.length,n),a=r?.unitType?r.startLine:t.definition.startLine;return{role:t.role,symbol:t.definition.symbol,shortName:A(t.definition.symbol),file:t.definition.relativePath,startLine:a,endLine:a+s-1,source:o.slice(0,s).join(`
|
|
316
|
+
`),omittedLines:(r?.unitType?r.omittedLines:0)+Math.max(0,o.length-s)}}function z8(e){return e.source!==void 0&&e.source!==null&&e.sourceStartLine!==void 0&&e.sourceStartLine!==null&&e.sourceEndLine!==void 0&&e.sourceEndLine!==null}function G8(e){let t=new Map;for(let n of e.referencedBy){if(!z8(n))continue;let r=`${n.relativePath}:${n.sourceStartLine}-${n.sourceEndLine}`,i=t.get(r);if(i){i.focusLines=[...new Set([...i.focusLines??[],n.line])].sort((o,s)=>o-s);continue}t.set(r,{role:"consumer",symbol:n.enclosingSymbol??`${n.relativePath}:${n.line}`,shortName:n.enclosingShort,file:n.relativePath,startLine:n.sourceStartLine,endLine:n.sourceEndLine,source:n.source,omittedLines:0,focusLines:[n.line]})}return t}function K8(e){let t=[],n=Iw;for(let r of e){if(t.length>=xw||n<=0)break;let i=r.source.split(`
|
|
317
|
+
`),o=Math.min(i.length,n);t.push({...r,endLine:r.startLine+o-1,source:i.slice(0,o).join(`
|
|
318
|
+
`),omittedLines:r.omittedLines+Math.max(0,i.length-o),...r.focusLines?{focusLines:r.focusLines.filter(s=>s<=r.startLine+o-1)}:{}}),n-=o}return t}function Sw(e,t){let n=la(e,t);return n?D(e,n.relativePath).find(r=>r.symbol===t)??null:null}function W8(e,t,n,r={}){let i=Dl(r.consumerLimit,Cw),o=Dl(r.perConsumerSearchLimit,Fl),s=Dl(r.perConsumerCandidateLimit,Up),a=Dl(r.candidateLimit,qp),c=J8(e),l=c.slice(0,i),u=new Set(c.map(p=>p.symbol));t&&u.add(t);let d=new Map;for(let p of l)V8(p,n,u,d,o,s);let m=[...d.values()].filter(p=>p.candidate.actionTier==="direct"||p.candidate.similarity>=k8||p.consumers.length>1).sort(X8).slice(0,a);return{candidates:m,coverage:{totalConsumers:c.length,analyzedConsumers:l.length,omittedConsumers:Math.max(0,c.length-l.length),perConsumerSearchLimit:o,perConsumerCandidateLimit:s,candidateLimit:a,returnedCandidates:m.length}}}function V8(e,t,n,r,i,o){let s=t(e.symbol).slice(0,i),a=0;for(let c of s){let l=Y8(c,e.symbol);if(!l||n.has(l.symbolB))continue;let u=r.get(l.symbolB);if(u?(u.consumers.some(d=>d.symbol===e.symbol)||u.consumers.push(e),l.similarity>u.candidate.similarity&&(u.candidate=l)):r.set(l.symbolB,{candidate:l,consumers:[e]}),a+=1,a>=o)break}}function J8(e){let t=new Map;for(let n of e.referencedBy){if(!n.enclosingSymbol)continue;let r=t.get(n.enclosingSymbol);if(r){r.referenceCount+=1;continue}t.set(n.enclosingSymbol,{symbol:n.enclosingSymbol,shortName:A(n.enclosingSymbol)||n.enclosingShort,file:n.relativePath,referenceCount:1})}return[...t.values()].sort((n,r)=>r.referenceCount-n.referenceCount||n.symbol.localeCompare(r.symbol))}function Y8(e,t){return e.symbolA===t?e:e.symbolB!==t?null:{...e,symbolA:e.symbolB,shortNameA:e.shortNameB,fileA:e.fileB,symbolB:e.symbolA,shortNameB:e.shortNameA,fileB:e.fileA,uniqueToA:e.uniqueToB,uniqueToB:e.uniqueToA}}function X8(e,t){let n=vw(t.candidate.actionTier)-vw(e.candidate.actionTier);if(n!==0)return n;let r=t.consumers.length-e.consumers.length;if(r!==0)return r;let i=t.candidate.similarity-e.candidate.similarity;return i!==0?i:e.candidate.symbolB.localeCompare(t.candidate.symbolB)}function vw(e){return e==="direct"?1:0}function Dl(e,t){return typeof e=="number"&&Number.isFinite(e)?Math.max(1,Math.floor(e)):t}function Q8(){return{candidates:[],coverage:{totalConsumers:0,analyzedConsumers:0,omittedConsumers:0,perConsumerSearchLimit:Fl,perConsumerCandidateLimit:Up,candidateLimit:qp,returnedCandidates:0}}}function Ve(e,t,n,r=()=>({})){let i;return M(`context.${e}`,()=>(i=n(),i),()=>({target:t,...r(i)}))}function Z8(e,t,n){let r={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return r;let i=kt(e,n?{head:n}:{}),o=Ve("history.churn",t,()=>i.fileChurn(),c=>({files:c?.size??0}));if(!o)return r;let s=Ve("history.co-change",t,()=>Rs(e,t,{limit:5,...n?{head:n}:{}}),c=>({commits:c.commitsAnalyzed,partners:c.findings.length})),a=Ve("history.suppressions",t,()=>Ml(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 e9(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}var mt={dead:{minLoc:1,skipBarrels:!1,deadCodeOnly:!1},similar:{minSimilarity:.6,limit:50,minCallees:4},duplicateBodies:{maxLoc:15,limit:50},passthroughs:{maxLoc:15,limit:50},drift:{},twinDrift:{minSimilarity:.3}};import{existsSync as t9}from"fs";import{isAbsolute as n9,join as r9}from"path";var i9=".scipquery-baseline.json";function zp(e){if(e.startsWith("similar:")){let t=e.slice(8).split("|");return t.length!==2?e:`similar:${t.map(L).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(L).sort().join("|")}`}return e}function Gp(e,t){return t&&n9(t)?t:r9(e.config.projectRoot,t??i9)}function ww(e,t,n={}){let r=Gp(e,n.path);if(!t9(r))throw new Error(`No baseline found at ${r}. Create one with: scip-query health --write-baseline`);let o=(JSON.parse(Ye(r,"health baseline")).findings??[]).map(zp),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 Ts from"path";function Ms(e,t){let{scope:n,minDeviation:r=5,limit:i=50}=t??{},o=t?.semantic!==!1,s=t?.includePatternDeviations===!0,c=new N(e).fileDependencyGraph(n),l=hs(e,{scope:n}),u=u9([...o9(e,c,{scope:n,semantic:o}),...a9(l.forbiddenEdges),...s?c9(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 o9(e,t,n){let r=p9(e,n.scope),i=[],o=new Set;E9(e,t,n,r,i,o),o.size>0&&h9(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:"Review unused bindings; preserve module-initialization side effects and verify the change with project checks."});return s}function s9(e,t,n,r){return S9(e,t,n)||v9(e,t,n)||y9(n)||x9(e,t,n)||C9(n)?!0:r.semantic&&b9(e,t,n)}function a9(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 c9(e,t){let n=[];for(let[r,i]of d9(e)){let o=i.filter(a=>!Ls(a));if(o.length<t)continue;let s=m9(e,o);l9(e,r,o,s,n)}return n}function l9(e,t,n,r,i){for(let o of n)for(let s of e.get(o)??[])Ls(s)||(r.get(s)??0)===1&&Ts.dirname(s)!==t&&Ts.dirname(s)!==Ts.dirname(t)&&i.push({file:o,kind:"pattern-deviation",description:`Only file in ${t}/ that depends on ${s}`,dep:s,actionTier:"signal",evidenceReasons:[`${n.length} sibling file(s) in ${t}/ were compared`,`${o} is the only non-skipped sibling depending on ${s}`],recommendation:"Review sibling ownership before changing this import; unique dependency shape can be intentional specialization."})}function u9(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 d9(e){let t=new Map;for(let n of e.keys()){let r=Ts.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function m9(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])Ls(i)||n.set(i,(n.get(i)??0)+1);return n}function p9(e,t){let n=new Map;return f9(e,n,t),n}function f9(e,t,n){for(let r of g9(e,n))Pw(e,t,r.from_file,r.to_file)}function g9(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
|
|
319
|
+
FROM mentions m
|
|
320
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
321
|
+
JOIN documents d1 ON c.document_id = d1.id
|
|
322
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
323
|
+
JOIN (
|
|
324
|
+
SELECT m2.symbol_id, c2.document_id
|
|
325
|
+
FROM mentions m2
|
|
326
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
327
|
+
WHERE m2.role = 1
|
|
328
|
+
GROUP BY m2.symbol_id
|
|
329
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
330
|
+
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
331
|
+
WHERE d1.id != d2.id
|
|
332
|
+
AND m.role = 0
|
|
333
|
+
${e.pathExclusionsFor("d1","d2")}
|
|
334
|
+
${n}`,...r)}function h9(e,t,n={}){new N(e).scanSourceReferences({paths:n.paths??q(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},i=>{i.target.relativePath!==i.sourceFile&&(i.occurrences<=1&&V(e,i.sourceFile).some(o=>o.sourcePath===i.target.relativePath&&!o.used&&(o.localName===i.name||o.importedName===i.name))||e.isIgnored(i.target.relativePath)||Pw(e,t,i.sourceFile,i.target.relativePath))})}function Pw(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 y9(e){return e.includes("types")||e.endsWith(".d.ts")}function b9(e,t,n){return Ho(e,t).filter(i=>i.sourcePath===n).some(i=>i.isUsed)}function S9(e,t,n){return V(e,t).filter(i=>i.sourcePath===n).some(i=>i.used)}function v9(e,t,n){let r=V(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function C9(e){return e.endsWith(".vue")}function x9(e,t,n){let r=V(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 Ls(e){let t=F(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||R9(Ts.basename(e)))}function R9(e){return!!(e==="index.ts"||e==="index.js"||e==="cli.ts"||e==="main.ts"||e==="main.rs"||e.includes("worker.")||e.includes("postinstall.")||e==="health.ts"||e==="health.js")}function E9(e,t,n,r,i,o){for(let[s,a]of t){if(Ls(s))continue;let c=r.get(s)??new Set;for(let l of a)Ls(l)||c.has(l)||s9(e,s,l,n)||(i.push({file:s,dep:l}),o.add(s))}}function Kp(e,t={}){let{scope:n}=t,r=[];T9(e,n,r);for(let i of gs(e,{scope:n,edgeBasis:"imports"}))r.push(`cycle:${I9(i.path)}`);for(let i of vs(e,{scope:n,...mt.similar,limit:Number.POSITIVE_INFINITY}))r.push(`similar:${[i.symbolA,i.symbolB].sort().join("|")}`);for(let i of Xm(e,{scope:n,...mt.duplicateBodies,limit:Number.POSITIVE_INFINITY}))r.push(`duplicate-bodies:${i.hash}:${i.functions.map(o=>o.symbol).sort().join("|")}`);for(let i of Is(e,{scope:n,...mt.passthroughs,limit:Number.POSITIVE_INFINITY}))r.push(`passthrough:${i.file}:${i.shortName}`);for(let i of Ms(e,{scope:n,...mt.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY}).results)i.kind!=="architecture-violation"&&r.push(`drift:${i.kind}:${i.file}:${i.dep}`);return r.push(...zm(hs(e,{scope:n}))),[...new Set(r.map(zp))].sort()}function I9(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 w9(e,t={}){let n=Kp(e,{scope:t.scope}),r=Gp(e,t.path);return jg(r,{version:1,findings:n},{spacing:2,trailingNewline:!0}),{path:r,findingCount:n.length}}function P9(e,t={}){return ww(e,Kp(e,{scope:t.scope}),{path:t.path})}function T9(e,t,n){let r=Pr(e,{scope:t,...mt.dead});for(let i of r.symbols)Ke(e,i.relativePath)||We(e,i.symbol,i.relativePath)||i.kind==="dead-code"&&n.push(`dead:${i.relativePath}:${i.shortName}`)}import{ts as Ki}from"@ts-morph/common";function L9(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new N(e),s=new Map;return Gi({candidates:()=>o.productionCallableDefinitions({scope:n,files:t.files,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}),filterCandidate:a=>M9(a.relativePath),scanLimit:i,profile:{name:"unused-params"},evaluate:a=>{let c=s.get(a.relativePath);if(c||(c=ot(a.relativePath,te(e.config.projectRoot,a.relativePath)),s.set(a.relativePath,c)),c.errors.length>0)return null;let l=[],u=p=>{if(Ki.isFunctionLike(p)&&"body"in p&&p.body&&c.sourceFile.getLineAndCharacterOfPosition(p.getStart(c.sourceFile)).line>=a.startLine&&c.sourceFile.getLineAndCharacterOfPosition(p.end).line<=a.endLine){l.push(p);return}Ki.forEachChild(p,u)};if(u(c.sourceFile),l.length!==1)return null;let d=l[0],m=D9(d,c.checker);return m.length===0?null:{symbol:a.symbol,shortName:L(a.symbol),file:a.relativePath,startLine:a.startLine,endLine:a.endLine,paramCount:d.parameters.length,unusedTrailing:m}},orderResults:(a,c)=>c.unusedTrailing.length-a.unusedTrailing.length||a.file.localeCompare(c.file)||a.startLine-c.startLine,limit:r})}function M9(e){let t=se(e);return t==="typescript"||t==="tsx"||t==="javascript"}function D9(e,t){if(!e.body||e.parameters.some(s=>!Ki.isIdentifier(s.name)||s.initializer||s.dotDotDotToken||s.modifiers?.length))return[];let n=new Set,r=!1,i=s=>{if(Ki.isIdentifier(s)){(s.text==="arguments"||s.text==="eval")&&(r=!0);let a=Ki.isShorthandPropertyAssignment(s.parent)?t.getShorthandAssignmentValueSymbol(s.parent):t.getSymbolAtLocation(s);a&&n.add(a)}Ki.forEachChild(s,i)};if(i(e.body),r)return[];let o=[];for(let s of[...e.parameters].reverse()){let a=s.name.text,c=t.getSymbolAtLocation(s.name);if(a.startsWith("_")||!c||n.has(c))break;o.unshift(a)}return o}var F9=10,k9=4,N9=3,Vp=5,A9=.5,Tw=80,_9=3,Ji=new Set(["statement","predicate","return","throw"]),ks=/^use[A-Z0-9_]/u,O9=/^use(?:[A-Z0-9_]\w*)?Effect$/u,B9=/(?:^|\/)(?:scripts?|bin|tools?|tooling|migrations?|integration-tests?|e2e)\//u,Bw=new Set(["get","has","at","find","findLast","findIndex","findLastIndex","includes","indexOf","lastIndexOf","keys","values","entries","forEach","map","filter","flatMap","reduce","reduceRight","some","every","slice","concat","join","toString","toJSON","toSorted","toReversed","toSpliced","with","startsWith","endsWith","match","matchAll","test","exec","search","localeCompare","trim","trimStart","trimEnd","split","replace","replaceAll","toLowerCase","toUpperCase","padStart","padEnd","charAt","charCodeAt","codePointAt","substring","repeat","normalize","isArray","from","of","assign","freeze","hasOwn","getOwnPropertyNames","stringify","parse","toFixed","toISOString","getTime","valueOf","then","catch","finally","size","length"]),Lw=new Set(["map","filter","flatMap","slice","concat","keys","values","entries","from","of","toSorted","toReversed","toSpliced","with","join","reduce","reduceRight","some","every","includes","has","indexOf","lastIndexOf","findIndex","size","length","toString","toJSON","then","catch","finally","trim","split","replace","replaceAll","toLowerCase","toUpperCase","startsWith","endsWith","match","test","exec","localeCompare","padStart","padEnd","charAt","charCodeAt","codePointAt","substring","repeat","normalize"]);function $9(e,t={}){let{scope:n,symbol:r,minLoc:i=12,minStatements:o,minClusterUnits:s,limit:a=20,scanLimit:c,onProgress:l}=t,u={files:new Map},d={minStatements:o,minClusterUnits:s,detail:t.detail??r!==void 0};if(r){let p=H9(e,r);if(!p)return[];let f=Jp(e,p,d,u);return f?[f]:[]}let m=new N(e);return Gi({candidates:()=>m.productionCallableDefinitions({scope:n,minLoc:i,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:c,orderScanned:(p,f)=>p.relativePath.localeCompare(f.relativePath)||p.startLine-f.startLine,filterCandidate:p=>xt(p.relativePath)&&!_e(e,p.relativePath,p.startLine,"extract"),profile:{name:"slice-cohesion"},onProgress:l,onProfile:t.onProfile,evaluate:p=>{let f=Jp(e,p,d,u);return f?.splitCandidate?f:null},orderResults:j9,limit:a})}function j9(e,t){return Mw(e.actionTier)-Mw(t.actionTier)||Number(e.operational)-Number(t.operational)||Dw(e.archetype)-Dw(t.archetype)||Fw(e)-Fw(t)||kw(t)-kw(e)||t.separableStatements-e.separableStatements||t.loc-e.loc}function Mw(e){return e==="signal"?0:1}function Dw(e){switch(e){case"calculation":return 0;case"react-hook":return 1;case"react-component":return 2;case"orchestration":return 3}}function Fw(e){let t=new Set(e.clusters.filter(n=>n.role==="extraction").map(n=>n.kind));return t.has("calculation")?0:t.has("operation")||t.has("hook")?1:2}function kw(e){return e.clusters.filter(t=>t.role==="extraction"&&t.narrow).reduce((t,n)=>t+n.units.length,0)}function H9(e,t){let n=J(e,t);if(n.candidates.length>0)throw new Error(`Ambiguous symbol: ${t}. Use an exact SCIP symbol or file:line.`);let r=n.match;if(!r)return null;let i=D(e,r.relativePath);return i.find(o=>o.symbolId===r.symbolId)??i.find(o=>o.symbol===r.symbol)??null}function Jp(e,t,n={},r={files:new Map}){let i={minStatements:n.minStatements??F9,minClusterUnits:n.minClusterUnits??k9},o=n.detail??!0,s=U9(e,t,r);if(!s)return null;let{ts:a,sourceFile:c,callable:l,flow:u}=s,d=V9(a,c,l,t.relativePath),m=f7(d,u,t.relativePath),p=A7(d,m),f=d.units.filter($=>Ji.has($.kind)).map($=>$.index),g=new Set(f),h=q9(d,m,p,g),y=h.filter($=>!$.guard),S=z7(y,f.length),I=new Set(h.flatMap($=>$.units)),{clusters:x,preamble:E}=z9(y,I,d,m,i),b=new Set(x.flatMap($=>$.outputs)),v=y.filter($=>!b.has($.id)).map($=>$.id),C=new Set(h.flatMap($=>$.fullSlice??[])),R=f.filter($=>!C.has($)&&!I.has($)&&d.units[$].kind==="statement"),P=x.filter($=>$.role==="extraction"),w=P.reduce(($,U)=>$+U.units.length,0),T=f.length>=i.minStatements&&P.length>=1,G=[...u.coverage.unsupported],K={status:u.coverage.status==="complete"&&m.candidateEdges===0?"complete":"partial",model:"function-local-flow",basis:"typescript-local-flow-backward-slices",unsupported:G,candidateEdges:m.candidateEdges,candidateEdgeEffect:"merge-only"},ue=Z7(d,y),ce=eee(T,ue,x,K),Ce=h.filter($=>$.guard).length,pe={body:d,flow:m,thresholds:i,archetype:ue,clusters:x,preamble:E,orphans:R,guards:Ce,coverage:K},Je=o?h:h.map(({slice:$,fullSlice:U,...pt})=>pt);return{symbol:t.symbol,shortName:L(t.symbol),relativePath:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:oe(t),archetype:ue,operational:B9.test(t.relativePath),...o?{units:d.units.map(({node:$,start:U,end:pt,...Or})=>Or)}:{},statementCount:f.length,outputs:Je,metrics:S,clusters:x,preambleOnlyOutputs:v,preamble:E,orphans:R,separableStatements:w,splitCandidate:T,actionTier:ce.tier,tierReason:ce.reason,evidenceReasons:tee(f.length,h,S,pe),recommendation:nee(T,y,S,pe),coverage:K}}function U9(e,t,n){if(!xt(t.relativePath))return null;let r=os();if(!r)return null;let i=G9(e,t.relativePath,n);if(!i)return null;let o=K9(r,i,t);if(!o)return null;let s=Er(e,t.relativePath,t.startLine,t.endLine);return!s||s.coverage.status==="unsupported"?null:{ts:r,sourceFile:i,callable:o,flow:s}}function q9(e,t,n,r){let i=l=>{let u=[],d=new Set,m=[...t.controlDeps[l]];for(;m.length>0;){let p=m.pop();d.has(p)||(d.add(p),e.guardPredicates.has(p)?m.push(...t.controlDeps[p]):u.push(p))}return u},o=l=>e.handlerDeps.get(l)??[],s=l=>[...t.dataDeps[l],...i(l),...o(l)],a=l=>[...t.dataDeps[l],...t.controlDeps[l],...o(l)],c=n.map(l=>{let u=U7(l,t),d=[...Nw(u,s)].filter(f=>r.has(f)),m=[...Nw(u,a)].filter(f=>r.has(f)),p=e.guardUnits.has(l.unit)||(l.kind==="throw"||l.kind==="return")&&l.seedPoints===null&&d.every(f=>f===l.unit);return{seed:l,guard:p,slice:new Set(d),fullSlice:new Set(m)}});return q7(c)}function z9(e,t,n,r,i){let o=new Set(G7(e,t,n,r)),s=Ow(e,o,n,r,i);for(;;){let c=new Map;s.forEach((u,d)=>u.outputs.forEach(m=>c.set(m,d)));let l=[...o].filter(u=>{let d=new Set;for(let m of e){let p=c.get(m.id);p!==void 0&&Al(m).includes(u)&&d.add(p)}return d.size<=1});if(l.length===0)break;for(let u of l)o.delete(u);s=Ow(e,o,n,r,i)}let a=[...o].sort(Wi);return{clusters:s,preamble:a}}function Al(e){return e.slice??[]}function Wi(e,t){return e-t}function G9(e,t,n){let r=n.files.get(t);if(r!==void 0)return r;let i=HC(e,t);return n.files.set(t,i),i}function K9(e,t,n){let r=null,i=o=>{if(r)return;let s=t.getLineAndCharacterOfPosition(o.getStart(t)).line,a=t.getLineAndCharacterOfPosition(o.getEnd()).line;if(!(a<n.startLine||s>n.endLine)){if(e.isFunctionLike(o)&&"body"in o&&o.body!==void 0&&s>=n.startLine&&a<=n.endLine){r=o;return}o.forEachChild(i)}};return t.forEachChild(i),r}function W9(e,t){return e.isReturnStatement(t)?"return":e.isThrowStatement(t)?"throw":e.isBreakOrContinueStatement(t)?"jump":e.isFunctionDeclaration(t)||e.isClassDeclaration(t)||e.isInterfaceDeclaration(t)||e.isTypeAliasDeclaration(t)||e.isEnumDeclaration(t)?"declaration":e.isEmptyStatement(t)?null:"statement"}function V9(e,t,n,r){let{units:i,guardPredicates:o,guardUnits:s,enclosingPredicates:a,awaitUnits:c,handlerDeps:l}=J9(e,t,n),{paramNames:u,localNames:d,calleeSpans:m,closureNodes:p,containers:f,aliases:g,stateSetters:h}=Y9(e,t,n),y=[];for(let b=n.parent;b;b=b.parent)e.isFunctionLike(b)&&y.push({start:b.getStart(t),end:b.getEnd()});let S=new Map;for(let b of i){if(!Ji.has(b.kind))continue;let v=t7(e,b.node);v.length>0&&S.set(b.index,v)}let I=n.name&&"text"in n.name?String(n.name.text):"",x=S.size>0&&(/\.[jt]sx$/iu.test(r)||ks.test(I)),E={ts:e,sourceFile:t,callable:n,units:i,paramNames:u,localNames:d,guardPredicates:o,guardUnits:s,enclosingPredicates:a,awaitUnits:c,calleeSpans:m,closures:new Map,containers:f,aliases:g,enclosingRanges:y,handlerDeps:l,stateSetters:h,hookCalls:S,react:x};return E.closures=l7(E,p),E}function J9(e,t,n){let r=[],i=new Set,o=new Set,s=[],a=new Map,c=[],l=n.body,u=(b,v)=>{let C=v.getStart(t),R=v.getEnd();r.push({index:0,kind:b,node:v,start:C,end:R,startLine:t.getLineAndCharacterOfPosition(C).line,endLine:t.getLineAndCharacterOfPosition(R).line,label:c7(t,v)}),a.set(v,[...s])},d=(b,v)=>{s.push(b),v(),s.pop()},m=b=>{u("predicate",b.expression);let v=!b.elseStatement&&o7(e,b.thenStatement,s7(e,b));v&&i.add(b.expression);let C=r.length;d(b.expression,()=>{if(g(b.thenStatement),v)for(let R of r.slice(C))o.add(R.node);b.elseStatement&&g(b.elseStatement)})},p=b=>{let v=r.length;g(b.tryBlock);let C=r.length;b.catchClause&&(b.catchClause.variableDeclaration&&u("statement",b.catchClause.variableDeclaration),g(b.catchClause.block)),b.finallyBlock&&g(b.finallyBlock),c.push({tryNodes:r.slice(v,C).map(R=>R.node),handlerNodes:r.slice(C).map(R=>R.node)})},f=b=>{if(e.isWhileStatement(b)||e.isDoStatement(b))return u("predicate",b.expression),d(b.expression,()=>g(b.statement)),!0;if(e.isForStatement(b)){b.initializer&&u("statement",b.initializer),b.condition&&u("predicate",b.condition);let v=b.condition??b;return d(v,()=>{b.incrementor&&u("statement",b.incrementor),g(b.statement)}),!0}return e.isForInStatement(b)||e.isForOfStatement(b)?(u("predicate",b.expression),d(b.expression,()=>{u("statement",b.initializer),g(b.statement)}),!0):!1},g=b=>{if(e.isBlock(b)){for(let C of b.statements)g(C);return}if(e.isIfStatement(b)){m(b);return}if(f(b))return;if(e.isSwitchStatement(b)){u("predicate",b.expression),d(b.expression,()=>{for(let C of b.caseBlock.clauses)for(let R of C.statements)g(R)});return}if(e.isTryStatement(b)){p(b);return}if(e.isLabeledStatement(b)){g(b.statement);return}let v=W9(e,b);v&&u(v,b)};if(e.isBlock(l))for(let b of l.statements)g(b);else u("return",l);r.sort((b,v)=>b.start-v.start);let h=new Map;r.forEach((b,v)=>{b.index=v,h.set(b.node,v)});let y=new Set(r.filter(b=>i.has(b.node)).map(b=>b.index)),S=new Set(r.filter(b=>o.has(b.node)).map(b=>b.index)),I=r.map(b=>(a.get(b.node)??[]).map(v=>h.get(v)).filter(v=>v!==void 0)),x=new Set(r.filter(b=>Ji.has(b.kind)&&a7(e,b.node)).map(b=>b.index)),E=new Map;for(let b of c){let v=b.tryNodes.map(C=>h.get(C)).filter(C=>Ji.has(r[C].kind));for(let C of b.handlerNodes){let R=h.get(C);E.set(R,[...E.get(R)??[],...v])}}return{units:r,guardPredicates:y,guardUnits:S,enclosingPredicates:I,awaitUnits:x,handlerDeps:E}}function Y9(e,t,n){let r=n.body,i=new Set;for(let x of n.parameters)for(let E of an(x.name))i.add(E);let o=new Set,s=new Set,a=new Map,c=new Set,l=new Map,u=new Map,d=(x,E)=>{if(!E||E===x)return;let b=l.get(x)??new Set;b.add(E),l.set(x,b)},m=(x,E)=>{for(let b of Gn(e,E))for(let v of x)d(v,b)},p=(x,E)=>{let b=Z(e,E);if(kl(e,b)){for(let v of x)c.add(v);return}m(x,b)},f=x=>{let E=an(x.name);for(let R of E)o.add(R);let b=x.initializer?Z(e,x.initializer):null,v=b?Q9(e,b):null;if(v&&e.isIdentifier(x.name)){a.set(x.name.text,v);return}if(x.initializer){p(E,x.initializer);let R=Z9(e,x);R&&u.set(R.setter,R.state);return}let C=r7(e,x);C&&m(E,Z(e,C))},g=x=>{let E=Z(e,x.left),b=Z(e,x.right);e.isIdentifier(E)?p([E.text],x.right):e.isIdentifier(b)&&d(b.text,Fr(e,E))},h=x=>{let E=Z(e,x.expression);if(!e.isPropertyAccessExpression(E)&&!e.isElementAccessExpression(E)||e.isPropertyAccessExpression(E)&&Bw.has(E.name.text))return;let b=Fr(e,E);for(let v of x.arguments){let C=Z(e,v);e.isIdentifier(C)&&d(C.text,b)}},y=x=>{if(e.isParameter(x)&&x.parent!==n)for(let E of an(x.name))o.add(E);else if(e.isFunctionDeclaration(x)||e.isClassDeclaration(x))X9(e,x,o,a);else if(e.isCatchClause(x)&&x.variableDeclaration)for(let E of an(x.variableDeclaration.name))o.add(E)},S=x=>{e.isCallExpression(x)||e.isNewExpression(x)?s.add(`${x.expression.getStart(t)}:${x.expression.getEnd()}`):e.isTaggedTemplateExpression(x)&&s.add(`${x.tag.getStart(t)}:${x.tag.getEnd()}`)},I=x=>{e.isVariableDeclaration(x)?f(x):e.isBinaryExpression(x)&&x.operatorToken.kind===e.SyntaxKind.EqualsToken?g(x):e.isCallExpression(x)?h(x):y(x),S(x),x.forEachChild(I)};return I(r),{paramNames:i,localNames:o,calleeSpans:s,closureNodes:a,containers:c,aliases:l,stateSetters:u}}function X9(e,t,n,r){t.name&&(n.add(t.name.text),e.isFunctionDeclaration(t)&&t.body&&r.set(t.name.text,t))}function Q9(e,t){if(e.isArrowFunction(t)||e.isFunctionExpression(t))return t;if(e.isCallExpression(t)&&Ns(e,Z(e,t.expression))==="useCallback"&&t.arguments.length>0){let r=Z(e,t.arguments[0]);if(e.isArrowFunction(r)||e.isFunctionExpression(r))return r}return null}function Z9(e,t){if(!e.isArrayBindingPattern(t.name)||!t.initializer)return null;let n=Z(e,t.initializer);if(!e.isCallExpression(n))return null;let r=Ns(e,Z(e,n.expression));return!r||!ks.test(r)?null:e7(e,t.name)}function e7(e,t){let[n,r]=t.elements;return!n||!r||e.isOmittedExpression(n)||e.isOmittedExpression(r)||!e.isIdentifier(n.name)||!e.isIdentifier(r.name)?null:{state:n.name.text,setter:r.name.text}}function Ns(e,t){return e.isIdentifier(t)?t.text:e.isPropertyAccessExpression(t)?t.name.text:null}function t7(e,t){let n=[],r=i=>{if(!e.isFunctionLike(i)){if(e.isCallExpression(i)){let o=Ns(e,Z(e,i.expression));o&&ks.test(o)&&n.push(o)}i.forEachChild(r)}};return r(t),n}function kl(e,t){if(e.isArrayLiteralExpression(t)||e.isObjectLiteralExpression(t)||e.isNewExpression(t))return!0;if(e.isBinaryExpression(t)){let n=t.operatorToken.kind;if(n===e.SyntaxKind.QuestionQuestionToken||n===e.SyntaxKind.BarBarToken)return kl(e,Z(e,t.right))}return e.isConditionalExpression(t)?kl(e,Z(e,t.whenTrue))||kl(e,Z(e,t.whenFalse)):!1}function Gn(e,t){let n=Z(e,t);if(e.isIdentifier(n))return[n.text];if(n.kind===e.SyntaxKind.ThisKeyword)return["this"];if(e.isBinaryExpression(n)){let r=n.operatorToken.kind;return r===e.SyntaxKind.QuestionQuestionToken||r===e.SyntaxKind.BarBarToken?[...Gn(e,n.left),...Gn(e,n.right)]:[]}return e.isConditionalExpression(n)?[...Gn(e,n.whenTrue),...Gn(e,n.whenFalse)]:n7(e,n)}function n7(e,t){if(e.isPropertyAccessExpression(t))return Lw.has(t.name.text)?[]:Gn(e,t.expression);if(e.isElementAccessExpression(t))return Gn(e,t.expression);if(e.isCallExpression(t)){let n=Z(e,t.expression);return e.isPropertyAccessExpression(n)?Lw.has(n.name.text)?[]:Gn(e,n.expression):[]}return[]}function r7(e,t){let n=t.parent;if(!n||!e.isVariableDeclarationList(n))return null;let r=n.parent;return r&&(e.isForOfStatement(r)||e.isForInStatement(r))&&r.initializer===n?r.expression:null}function i7(e,t){let n=new Set([t]),r=[t];for(;r.length>0;){let i=r.pop();if(As(e,i))for(let o of e.aliases.get(i)??[])n.has(o)||(n.add(o),r.push(o))}return n}function o7(e,t,n){let r=e.isBlock(t)?t.statements:[t];if(r.length===0)return!1;let i=r[r.length-1];if(!e.isReturnStatement(i)&&!e.isThrowStatement(i))return!1;let o=new Set(n);if(!see(e,r.slice(0,-1),o))return!1;if(!e.isReturnStatement(i)||!i.expression)return!0;let s=!1,a=c=>{s||(e.isIdentifier(c)&&$w(e,c)&&o.has(c.text)?s=!0:c.forEachChild(a))};return a(i.expression),!s}function s7(e,t){let n=new Set;for(let r=t.parent;r&&!e.isFunctionLike(r);r=r.parent){if(!e.isIterationStatement(r,!1))continue;let i=o=>{if(e.isVariableDeclaration(o))for(let s of an(o.name))n.add(s);o.forEachChild(i)};i(r)}return n}function a7(e,t){let n=!1,r=i=>{if(!(n||e.isFunctionLike(i)&&i!==t)){if(e.isAwaitExpression(i)||e.isForOfStatement(i)&&i.awaitModifier!==void 0){n=!0;return}i.forEachChild(r)}};return r(t),n}function c7(e,t){let n=t.getText(e).replace(/\s+/gu," ").trim();return n.length>Tw?`${n.slice(0,Tw-3)}...`:n}function l7(e,t){let n=new Map;for(let[i,o]of t)n.set(i,d7(e,o,t));let r=!0;for(;r;){r=!1;for(let i of n.values())p7(i,n)&&(r=!0)}return n}function u7(e,t){let n=new Set;for(let i of t.parameters)for(let o of an(i.name))n.add(o);let r=i=>{if(e.isVariableDeclaration(i)||e.isParameter(i))for(let o of an(i.name))n.add(o);else(e.isFunctionDeclaration(i)||e.isClassDeclaration(i))&&i.name&&n.add(i.name.text);i.forEachChild(r)};return t.body&&r(t.body),n}function d7(e,t,n){let{ts:r}=e,i=u7(r,t),o={reads:new Set,writes:new Set,stateWrites:new Set,calls:new Set},s=a=>{if(r.isTypeNode(a))return;let c=Yp(e,a);c&&!i.has(c)&&o.writes.add(c),r.isCallExpression(a)&&m7(e,a,i,n,o),r.isIdentifier(a)&&$w(r,a)&&!i.has(a.text)&&o.reads.add(a.text),a.kind===r.SyntaxKind.ThisKeyword&&o.reads.add("this"),a.forEachChild(s)};return t.body&&s(t.body),o}function m7(e,t,n,r,i){let o=Z(e.ts,t.expression);if(!e.ts.isIdentifier(o)||n.has(o.text))return;r.has(o.text)&&i.calls.add(o.text);let s=e.stateSetters.get(o.text);s&&i.stateWrites.add(s)}function p7(e,t){let n=!1;for(let r of e.calls){let i=t.get(r);i&&(Wp(i.reads,e.reads)&&(n=!0),Wp(i.writes,e.writes)&&(n=!0),Wp(i.stateWrites,e.stateWrites)&&(n=!0))}return n}function Wp(e,t){let n=!1;for(let r of e)t.has(r)||(t.add(r),n=!0);return n}function $w(e,t){let n=t.parent;return!(!n||aee(e,t,n)||e.isLabeledStatement(n)||e.isBreakOrContinueStatement(n))}function f7(e,t,n){let r=g7(e,t),{reachedUses:i,...o}=h7(e,t,r),s=S7(e,r,i,o.paramReads,n),a=w7(e);return C7(e.units,r,a,o),{...r,...o,...s,writesByUnit:a.byUnit,stateWritesByUnit:a.stateWritesByUnit}}function g7(e,t){let{units:n}=e,r=e.callable.getStart(e.sourceFile),i=e.callable.getEnd(),o=e.callable.body.getStart(e.sourceFile),s=new Map,a=new Map;for(let c of t.points){if(c.start<r||c.end>i)continue;if(s.set(c.id,c),c.start<o){a.set(c.id,-1);continue}let l=R7(n,c.start);l!==null&&a.set(c.id,l)}return{pointById:s,unitOfPoint:a}}function jw(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function h7(e,t,n){let{units:r}=e,i=r.map(()=>new Set),o=r.map(()=>new Set),s=new Map,a=r.map(()=>new Set),l={dataDeps:i,controlDeps:o,pointDeps:s,paramReads:a,candidateEdges:0,reachedUses:new Set};for(let u of t.edges){let d=y7(n,u);d&&b7(u,d,l)}return e.enclosingPredicates.forEach((u,d)=>{for(let m of u)m!==d&&o[d].add(m)}),l}function y7(e,t){let{pointById:n,unitOfPoint:r}=e,i=n.get(t.fromPointId),o=n.get(t.toPointId);if(!i||!o)return null;let s=r.get(i.id),a=r.get(o.id);return s===void 0||a===void 0||a===-1?null:{from:i,to:o,fromUnit:s,toUnit:a}}function b7(e,t,n){let{from:r,to:i,fromUnit:o,toUnit:s}=t,{reachedUses:a,paramReads:c,controlDeps:l,dataDeps:u,pointDeps:d}=n;if(e.kind!=="control-dependence"&&a.add(i.id),o===-1){e.kind!=="control-dependence"&&c[s].add(_l(r.name));return}o!==s&&(e.strength==="candidate"&&(n.candidateEdges+=1),e.kind==="control-dependence"?l[s].add(o):(u[s].add(o),jw(d,i.id,o)))}function S7(e,t,n,r,i){let{units:o}=e,{pointById:s,unitOfPoint:a}=t,c=o.map(()=>new Set),l=o.map(()=>new Set),u=new Map;for(let d of s.values()){let m=a.get(d.id);if(m===void 0||m===-1)continue;if(d.kind==="definition"){uee(d,m,l,u);continue}if(d.kind!=="use"||n.has(d.id))continue;let p=v7(e,d,i);if(!p)continue;(p.kind==="parameter"?r:c)[m].add(p.name)}return{definitionsByUnitName:u,outerReads:c,definedNames:l}}function v7(e,t,n){if(e.calleeSpans.has(`${t.start}:${t.end}`)||t.name.includes("("))return null;let r=_l(t.name);return e.paramNames.has(r)?{kind:"parameter",name:r}:e.localNames.has(r)?null:r==="this"||I7(t.symbolKey,n,e.enclosingRanges)?{kind:"outer",name:r}:null}function C7(e,t,n,r){let{writes:i,reads:o}=n,{dataDeps:s,pointDeps:a}=r,c=x7(t);for(let l of i){let u=e[l.unit].start;for(let d of c.get(l.base)??[])d.unit===l.unit||d.start<=u||(s[d.unit].add(l.unit),jw(a,d.id,l.unit));dee(e,l,o,u,s)}}function x7(e){let{pointById:t,unitOfPoint:n}=e,r=new Map;for(let i of t.values()){if(i.kind!=="use")continue;let o=n.get(i.id);if(o===void 0||o===-1)continue;let s=_l(i.name),a=r.get(s)??[];a.push({id:i.id,start:i.start,unit:o}),r.set(s,a)}return r}function R7(e,t){let n=0,r=e.length-1,i=-1;for(;n<=r;){let o=n+r>>1;e[o].start<=t?(i=o,n=o+1):r=o-1}return i<0?null:t<e[i].end?i:null}function _l(e){let t=e.search(/[.[?!(]/u);return t<0?e:e.slice(0,t)}function E7(e){if(!e)return null;let t=e.split(":");if(t.length<4)return null;let n=Number(t[2]);if(!Number.isSafeInteger(n))return null;try{return{fileName:decodeURIComponent(t[1]).replace(/\\/gu,"/"),offset:n}}catch{return null}}function Hw(e,t,n,r){let i=E7(e);return i?i.fileName.endsWith(t.replace(/\\/gu,"/"))&&i.offset>=n&&i.offset<r:!1}function I7(e,t,n){return n.some(r=>Hw(e,t,r.start,r.end))}function w7(e){let t=[],n=[],r=new Map,i=new Map,o=(s,a,c)=>{let l=r.get(s);l||(l={local:new Set,external:new Set},r.set(s,l));let u=c?i7(e,a):new Set([a]);for(let d of u)As(e,d)?(l.local.add(d),t.push({unit:s,base:d})):(c||d!==a)&&(l.external.add(d),c&&(d==="this"||e.paramNames.has(d))&&t.push({unit:s,base:d}))};for(let s of e.units)Ji.has(s.kind)&&P7(e,s,o,n,i);return{writes:t,reads:n,byUnit:r,stateWritesByUnit:i}}function P7(e,t,n,r,i){let{ts:o}=e,s=Uw(o,t.node);if(s){let c=Yp(e,s);c&&n(t.index,c,D7(e,s))}for(let c of k7(e,t.node)){for(let l of c.writes)n(t.index,l,!0);for(let l of c.reads)As(e,l)&&r.push({unit:t.index,base:l})}for(let c of F7(e,t.node))n(t.index,c,!0);let a=T7(e,t.node);if(a.length>0){i.set(t.index,a);for(let c of a)n(t.index,c,!0)}}function T7(e,t){let{ts:n}=e,r=new Set,i=(o,s)=>{if(!(n.isFunctionLike(o)&&o!==t&&!s)){if(n.isCallExpression(o)){let a=Z(n,o.expression);L7(e,a,r);let c=Ns(n,a);if(c&&O9.test(c)){M7(n,o,s,i);return}}o.forEachChild(a=>i(a,s))}};return i(t,!1),[...r]}function L7(e,t,n){let{ts:r}=e;if(r.isIdentifier(t)){let i=e.stateSetters.get(t.text);i&&n.add(i);let o=e.closures.get(t.text);if(o)for(let s of o.stateWrites)n.add(s)}}function M7(e,t,n,r){for(let i of t.arguments){let o=Z(e,i);(e.isArrowFunction(o)||e.isFunctionExpression(o))&&o.body?r(o.body,!0):r(i,n)}}function D7(e,t){let{ts:n}=e;if(n.isCallExpression(t)||n.isDeleteExpression(t))return!0;let r=n.isBinaryExpression(t)?t.left:n.isPrefixUnaryExpression(t)||n.isPostfixUnaryExpression(t)?t.operand:null;return r!==null&&!n.isIdentifier(Z(n,r))}function F7(e,t){let{ts:n}=e,r=[],i=o=>{if(n.isCallExpression(o)||n.isNewExpression(o))for(let s of o.arguments??[]){let a=Z(n,s);n.isIdentifier(a)&&e.containers.has(a.text)&&r.push(a.text)}o.forEachChild(i)};return i(t),r}function k7(e,t){let{ts:n}=e,r=[],i=o=>{if(n.isCallExpression(o)){let s=Z(n,o.expression);if(n.isIdentifier(s)){let a=e.closures.get(s.text);a&&r.push(a)}}o.forEachChild(i)};return i(t),r}function Uw(e,t){let n=e.isExpressionStatement(t)?t.expression:e.isExpression(t)?t:null;return n?Z(e,n):null}function Z(e,t){let n=t;for(;;)if(e.isParenthesizedExpression(n)||e.isAwaitExpression(n)||e.isVoidExpression(n))n=n.expression;else if(e.isAsExpression(n)||e.isSatisfiesExpression(n)||e.isNonNullExpression(n)||e.isTypeAssertionExpression(n))n=n.expression;else return n}function Yp(e,t){let{ts:n}=e;return n.isBinaryExpression(t)&&N7(n,t.operatorToken.kind)?Fr(n,t.left):n.isPrefixUnaryExpression(t)||n.isPostfixUnaryExpression(t)?t.operator===n.SyntaxKind.PlusPlusToken||t.operator===n.SyntaxKind.MinusMinusToken?Fr(n,t.operand):null:n.isDeleteExpression(t)?Fr(n,t.expression):n.isCallExpression(t)?cee(n,t):null}function N7(e,t){return t>=e.SyntaxKind.FirstAssignment&&t<=e.SyntaxKind.LastAssignment}function Fr(e,t){let n=Z(e,t);for(;;)if(e.isPropertyAccessExpression(n)||e.isElementAccessExpression(n))n=Z(e,n.expression);else{if(e.isIdentifier(n))return n.text;if(n.kind===e.SyntaxKind.ThisKeyword)return"this";if(e.isCallExpression(n))n=Z(e,n.expression);else return null}}function As(e,t){return t!=="this"&&!e.paramNames.has(t)&&e.localNames.has(t)}function A7(e,t){let n=[],r=[...t.pointById.values()].filter(i=>i.kind==="use");for(let i of e.units)if(i.kind==="return")n.push(..._7(e,i,r));else if(i.kind==="throw")n.push({id:`throw@${i.startLine+1}`,kind:"throw",label:i.label,line:i.startLine,unit:i.index,group:`throw@${i.startLine+1}`,hook:!1,seedPoints:null});else if(i.kind==="statement"){let o=O7(e,t,i);o&&n.push(o)}return n}function _7(e,t,n){let{ts:r,sourceFile:i}=e,o=t.startLine,s=r.isReturnStatement(t.node)?t.node.expression:t.node;if(!s)return[];let a=Z(r,s);return r.isObjectLiteralExpression(a)&&a.properties.length>=2?a.properties.map(c=>{let l=H7(r,i,c),u=c.getStart(i),d=c.getEnd();return{id:`return.${l}@${o+1}`,kind:"return-property",label:`return.${l}`,line:o,unit:t.index,group:`return.${l}`,hook:!1,seedPoints:n.filter(m=>m.start>=u&&m.end<=d)}}):[{id:`return@${o+1}`,kind:"return",label:"return",line:o,unit:t.index,group:"return",hook:!1,seedPoints:null}]}function qw(e,t){return{id:`write:${t}@${e.startLine+1}`,kind:"mutation",label:e.label,line:e.startLine,unit:e.index,group:`write:${t}@${e.startLine+1}`,hook:!1,seedPoints:null}}function O7(e,t,n){let{ts:r}=e,i=Uw(r,n.node);if(!i)return null;let o=Yp(e,i),s=t.writesByUnit.get(n.index);if(o!==null&&As(e,o)){let a=s?[...s.external]:[];return a.length>0?qw(n,a[0]):null}return r.isCallExpression(i)||r.isNewExpression(i)||r.isTaggedTemplateExpression(i)?$7(e,n,i,o,s):B7(e,n,i,o,t)}function B7(e,t,n,r,i){return r===null||r!=="this"&&!e.paramNames.has(r)&&j7(e,n,i,t)?null:qw(t,r)}function $7(e,t,n,r,i){let{ts:o,sourceFile:s}=e,a=o.isTaggedTemplateExpression(n)?n.tag:Z(o,n.expression);if(r===null&&lee(e,a,i))return null;let c=Nl(a.getText(s)),l=o.isTaggedTemplateExpression(n)?null:Ns(o,a);return{id:`call:${c}@${t.startLine+1}`,kind:"effect-call",label:`${c}(\u2026)`,line:t.startLine,unit:t.index,group:`call:${c}@${t.startLine+1}`,hook:l!==null&&ks.test(l),seedPoints:null}}function j7(e,t,n,r){let{ts:i}=e,o=i.isBinaryExpression(t)?t.left:i.isPrefixUnaryExpression(t)||i.isPostfixUnaryExpression(t)?t.operand:null;if(!o)return!1;let s=Z(i,o);if(!i.isIdentifier(s)||!e.localNames.has(s.text))return!1;let a=n.definitionsByUnitName.get(`${r.index}\0${s.text}`);if(!a)return!0;let c=e.callable.getStart(e.sourceFile),l=e.callable.getEnd();return Hw(a.symbolKey,e.sourceFile.fileName,c,l)}function H7(e,t,n){if(e.isSpreadAssignment(n))return`...${Nl(n.expression.getText(t))}`;let r=n.name;return r?e.isIdentifier(r)||e.isPrivateIdentifier(r)||e.isStringLiteral(r)||e.isNumericLiteral(r)?r.text:Nl(r.getText(t)):Nl(n.getText(t))}function Nl(e){let t=e.replace(/\s+/gu," ").trim();return t.length>40?`${t.slice(0,37)}...`:t}function U7(e,t){if(e.seedPoints===null)return[e.unit];let n=new Set;for(let r of e.seedPoints)for(let i of t.pointDeps.get(r.id)??[])n.add(i);return[...n]}function Nw(e,t){let n=new Set(e),r=[...e];for(;r.length>0;){let i=r.pop();for(let o of t(i))n.has(o)||(n.add(o),r.push(o))}return n}function q7(e){let t=new Map,n=[];for(let o of e){if(o.guard){n.push(o);continue}let s=t.get(o.seed.group)??[];s.push(o),t.set(o.seed.group,s)}let r=new Map;e.forEach((o,s)=>r.set(o.seed.id,s));let i=[];for(let o of n)i.push({output:Aw([o],!0),order:r.get(o.seed.id)});for(let o of t.values())i.push({output:Aw(o,!1),order:Math.min(...o.map(s=>r.get(s.seed.id)))});return i.sort((o,s)=>o.order-s.order).map(o=>o.output)}function Aw(e,t){let n=[...e].sort((s,a)=>s.seed.line-a.seed.line)[0],r=[...new Set(e.flatMap(s=>[...s.slice]))].sort(Wi),i=[...new Set(e.flatMap(s=>[...s.fullSlice]))].sort(Wi),o=[...new Set(e.map(s=>s.seed.unit))].sort(Wi);return{id:e.length===1?n.seed.id:`${n.seed.label}@${n.seed.line+1}`,kind:n.seed.kind,label:n.seed.label,line:n.seed.line,units:o,guard:t,hook:e.some(s=>s.seed.hook),sliceSize:r.length,fullSliceSize:i.length,slice:r,fullSlice:i}}function z7(e,t){if(e.length===0||t===0)return{tightness:0,fullTightness:0,sliceShare:0,fullSliceShare:0,overlap:0,superglue:0,glue:0};let n=_w(e.map(Al)),r=_w(e.map(s=>s.fullSlice??[])),i=new Map;for(let s of e)for(let a of s.fullSlice??[])i.set(a,(i.get(a)??0)+1);let o=s=>s.reduce((a,c)=>a+c,0)/s.length;return{tightness:Ds(n.size/t),fullTightness:Ds(r.size/t),sliceShare:Ds(o(e.map(s=>s.sliceSize))/t),fullSliceShare:Ds(o(e.map(s=>s.fullSliceSize))/t),overlap:Ds(o(e.map(s=>s.sliceSize===0?0:n.size/s.sliceSize))),superglue:r.size,glue:[...i.values()].filter(s=>s>=2).length}}function _w(e){if(e.length===0)return new Set;let t=new Set(e[0]);for(let n of e.slice(1)){let r=new Set(n);t=new Set([...t].filter(i=>r.has(i)))}return t}function Ds(e){return Math.round(e*100)/100}function G7(e,t,n,r){let i=new Map;for(let l of e)for(let u of Al(l))i.set(u,(i.get(u)??0)+1);let o=new Set;for(let l of r.writesByUnit.values())for(let u of l.local)o.add(u);let s=new Set([...i].filter(([l,u])=>u>=2&&!t.has(l)&&n.units[l].kind!=="predicate"&&![...r.definedNames[l]].some(d=>o.has(d))&&[...r.controlDeps[l]].every(d=>n.guardPredicates.has(d))&&(r.dataDeps[l].size===0||u>=e.length*A9)).map(([l])=>l)),a=new Set,c=!0;for(;c;){c=!1;for(let l of s)a.has(l)||[...r.dataDeps[l]].every(u=>a.has(u))&&(a.add(l),c=!0)}return[...a].sort(Wi)}function Ow(e,t,n,r,i){let o=e.map(l=>Al(l).filter(u=>!t.has(u))),s=K7(e,o),a=[];for(let l of s.values()){let u=[...new Set(l.flatMap(d=>o[d]))].sort(Wi);u.length!==0&&a.push(J7(e,l,u,t,n,r,i))}a.sort((l,u)=>u.units.length-l.units.length||X7(l,u));let c=a.find(l=>l.role==="extraction");return c&&(c.role="remainder"),a}function K7(e,t){let n=e.map((s,a)=>a),r=s=>{for(;n[s]!==s;)n[s]=n[n[s]],s=n[s];return s},i=new Map;t.forEach((s,a)=>{for(let c of s){let l=i.get(c);l===void 0?i.set(c,a):n[r(a)]=r(l)}});let o=new Map;return e.forEach((s,a)=>{let c=r(a),l=o.get(c)??[];l.push(a),o.set(c,l)}),o}function W7(e,t,n,r){let i=new Set,o=[];for(let s of e){for(let a of r.paramReads[s])i.add(a);for(let a of r.outerReads[s])i.add(a);V7(r,s,t,i);for(let a of n.hookCalls.get(s)??[])o.push(`${a}@${n.units[s].startLine+1}`)}return{inputs:i,hooks:o}}function V7(e,t,n,r){for(let i of e.dataDeps[t])if(n.has(i))for(let o of e.definedNames[i])r.add(o)}function J7(e,t,n,r,i,o,s){let{inputs:a,hooks:c}=W7(n,r,i,o),l=t.map(f=>e[f]),u=l.every(f=>f.kind==="throw"),d=Q7(n.map(f=>i.units[f])),m=d.reduce((f,g)=>f+g.endLine-g.startLine+1,0),p=n.length>=s.minClusterUnits&&!u&&m>=N9;return{outputs:l.map(f=>f.id),units:n,lineRanges:d,inputs:[...a].sort(),kind:Y7(l,c,n.some(f=>i.awaitUnits.has(f))),role:p?"extraction":"below-threshold",narrow:a.size<=Vp,hooks:c,guardOnly:u}}function Y7(e,t,n){if(t.length>0||e.some(o=>o.hook))return"hook";let r=e.some(o=>o.kind==="return"||o.kind==="return-property"),i=n||e.some(o=>o.kind==="effect-call"||o.kind==="mutation");return r?i?"operation":"calculation":"effects"}function X7(e,t){return(e.lineRanges[0]?.startLine??0)-(t.lineRanges[0]?.startLine??0)}function Q7(e){let t=[];for(let n of[...e].sort((r,i)=>r.startLine-i.startLine)){let r=t[t.length-1];r&&n.startLine<=r.endLine+1?r.endLine=Math.max(r.endLine,n.endLine):t.push({startLine:n.startLine,endLine:n.endLine})}return t}function Z7(e,t){let n=Gw(e);return e.react?ks.test(n)?"react-hook":"react-component":t.length>=_9&&t.every(r=>r.kind==="effect-call")?"orchestration":"calculation"}function eee(e,t,n,r){if(!e)return{tier:"support",reason:"No split meets the selected output and statement thresholds."};if(r.status!=="complete")return{tier:"support",reason:`${t==="orchestration"?"Orchestration root: disjoint slices are expected. ":""}Local flow is partial (${Xp(r)}), so a dropped dependency could join the clusters; the seam is unproven.`};if(t==="orchestration")return{tier:"support",reason:"The body matches an operation-sequencing pattern; disjoint slices alone do not justify splitting it."};let i=n.filter(s=>s.role==="extraction"),o=i.filter(s=>s.narrow);return o.length===0?{tier:"support",reason:`Local slices are disjoint, but each of the ${i.length} extraction(s) has more than ${Vp} observed input names.`}:{tier:"signal",reason:`Local flow model complete; ${o.length} extraction(s) with at most ${Vp} observed input names; review captured state and ordering before planning an extraction.`}}function Xp(e){return e.unsupported[0]??"candidate dependencies or unsupported constructs present"}function tee(e,t,n,r){let{body:i,flow:o,clusters:s,preamble:a,orphans:c,coverage:l}=r,u=t.filter(g=>g.guard).length,d=[`${e} statements, ${t.length-u} value output(s), ${u} guard exit(s); ${r.archetype}`,`tightness ${n.tightness.toFixed(2)} (with guards ${n.fullTightness.toFixed(2)}); overlap ${n.overlap.toFixed(2)}; local model only`];s.filter(g=>g.role!=="below-threshold").forEach((g,h)=>{d.push(`cluster ${h+1} (${g.kind}, ${g.role}): ${g.units.length} statements at ${Fs(g.lineRanges)} produce ${g.outputs.join(", ")}`+(g.role==="extraction"?g.inputs.length>0?`; takes ${Vi(g.inputs)}`:"; takes no parameters":""))});let m=s.filter(g=>g.role==="below-threshold"&&!g.guardOnly);if(m.length>0&&d.push(`${m.length} cluster(s) below --min-cluster ${r.thresholds.minClusterUnits} stay in place: ${m.map(g=>`${Fs(g.lineRanges)} (${g.outputs.join(", ")})`).join("; ")}`),a.length>0){let g=[...new Set(a.flatMap(h=>[...o.definedNames[h]]))];d.push(`${a.length} shared setup statement(s) derived only from inputs`+(g.length>0?`: ${Vi(g)}`:""))}if(c.length>0){let g=[...new Set(c.map(h=>i.units[h].startLine+1))];d.push(`${c.length} statement(s) reach no output: ${g.map(h=>`line ${h}`).join(", ")}`)}let p=[...i.handlerDeps.keys()].filter(g=>Ji.has(i.units[g].kind)).length;p>0&&d.push(`${p} catch/finally statement(s) were kept with the try block they handle`);let f=[...new Set([...o.stateWritesByUnit.values()].flat())];return f.length>0&&d.push(`state written at render time or in effects was treated as a dependency of later reads: ${Vi(f)}`),l.status!=="complete"&&d.push(`local flow partial: ${Xp(l)}`),l.candidateEdges>0&&d.push(`${l.candidateEdges} candidate flow edge(s) (closure capture or field flow) were treated as dependencies; they can merge clusters but never separate them`),d}function Vi(e,t=8){return e.length>t?`${e.slice(0,t).join(", ")}, +${e.length-t} more`:e.join(", ")}function Fs(e,t=6){let n=e.map(r=>r.startLine===r.endLine?`line ${r.startLine+1}`:`lines ${r.startLine+1}-${r.endLine+1}`);return n.length>t?`${n.slice(0,t).join(", ")}, +${n.length-t} more ranges`:n.join(", ")}function nee(e,t,n,r){let{body:i,clusters:o,coverage:s,archetype:a}=r,c=Gw(i);if(!e)return ree(t,n,r);let l=o.filter(g=>g.role==="extraction"),u=o.find(g=>g.role==="remainder"),d=(g,h)=>`${h+1}) ${oee(g)}: ${Fs(g.lineRanges)} producing ${zw(g.outputs)}`+(g.inputs.length>0?` from (${Vi(g.inputs,6)})`:" from no parameters")+(g.narrow?"":` [wide interface: ${g.inputs.length} parameters]`)+(g.hooks.length>0?` [hooks: ${Vi(g.hooks,4)}]`:""),m=l.map(d).join("; "),p=iee(r,u);if(s.status!=="complete")return`${a==="orchestration"?"Preserve sequencing and treat it as an orchestration root. ":""}Inspect before extracting: local flow is partial (${Xp(s)}). Candidate seam(s): ${m}. ${p}`.trim();if(a==="orchestration")return`${c} sequences ${l.length+1} independent operations (${m}); treat it as an orchestration root, not a cohesion defect, unless the steps serve unrelated purposes.`;let f=l.every(g=>g.kind==="effects")?" Advisory: an effect sequence may be intentional orchestration; confirm the steps serve a separate purpose before moving them.":"";return`Review a possible extraction from ${c}: ${m}. ${p}${f}`.trim()}function ree(e,t,n){let{clusters:r}=n;if(e.length===0)return"No value output was found; the body has nothing to slice.";if(e.length===1)return"One value output; cohesion is trivially complete.";let i=new Set(r.flatMap(l=>l.outputs)),o=e.filter(l=>!i.has(l.id)).length,s=r.filter(l=>l.role==="below-threshold"&&!l.guardOnly),a=[];if(r.length===0)return`The ${e.length} value outputs read only shared setup derived from the inputs (${n.preamble.length} statement(s)); nothing separates them; keep the function whole.`;a.push(`The ${e.length} value outputs form ${r.length} cluster(s)`+(o>0?`, and ${o} of them read only shared setup`:""));let c=r.length===1?r[0]:null;return c&&c.outputs.length>1&&a.push(`${t.superglue} statement(s) feed every output and ${t.glue} feed more than one`+(t.superglue===0?"; the outputs are chained through shared statements, branch predicates, or state writes rather than one common root":"")),s.length>0&&a.push(`${s.length} cluster(s) stay below --min-cluster ${n.thresholds.minClusterUnits}: ${s.map(l=>Fs(l.lineRanges,2)).join("; ")}`),`${a.join("; ")}; keep the function whole.`}function zw(e,t=4){let n=e.map(r=>r.replace(/@\d+$/u,""));return n.length>t?`${n.slice(0,t).join(", ")}, +${n.length-t} more`:n.join(", ")}function iee(e,t){let{flow:n,clusters:r,preamble:i,guards:o,thresholds:s}=e,a=[];if(t&&a.push(`the largest computation (${Fs(t.lineRanges,4)} producing ${zw(t.outputs)})`),i.length>0){let l=[...new Set(i.flatMap(u=>[...n.definedNames[u]]))];a.push(`${i.length} shared setup statement(s)${l.length>0?` (${Vi(l,4)})`:""}`)}let c=r.filter(l=>l.role==="below-threshold"&&!l.guardOnly);return c.length>0&&a.push(`${c.length} smaller cluster(s) below --min-cluster ${s.minClusterUnits}`),o>0&&a.push(`${o} guard exit(s)`),a.length>0?`Stays in place: ${a.join(", ")}.`:""}function oee(e){switch(e.kind){case"calculation":return"pure calculation candidate";case"operation":return"operation candidate (awaits or effects inside; not pure)";case"hook":return"custom hook candidate (hooks stay unconditional and in order)";case"effects":return"effect sequence candidate"}}function Gw(e){let t=e.callable.name;return t&&"text"in t?String(t.text):"this function"}function see(e,t,n){for(let r of t)if(e.isVariableStatement(r))for(let i of r.declarationList.declarations)for(let o of an(i.name))n.add(o);else if(!e.isExpressionStatement(r))return!1;return!0}function aee(e,t,n){return!!(e.isPropertyAccessExpression(n)&&n.name===t||e.isPropertyAssignment(n)&&n.name===t||e.isBindingElement(n)&&n.propertyName===t||"name"in n&&n.name===t&&!e.isShorthandPropertyAssignment(n))}function cee(e,t){let n=Z(e,t.expression);return e.isPropertyAccessExpression(n)?Bw.has(n.name.text)?null:Fr(e,n):e.isElementAccessExpression(n)?Fr(e,n):null}function lee(e,t,n){let{ts:r}=e;if(r.isIdentifier(t)){let i=e.closures.get(t.text);if(i&&![...i.writes].some(o=>!As(e,o)))return!0}return!!(n&&n.local.size>0&&n.external.size===0)}function uee(e,t,n,r){n[t].add(_l(e.name));let i=`${t}\0${e.name}`;r.has(i)||r.set(i,e)}function dee(e,t,n,r,i){for(let o of n)o.unit===t.unit||o.base!==t.base||e[o.unit].start<=r||i[o.unit].add(t.unit)}function Kw(e){let t;try{t=et(e,["rev-parse","HEAD"]).trim()}catch{return null}return/^[0-9a-f]{40,64}$/u.test(t)?{head:t,branch:mee(e),dirtyPaths:pee(e)}:null}function mee(e){try{let t=et(e,["rev-parse","--abbrev-ref","HEAD"]).trim();return t&&t!=="HEAD"?t:null}catch{return null}}function pee(e){try{return et(e,["status","--porcelain"]).split(`
|
|
335
|
+
`).filter(t=>t.length>0).length}catch{return 0}}import{readdirSync as fee}from"fs";import{basename as gee,join as Ww}from"path";function hee(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 yee(e,t){let n=bee(e,t.file,t.keys);if(!n.ok)return{name:t.name,file:t.file,status:"unavailable",missing:[],extra:[],unavailableReason:n.reason};let r=Eee(e.config.projectRoot,t.mustEqual),i=hee(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 Jw(e,t){return t.map(n=>yee(e,n))}function bee(e,t,n){return n.type==="markdown-list"?Ree(e,t,n.marker):See(e,t,n)}function See(e,t,n){if(!H(e,t))return{ok:!1,reason:`file not found: ${t}`};let i=se(t);if(!i)return{ok:!1,reason:`unsupported file type for ${n.type} extraction: ${t}`};let o=_(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"?vee(o,n.identifier):xee(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 Yw(e){let t=e.childForFieldName("value");return t?t.type==="as_expression"||t.type==="satisfies_expression"?t.namedChild(0):t:null}function vee(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=Yw(n);if(i?.type==="object")return Cee(i)}return null}function Cee(e){let t=new Set;for(let n of e.namedChildren)if(n.type==="pair"){let r=n.childForFieldName("key");r&&t.add(Xw(r.text))}else n.type==="shorthand_property_identifier"&&t.add(n.text);return[...t].sort()}function xee(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=Yw(n);if(i?.type!=="array")continue;let o=new Set;for(let s of i.namedChildren)s.type==="string"&&o.add(Xw(s.text));return[...o].sort()}return null}function Xw(e){return e.length>=2&&(e[0]==="'"&&e.endsWith("'")||e[0]==='"'&&e.endsWith('"'))?e.slice(1,-1):e}function Ree(e,t,n){let r=H(e,t);if(!r)return{ok:!1,reason:`file not found: ${t}`};let i=Qw(r,n);return i===null?{ok:!1,reason:`no <!-- BEGIN GENERATED ${n} --> ... <!-- END GENERATED ${n} --> block in ${t}`}:{ok:!0,keys:Zw(i)}}function Qw(e,t){let n=Ge(t),i=new RegExp(`<!--\\s*BEGIN GENERATED ${n}\\s*-->([\\s\\S]*?)<!--\\s*END GENERATED ${n}\\s*-->`).exec(e);return i?i[1]:null}function Zw(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 Eee(e,t){switch(t.type){case"top-level-dirs":return Vw(Ww(e,t.path));case"file-glob":return[...new Set(tl(e,t.pattern).map(n=>gee(n)))].sort();case"registered-commands":return Iee(e);case"builtin-skills":return Vw(Ww(e,"skills"))}}function Vw(e){let t;try{t=fee(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort()}function Iee(e){let t;try{t=te(e,"docs/COMMAND_REFERENCE.md",{maxBytes:8*1024*1024,inputKind:"generated command reference"})}catch(r){if(!xe(r))throw r;return[]}let n=Qw(t,"COMMAND REFERENCE");return n?Zw(n):[]}import{getHeapStatistics as wee}from"v8";var Pee=64*1024*1024;function Qp(){let e=globalThis.gc;if(!e)return;let t=wee();t.heap_size_limit-t.used_heap_size<Pee||e()}function Zp(e){return e.scoreCount??e.count}function eP(e,t){let n=_ee(e);return{overview:{documents:e.statsResult.documents,symbols:e.statsResult.symbols,indexSizeBytes:e.statsResult.indexSizeBytes},...t?{provenance:t}:{},findings:{deadSymbols:e.dead.count,deadLoc:e.dead.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:Zp(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:Zp(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,passthroughs:e.passthroughs.count,driftedFiles:e.drift.count,hiddenCouplingPairs:e.gitEvidence?.hiddenCoupling.pairCount??null,hiddenCouplingScoreCount:e.gitEvidence?.hiddenCoupling.scoreCount??null,coverageContractViolations:e.coverageContracts.count},axes:Mee(e),validation:Dee(e),suppressions:e.suppressions,actions:n,policyExclusions:Lee(e),detectorEvidence:e.detectorEvidence,warnings:e.warnings.length>0?e.warnings:void 0}}var Tee=[["react-component-duplicates",e=>e.reactComponentDuplicates],["react-hook-candidates",e=>e.reactHookCandidates],["react-large-component-pressure",e=>e.reactLargeComponentPressure],["duplicate-bodies",e=>e.duplicateBodies],["dead",e=>e.dead]];function Lee(e){let t=[],n=(r,i)=>{for(let o of i??[])o.count<=0||t.push({detector:r,reason:o.reason,detail:o.detail,count:o.count})};for(let[r,i]of Tee)n(r,i(e).exclusions);return n("cycles",e.cycleExclusions),n("co-change",e.gitEvidence?.hiddenCoupling.exclusions),t}function Mee(e){return{deletable:{loc:e.dead.loc,symbols:e.dead.count},cycles:{count:e.realCycleCount},changeAmplification:e.gitEvidence?.amplification??null,hiddenCoupling:e.gitEvidence?.hiddenCoupling??null,evidenceQuality:{graphFindings:e.dead.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.passthroughs.count+e.drift.count,userSuppressed:e.suppressions?.total??0}}}function Dee(e){let t=e.gitEvidence?.fileStats;if(!t)return null;let n=Fee(e),r=new Set(Object.values(n).flat()),{flaggedFixDensity:i,baselineFixDensity:o}=kee(t,r),s=Nee(n,t,o);return{flaggedFiles:r.size,flaggedFixDensity:i,baselineFixDensity:o,ratio:r.size>0&&o>0?_s(i/o):null,byCategory:s,validationBasis:{method:"subject-regex",commitsScanned:e.gitEvidence?.commitsScanned??0}}}function Fee(e){return{dead:e.dead.files??[],twinDrift:e.twinDrift.files??[],passthroughs:e.passthroughs.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??[]}}function kee(e,t){let n=0,r=0,i=0;for(let[a,c]of Object.entries(e))t.has(a)?n+=c.fixChanges:(r+=c.fixChanges,i+=1);let o=t.size>0?_s(n/t.size):0,s=i>0?_s(r/i):0;return{flaggedFixDensity:o,baselineFixDensity:s}}function Nee(e,t,n){let r={};for(let[i,o]of Object.entries(e)){let s=new Set(o);if(s.size===0)continue;let a=0;for(let l of s)a+=t[l]?.fixChanges??0;let c=_s(a/s.size);r[i]={flaggedFiles:s.size,fixDensity:c,lift:n>0?_s(c/n):null}}return r}function _s(e){return Math.round(e*100)/100}function Aee(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function Ol(e,t="existing shared infrastructure discount"){let n=Zp(e);return Math.abs(n-e.count)<.01?"":` (combined pair weight ${Aee(n)} after ${t})`}function _ee(e){let t=[];Oee(e,t),Bee(e,t),$ee(e,t),jee(e,t),Hee(e,t);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}function Oee(e,t){e.dead.count>0&&t.push({category:"Dead code",evidence:"graph-fact",evidenceContractId:"dead-visible-references",description:`${e.dead.count} indexed symbols with no visible repository references \u2014 review runtime/framework roots and the capability disclosure, then verify any deletion with cleanup-plan --verify`,effort:"low",impact:"high",count:e.dead.count,locRecoverable:e.dead.loc}),e.realCycleCount>0&&t.push({category:"Circular dependencies",evidence:"graph-fact",description:`${e.realCycleCount} cyclic import/re-export component(s), including type-only dependencies \u2014 inspect ownership and runtime effects before changing them`,effort:"medium",impact:"high",count:e.realCycleCount,locRecoverable:0})}function Bee(e,t){e.similarCount>0&&t.push({category:"Similar functions",evidence:"heuristic",evidenceContractId:"duplicate-structural-candidate",description:`${e.similarCount} pairs share disclosed call or source-token evidence beyond imports \u2014 review domain identity before considering consolidation`,effort:"medium",impact:"medium",count:e.similarCount,locRecoverable:0}),e.duplicateBodies.count>0&&t.push({category:"Duplicate function bodies",evidence:"heuristic",evidenceContractId:"duplicate-structural-candidate",description:`${e.duplicateBodies.count} exact small-body group(s) across files \u2014 consolidate only when the domain concept matches`,effort:"low",impact:"medium",count:e.duplicateBodies.count,locRecoverable:e.duplicateBodies.loc}),e.twinDrift.count>0&&t.push({category:"Drifted twin implementations",evidence:"heuristic",description:`${e.twinDrift.count} same-name (or near-name) function group(s) across files with diverged or identical bodies \u2014 determine whether they represent the same concept before acting`,effort:"medium",impact:"medium",count:e.twinDrift.count,locRecoverable:0})}function $ee(e,t){e.reactComponentDuplicates.count>0&&t.push({category:"Duplicated React components",evidence:"heuristic",description:`${e.reactComponentDuplicates.count} React component pair(s) share JSX structure${Ol(e.reactComponentDuplicates,"support-tier discount")} \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${Ol(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${Ol(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})}function jee(e,t){if(e.passthroughs.count>0&&t.push({category:"Passthrough functions",evidence:"heuristic",evidenceContractId:"passthrough-forwarding-candidate",description:`${e.passthroughs.count} functions that literally forward to one callee \u2014 inspect whether each is unnecessary indirection or an intentional boundary`,effort:"low",impact:"low",count:e.passthroughs.count,locRecoverable:e.passthroughs.loc}),e.drift.count>0){let n=[];e.drift.unusedImports>0&&n.push(`${e.drift.unusedImports} unused imports`),e.drift.architectureViolations>0&&n.push(`${e.drift.architectureViolations} declared architecture violations`),t.push({category:"Structural drift",evidence:"heuristic",description:`${n.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})}e.coverageContracts.count>0&&t.push({category:"Coverage contract drift",evidence:"graph-fact",description:`${e.coverageContracts.count} configured coverage contract(s) drifted from their ground-truth source (enumeration rot) \u2014 run \`scip-query health --json\` for the missing/extra keys`,effort:"low",impact:"medium",count:e.coverageContracts.count,locRecoverable:0})}function Hee(e,t){if(e.gitEvidence&&e.gitEvidence.hiddenCoupling.pairCount>0){let n=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`+Ol({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:e.gitEvidence.hiddenCoupling.scoreCount},"broad/stale-history discount")+(n?` (e.g. ${n.fileA} \u2194 ${n.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})}}var Uee=[{id:"dead-visible-references",detector:"dead",claim:"The symbol has no visible repository reference after entry, framework, and rooted-symbol exclusions.",relationRequirements:[{family:"identity",subtype:"references",minimumStrength:"exact"},{family:"execution",subtype:"call",minimumStrength:"exact"}],structuralEvidence:["entry-surface exclusions","framework/source fallback references","rooted-symbol exclusions"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Absence of visible references does not prove absence of reflection, generated dispatch, or external use."],recoverWith:"scip-query evidence --symbol <symbol> --edge execution --edge runtime --edge identity --direction both --depth 2 --max-edges 100"},{id:"passthrough-forwarding-candidate",detector:"passthrough-candidates",claim:"A small callable visibly forwards to one callee, with public-facade and boundary signals disclosed.",relationRequirements:[{family:"execution",subtype:"call",minimumStrength:"exact"},{family:"contract",subtype:"uses-contract-symbol",minimumStrength:"exact"}],structuralEvidence:["statement-complete forwarding shape","public facade evidence","runtime-boundary signals"],calibration:"mixed",providerCoverage:"partial",nonClaims:["Literal forwarding does not prove the callable has no contract, naming, policy, or compatibility role."],recoverWith:"scip-query inspect --symbol <symbol> --view behavior"},{id:"decorative-checker-terminal-behavior",detector:"decorative-checkers",claim:"A checker-shaped callable lacks a visible failure terminal directly or through one resolved delegate.",relationRequirements:[{family:"execution",subtype:"returns",minimumStrength:"exact"},{family:"execution",subtype:"throws",minimumStrength:"exact"}],structuralEvidence:["checker naming shape","direct terminal behavior","one-hop delegate body"],calibration:"mixed",providerCoverage:"partial",nonClaims:["No visible terminal does not prove the checker cannot fail through an opaque call, exception, or process exit."],recoverWith:"scip-query inspect --symbol <symbol> --view behavior"},{id:"duplicate-structural-candidate",detector:"duplicate and similarity detectors",claim:"Two source units share the detector-specific structural or token pattern.",relationRequirements:[],structuralEvidence:["normalized source/token/JSX/template similarity"],calibration:"candidate",providerCoverage:"partial",nonClaims:["Structural similarity does not establish shared domain identity or justify consolidation."],recoverWith:"scip-query inspect --symbol <symbol-a> --symbol <symbol-b> --view behavior"}];function tP(e=new Set(["indexed-graph","source-facts"])){return Uee.map(t=>{let n=t.relationRequirements.map(i=>{let o=Lc(i.family,i.subtype);if(!o)throw new Error(`Detector ${t.id} names an unregistered relation ${i.family}/${i.subtype}`);if(!o.relation.evidenceStrengths.includes(i.minimumStrength))throw new Error(`Detector ${t.id} requires unsupported strength ${i.minimumStrength} for ${i.family}/${i.subtype}`);return o.provider}),r=[...new Set(n.flatMap(i=>i.requirements))].filter(i=>!e.has(i));return{...t,status:r.length>0?"unsupported":t.calibration,providerIds:[...new Set(n.map(i=>i.id))],unavailableRequirements:r}})}var qee=25e3,zee=2500,nP=2500,ef=50,$l=["overview","dead","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","passthrough-candidates","drift","git-evidence","suppressions","coverage-contracts"],Gee={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:[...n.warnings,...t?["Scope filters detector candidates; repository statistics, history and coverage contracts remain global. A scoped graph cannot establish repository-wide cycle freedom."]:[]]}),dead:(e,t,n)=>({phase:"dead",dead:Jee(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",...Yee(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:Xee(e,t,n)}),"duplicate-bodies":(e,t,n)=>({phase:"duplicate-bodies",duplicateBodies:Qee(e,t,n)}),"twin-drift":(e,t,n)=>({phase:"twin-drift",twinDrift:Zee(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:ete(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:tte(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:nte(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:rte(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:ite(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:ote(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:ste(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:ute(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:ate(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:cte(e,n)}),"coverage-contracts":(e,t,n)=>({phase:"coverage-contracts",coverageContracts:lte(e,n)})};function oP(e){let t=e.generation.identity,n=Wg(e.config.dbPath),r=n?.currentGeneration===t?n:null;return{computedAt:new Date().toISOString(),generation:{identity:t,publishedAt:r?.publishedAt??null,mode:r?.publication?.mode??null},git:Kw(e.config.projectRoot)}}function nf(e,t,n={}){return Kee(e,[t],n)[0]}function Kee(e,t,n={}){return Wee(e,n.full!==!1,(r,i)=>{let o={...i,releaseCachesBetweenPhases:!1};return t.map(s=>Gee[s](e,n.scope,o,r))})}function Wee(e,t,n){let r=Wo(e),i=dte(r,t);try{return n(r,i)}finally{Bm(e,{semanticProvider:!0}),Qp()}}function rf(e,t){return eP(Vee(e),t?oP(t):void 0)}function Vee(e){let t=je(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,detectorEvidence:tP(),dead:je(e,"dead").dead,realCycleCount:je(e,"cycles").realCycleCount,cycleExclusions:je(e,"cycles").cycleExclusions,similarCount:je(e,"similar").similarCount,duplicateBodies:je(e,"duplicate-bodies").duplicateBodies,twinDrift:je(e,"twin-drift").twinDrift,reactComponentDuplicates:je(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:je(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:je(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:je(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:je(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:je(e,"vue-large-view-pressure").vueLargeViewPressure,passthroughs:je(e,"passthrough-candidates").passthroughs,drift:je(e,"drift").drift,gitEvidence:rP(e,"git-evidence")?.gitEvidence??null,suppressions:rP(e,"suppressions")?.suppressions??null,coverageContracts:je(e,"coverage-contracts").coverageContracts}}function rP(e,t){return e.find(n=>n.phase===t)}function je(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function Jee(e,t,n){return He(e,n,"dead",()=>{let r=Pr(e,{scope:t,...mt.dead,scanLimit:n.candidateScanLimit,semantic:n.semantic}),i=r.applicability;return{...of(fte(e,r.symbols)),exclusions:jl([{reason:"entry-surface-symbols",detail:"zero-reference symbols in framework entry surfaces (route handlers, pages, scheduled tasks, live barrels) that the framework invokes",count:i.entrySurfaceExcluded},{reason:"generated-artifact-symbols",detail:"zero-reference symbols in generated artifacts (migration dumps, codegen output) owned by their generator",count:i.generatedArtifactExcluded??0}])}})}function Yee(e,t,n){return He(e,n,"cycles",()=>{let r=gs(e,{scope:t,edgeBasis:"imports"}),i=jm(e,{scope:t}),o=new Set(r.flatMap(a=>a.component??a.path)),s=i.filter(a=>!(a.component??a.path).some(c=>o.has(c)));return{realCycleCount:r.length,cycleExclusions:s.length>0?[{reason:"symbol-reference-only-cycles",detail:`component(s) that cycle through type or symbol references but not through imports (${s.reduce((a,c)=>a+(c.component?.length??c.path.length-1),0)} files); listed by cycles on its default basis`,count:s.length}]:[]}})}function Xee(e,t,n){let r=He(e,n,"similar",()=>rp(e,{scope:t,...mt.similar,scanLimit:n.candidateScanLimit,semantic:n.semantic}));return Math.min(r,n.candidateResultLimit)}function Qee(e,t,n){return He(e,n,"duplicate-bodies",()=>{let r=cl(e,{scope:t,...mt.duplicateBodies,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),i=new Set,o=0;for(let s of r.groups)for(let a of s.functions.slice(1))i.add(a.file),o+=a.loc;return{count:r.groups.length,loc:o,files:[...i],exclusions:r.exclusions.map(s=>({reason:s.reason,detail:`${s.detail}; group members removed before counting`,count:s.count}))}})}function Zee(e,t,n){return He(e,n,"twin-drift",()=>{let r=wl(e,{scope:t,...mt.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 ete(e,t,n){return He(e,n,"react-component-duplicates",()=>{let r=sp(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),i=r.results.filter(o=>iP(o)>0);return{...sf(i,iP),exclusions:jl(r.exclusions,[{reason:"support-tier-pairs",detail:"support-tier pairs (generic structure only, or framework route scaffolding); listed by react-component-duplicates but not counted",count:r.results.length-i.length}])}})}function tte(e,t,n){return He(e,n,"react-hook-candidates",()=>{let r=cp(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),i=[],o=new Map;for(let s of r.results){let a=aP(s);if(a.weight>0){i.push(s);continue}let c=o.get(a.reason)??{reason:a.reason,detail:a.detail,count:0};c.count+=1,o.set(a.reason,c)}return{...sf(i,yte),exclusions:jl(r.exclusions,[...o.values()])}})}function nte(e,t,n){return He(e,n,"react-large-component-pressure",()=>{let r=lp(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return{...hte(r.results),exclusions:jl(r.exclusions,[])}})}function rte(e,t,n){return He(e,n,"vue-component-duplicates",()=>{let r=Cs(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return sP(r)})}function ite(e,t,n){return He(e,n,"vue-composable-candidates",()=>{let r=xs(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return sf(r,bte)})}function ote(e,t,n){return He(e,n,"vue-large-view-pressure",()=>{let r=up(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return of(r)})}function ste(e,t,n){return He(e,n,"passthrough-candidates",()=>{let r=Is(e,{scope:t,...mt.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return gte(r,Cte)})}function ate(e,t){return He(e,t,"git-evidence",()=>{let n=kt(e,{historyMode:t.gitHistoryMode}),r=n.fileChurn();if(!r)return null;let i=n.commitHistory(),o=Rs(e,void 0,{limit:t.candidateResultLimit,historyMode:t.gitHistoryMode}),s={};for(let[u,d]of r)s[u]={changes:d.changes,fixChanges:d.fixChanges};let a=o.findings.filter(u=>tf(u).counted),c=new Map;for(let u of o.findings){let d=tf(u);if(d.counted)continue;let m=c.get(d.reason)??{reason:d.reason,detail:d.detail,count:0};m.count+=1,c.set(d.reason,m)}let l=[...a].sort((u,d)=>Bl(d)-Bl(u)||d.together-u.together);return{amplification:n.changeAmplification(),hiddenCoupling:{pairCount:a.length,scoreCount:af(a.reduce((u,d)=>u+Bl(d),0)),exclusions:[...c.values()].sort((u,d)=>u.reason.localeCompare(d.reason)),top:l.slice(0,5).map(u=>({fileA:u.fileA,fileB:u.fileB,together:u.together,confidence:u.confidence,focusedTogether:u.focusedTogether,broadTogether:u.broadTogether,broadCommitRatio:u.broadCommitRatio,lastTogetherAt:u.lastTogetherAt,recentTogether:u.recentTogether,commitScope:u.commitScope,recency:u.recency,scoreWeight:Bl(u),subjectContext:u.subjectContext}))},fileStats:s,commitsScanned:i?.commits.length??0}})}function cte(e,t){return He(e,t,"suppressions",()=>{let n=Ml(e);return{total:n.total,byCategory:{...n.byCategory}}})}function lte(e,t){return He(e,t,"coverage-contracts",()=>{let n=e.config.coverageContracts??[],i=Jw(e,n).filter(o=>o.status!=="ok");return{count:i.length,loc:0,files:[...new Set(i.map(o=>o.file))].sort()}})}function ute(e,t,n){return He(e,n,"drift",()=>{let r=Ms(e,{scope:t,...mt.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 dte(e,t){let n=e.symbols>=qee||e.documents>=zee,r=t?Number.POSITIVE_INFINITY:ef;return!n||t?{candidateScanLimit:void 0,candidateResultLimit:r,semantic:!0,gitHistoryMode:t?"full":"bounded",releaseCachesBetweenPhases:!0,warnings:t&&n?["Large index detected; running health without candidate scan or result caps because full mode is enabled."]:t?[]:[`Candidate result counts are capped at ${ef}; history uses a bounded window. Enable full mode for unbounded analysis.`]}:{candidateScanLimit:nP,candidateResultLimit:r,semantic:!1,gitHistoryMode:"bounded",releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${nP} symbols and reported their top ${ef} findings. Enable full mode for unbounded candidate counts.`]}}function mte(e,t){t.releaseCachesBetweenPhases&&(Bm(e),Qp())}function He(e,t,n,r){pte(n);try{return r()}finally{mte(e,t)}}function pte(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function fte(e,t){return t.filter(n=>!Ke(e,n.relativePath)&&!We(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function of(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 gte(e,t){return{...of(e),scoreCount:af(e.reduce((r,i)=>r+t(i),0))}}function hte(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 sP(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 sf(e,t){return{...sP(e),scoreCount:af(e.reduce((r,i)=>r+t(i),0))}}function iP(e){return e.actionTier==="signal"?1:0}function yte(e){return aP(e).weight}function aP(e){if(e.evidenceClass==="generic-workflow-scaffolding")return{weight:0,reason:"generic-workflow-pairs",detail:"pairs whose shared behavior is only generic React mechanics (open/close/submit state and handlers)"};let t=e.sharedHooks.some(i=>!Ste.has(i)),n=cP({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});if(t&&n<=2)return{weight:0,reason:"shared-hook-covered-pairs",detail:"pairs whose concrete shared behavior is already carried by a project hook both sides call"};if(!t&&n===0)return{weight:0,reason:"generic-workflow-pairs",detail:"pairs whose shared behavior is only generic React mechanics (open/close/submit state and handlers)"};let r={reason:"counted",detail:"counted"};return t?{weight:.5,...r}:lP(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?{weight:.25,...r}:{weight:n>=2?1:.5,...r}}function jl(...e){let t=new Map;for(let n of e)for(let r of n){if(r.count<=0)continue;let i=t.get(r.reason);i?i.count+=r.count:t.set(r.reason,{...r})}return[...t.values()].sort((n,r)=>n.reason.localeCompare(r.reason))}function bte(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=cP({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:lP(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function cP(e){return e.requests.filter(n=>!vte.has(n)).length*2+e.lifecycle.length+e.namedState.filter(n=>!dP.has(uP(n))).length+Math.min(e.functions.length,3)}var Ste=new Set(["useForm","useFormContext","useInfiniteQuery","useMutation","useParams","usePathname","useQuery","useQueryClient","useRouter","useSearchParams","useSelector","useDispatch","useSuspenseQuery","useTheme","useTranslation"]),vte=new Set(["axios","fetch","gql","graphql","mutate","query","request","useInfiniteQuery","useMutation","useQuery","useSuspenseQuery"]);function lP(e,t,n){let r=[...e,...t,...n].map(uP);return r.length>0&&r.every(i=>dP.has(i))}function uP(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function Cte(e){return e.actionTier==="signal"?.25:1}function Bl(e){return tf(e).counted?e.commitScope==="broad-sweep"?e.recency==="recent"?.25:0:e.commitScope==="mixed"?e.recency==="recent"?.5:.25:e.recency==="recent"?1:.5:0}function tf(e){if(e.actionTier==="signal"&&e.partnerClass!=="doc-code"&&e.partnerClass!=="generated-artifact")return{counted:!1,reason:"sweep-only-pairs",detail:"pairs whose shared commits were only broad sweeps, stale pairs with at most two focused co-changes, and configuration or schema partners; listed by co-change at signal tier"};switch(e.partnerClass){case"doc-code":return{counted:!1,reason:"doc-sync-pairs",detail:"documentation that changes alongside the code it describes (doc-drift owns stale docs)"};case"generated-artifact":return{counted:!1,reason:"generated-artifact-pairs",detail:"generated artifacts (migration journals, snapshots, codegen output) rewritten from their source"};default:return{counted:!0,reason:"counted",detail:"counted"}}}function af(e){return Math.round(e*100)/100}var dP=new Set(["add","apply","cancel","change","clear","close","create","delete","draft","edit","error","filter","form","load","loading","name","open","refresh","remove","reset","save","saving","search","select","selected","submit","toggle","update","value"]);function xte(e,t,n={}){let{file:r,line:i,maxDepth:o,maxEdges:s,direction:a}=Ete(t,n),c=Er(e,r,i-1,i-1),l=c?.coverage??{status:"unsupported",basis:"typescript-compiler-cfg-reaching-definitions",unsupported:["Function-local slicing currently requires TypeScript or JavaScript source."]},u=wte(c?.points??[],i,n),d=Rte(l,u.length),m={kind:"dependence-slice",direction:a,criterion:t,...n.variable!==void 0?{variable:n.variable}:{},resolution:d,candidates:u,points:[],edges:[],coverage:{status:"incomplete",basis:"function-local-dependence",model:l,omittedEdges:0,omittedPoints:0,depthLimited:!1,candidateEdges:0}},p=u[0];if(d!=="matched"||!p||!c)return m;let f=new Map(c.points.map(b=>[b.id,b])),g=Pte(c,f,p.callableId,a),{selected:h,reached:y,depthFrontier:S}=Tte(g,p.id,a,o);m.edges=[...h.values()].slice(0,s);let I=new Set([p.id,...m.edges.flatMap(b=>[b.fromPointId,b.toPointId])]);m.points=[...I].map(b=>f.get(b)).sort((b,v)=>b.start-v.start||b.id.localeCompare(v.id));let x=h.size-m.edges.length,E=S.size>0;return m.coverage={status:l.status!=="complete"?"incomplete":x>0||E?"bounded":"complete",basis:"function-local-dependence",model:l,omittedEdges:x,omittedPoints:y.size-I.size,depthLimited:E,candidateEdges:c.edges.filter(b=>b.strength==="candidate"&&(y.has(b.fromPointId)||y.has(b.toPointId))).length},m}function Rte(e,t){return e.status==="unsupported"?"unsupported":t===1?"matched":t>1?"ambiguous":"missing"}function Ete(e,t){let n=/^(.*):([1-9]\d*)$/u.exec(e);if(!n)throw new Error("A dependence slice requires an exact file:line, with --variable or --column when ambiguous. Use evidence for symbol relationships.");let r=Number(n[2]),i=t.maxDepth??Number.MAX_SAFE_INTEGER,o=t.maxEdges??200;Ite(r,t.column,i,o);let s=t.direction??"backward";if(s!=="backward"&&s!=="forward")throw new Error("Slice direction must be backward or forward.");return{file:n[1],line:r,maxDepth:i,maxEdges:o,direction:s}}function Ite(e,t,n,r){for(let[i,o]of[["line",e],["depth",n],["max-edges",r]])if(!Number.isSafeInteger(o)||o<(i==="line"?1:0))throw new RangeError(`Invalid slice ${i}: ${o}.`);if(t!==void 0&&(!Number.isSafeInteger(t)||t<1))throw new RangeError("Slice column must be a positive safe integer.")}function wte(e,t,n){let r=e.filter(i=>i.line===t-1&&["use","definition","parameter-definition"].includes(i.kind)&&(n.variable===void 0||i.name===n.variable));if(n.column!==void 0){let i=n.column-1;r=r.filter(s=>i>=s.column&&i<s.column+s.end-s.start);let o=Math.min(...r.map(s=>s.end-s.start));r=r.filter(s=>s.end-s.start===o)}return r}function Pte(e,t,n,r){let i=new Map;for(let o of e.edges){if(o.strength!=="exact"||t.get(o.fromPointId)?.callableId!==n||t.get(o.toPointId)?.callableId!==n)continue;let s=r==="backward"?o.toPointId:o.fromPointId,a=i.get(s)??[];a.push(o),i.set(s,a)}return i}function Tte(e,t,n,r){let i=new Set([t]),o=new Map,s=[{id:t,depth:0}],a=new Set;for(let c=0;c<s.length;c++){let l=s[c],u=e.get(l.id)??[];if(l.depth>=r){for(let d of u)a.add(d.id);continue}for(let d of u){o.set(d.id,{...d,traversalDepth:l.depth+1});let m=n==="backward"?d.fromPointId:d.toPointId;i.has(m)||(i.add(m),s.push({id:m,depth:l.depth+1}))}}for(let c of o.keys())a.delete(c);return{selected:o,reached:i,depthFrontier:a}}function Lte(e,t={}){let{scope:n,limit:r}=t,i=new N(e),o=_te(Mte(e,i,n));return Ote(o),r?o.slice(0,r):o}function Mte(e,t,n){let r=[],i=Ate(e);for(let o of Dte(e,n))pP(i,o,o)>0||r.push(...Fte(e,t,o,i));return r}function Dte(e,t){return q(e,{scope:t,includeIgnored:!1}).filter(n=>Zs(e,n).length>0||Ot(e,n).length>0)}function Fte(e,t,n,r){let i=Zs(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>mP(e,t,n,s.sourcePath,r,[kte(s.specifier)])),o=Ot(e,n).filter(s=>s.sourcePath&&!e.isIgnored(s.sourcePath)).flatMap(s=>mP(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 mP(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?L(c.symbol):a,originalFile:r,barrelConsumers:0,directConsumers:pP(i,r,n),...Nte(e,n)}})}function kte(e){return e.split("::").at(-1)?.split("/").at(-1)?.replace(/\.[^.]+$/,"")??e}function Nte(e,t){return fn(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:"signal",surfaceEvidence:[],recommendation:"Review this re-export: no local source importer or re-exporter was resolved. Confirm external consumers and module initialization effects before removal."}}function Ate(e){let t=new Map;for(let n of q(e,{includeIgnored:!1}))for(let r of[...V(e,n),...Zs(e,n),...Ot(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 pP(e,t,n){let r=e.get(t);return r?r.size-(r.has(n)?1:0):0}function _te(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 Ote(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}var Bte=new Set(pa());function $te(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o,maxShapeFrequency:s=12}=t,a=t.semantic!==!1,c=Ute(e,jte(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:a,maxShapeFrequency:s}),l=zte(c);return i?l.slice(0,i):l}function jte(e,t){let n=Pe(e,{scope:t.scope}).filter(r=>Hte(r)&&!e.isIgnored(r.relativePath)).filter(r=>oe(r)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((r,i)=>oe(i)-oe(r)||r.relativePath.localeCompare(i.relativePath)),ge(n,t.scanLimit)}function Hte(e){return!e.isFunctionLike||ke(e.symbol)?!1:e.kind===null||Bte.has(e.kind)}function Ute(e,t,n){let r=rne(e,t,n),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=Gte(s.fn.loc),c=(i.get(s.signature)??0)>n.maxShapeFrequency,l=c?Qm(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 qte(e){return{symbol:e.symbol,shortName:L(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:oe(e)}}function zte(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 Gte(e){return e<=5?"<=5":e<=20?"6-20":">20"}function Kte(e,t,n){if(n.semantic){let o=Fb(e,t);if(o)return o}let r=Wte(t.documentation),i=r?Yte(r):null;return i||Xte(Vte(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function Wte(e){return ia(oa(e))}function Vte(e,t,n,r,i){let o=H(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=nne(s,n,r,i);for(let c of a){let l=ine(s,c);if(l!==null)return l}return null}function Jte(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||ng(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function Yte(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=gP(t),t.length<3)?null:t}function Xte(e,t){if(!e||!e.trim())return null;let n=e.trim(),r=n.indexOf("(");if(r===-1)return null;let i=n.slice(0,r),s=new RegExp(`\\b${Ge(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=tne(n.slice(r)).replace(/\)\s*=\s*[\s\S]*$/,")").replace(/\s+throws\s+[^={]+$/i,"").replace(/\s+where\s+.+$/i,"").trim();if(!a.startsWith("("))return null;let c=gP(`${i?`${i} `:""}${a}`);return c.length>=3?c:null}function Qte(e,t){return e.quote?(e.escaping?e.escaping=!1:t==="\\"?e.escaping=!0:t===e.quote&&(e.quote=null),!0):['"',"'","`"].includes(t)?(e.quote=t,!0):!1}var Zte={"(":["paren",1],")":["paren",-1],"[":["bracket",1],"]":["bracket",-1],"<":["angle",1],">":["angle",-1],"{":["brace",1],"}":["brace",-1]};function ene(e,t,n){let{paren:r,bracket:i,angle:o,brace:s}=n.depths;return r!==0||i!==0||o!==0?!1:e[t]==="{"?!0:e[t]==="="&&e[t+1]===">"&&s===0}function tne(e){let t={depths:{paren:0,brace:0,bracket:0,angle:0},quote:null,escaping:!1};for(let n=0;n<e.length;n+=1){let r=e[n];if(Qte(t,r))continue;if(ene(e,n,t))return e.slice(0,n);let i=Zte[r];if(i){let[o,s]=i;t.depths[o]=Math.max(0,t.depths[o]+s)}}return e}function nne(e,t,n,r){let i=Ge(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)));return fP(e,l,u,o,s,c,a),fP(e,0,e.length-1,o,s,c,a),a}function gP(e){return e.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|\s+/g,t=>/^\s/.test(t)?"":t)}function rne(e,t,n){let r=[];for(let i of t){let o=Kte(e,i,n);o&&r.push({signature:o,definition:i,fn:qte(i)})}return r}function ine(e,t){let n=Math.min(e.length-1,Math.max(t,t+4)),r="";for(let i=t;i<=n;i+=1){let o=e[i]?.trim();if(o&&(r=r?`${r} ${o}`:o,Jte(r)))return r}return r&&r.includes("(")?r:null}function fP(e,t,n,r,i,o,s){for(let a=t;a<=n;a+=1){let c=e[a]??"";(r.test(c)||i.test(c))&&!o.has(a)&&(o.add(a),s.push(a))}}import sne from"path";function hP(e){return{configured:e.configured,boundaries:e.boundaries,coverage:e.coverage,policyCoverage:e.policyCoverage,dependencyRoles:e.dependencyRoles,cycles:e.cycles.map(t=>({boundaries:t.boundaries,origin:t.origin,fileCycleMembers:t.fileCycleMembers,violatesPolicy:t.violatesPolicy}))}}function Os(e,t){return F(e)==="test"||/(^|\/)(fixtures|benchmarks)(\/|$)/.test(e)||(t?.testPaths??[]).some(n=>Ft(n,e))}function Hl(e,t){let n=new Map(e.map(r=>[r,new Set]));for(let r of t)r.resolution==="internal"&&r.target&&n.has(r.target)&&n.get(r.file)?.add(r.target);return n}function Bs(e,t){return e.filter(n=>!Os(n.file,t)&&(!n.target||!Os(n.target,t)))}function one(e){return e.filter(t=>t.kind==="value"&&(t.syntax==="import"||t.syntax==="reexport"))}function yP(e){let t={internal:0,external:0,builtin:0,excluded:0,missing:0,ambiguous:0,dynamic:0};for(let n of e)t[n.resolution]++;return{resolutions:t,typeOnly:e.filter(n=>n.kind==="type").length,test:e.filter(n=>n.role==="test").length,deferredOrCommonJs:e.filter(n=>n.syntax==="dynamic-import"||n.syntax==="require").length,unresolved:e.filter(n=>n.resolution==="missing"||n.resolution==="ambiguous"||n.resolution==="dynamic"),excluded:e.filter(n=>n.resolution==="excluded")}}function bP(e,t){let n=one(t),r=Hl(e,n);return ut(r).components.filter(i=>i.length>1||r.get(i[0])?.has(i[0])).map(i=>{let o=new Set(i),s=n.filter(a=>a.resolution==="internal"&&o.has(a.file)&&a.target&&o.has(a.target));return{id:`dependency-cycle:${$t([...i].sort().join("\0"))}`,rule:"dependency-cycle",evidence:"derived",summary:`${i.length} production files form a circular component of static value imports.`,score:i.length,sites:s.map(a=>({file:a.file,line:a.line})),details:s.map(a=>`${a.file}:${a.line} \u2192 ${a.target} (${a.syntax}, ${a.kind})`)}})}function SP(e,t,n){let r=Bs(t,n),i=il(Hl(e,r),e,n),o=new Map(e.map(a=>[a,Tr(n,a)])),s=i.forbiddenEdges.map(a=>{let c=r.filter(l=>l.resolution==="internal"&&l.target&&o.get(l.file)===a.from&&o.get(l.target)===a.to);return{id:`architecture:${a.from}:${a.to}`,rule:"architecture",evidence:"derived",summary:`${a.from} \u2192 ${a.to}: ${a.fileEdgeCount} production file dependencies violate the declared rule.`,sites:c.flatMap(l=>[{file:l.file,line:l.line},{file:l.target,line:1}]),score:a.fileEdgeCount,details:c.map(l=>`${l.file}:${l.line} \u2192 ${l.target} (${l.kind}, ${l.syntax})`)}});for(let a of i.cycles.filter(c=>c.violatesPolicy)){let c=r.filter(l=>l.resolution==="internal"&&l.target&&a.boundaries.includes(o.get(l.file)??"")&&a.boundaries.includes(o.get(l.target)??""));s.push({id:`architecture:group-cycle:${$t(a.boundaries.join("\0"))}`,rule:"architecture",evidence:"derived",score:a.boundaries.length,summary:`${a.boundaries.length} declared groups violate requireAcyclic (${a.origin}); group identities are retained in architecture.cycles.`,sites:c.map(l=>({file:l.file,line:l.line})),details:[i.dependencyRoles.cycleMeaning,...c.map(l=>`${l.file}:${l.line} \u2192 ${l.target} (${l.kind}, ${l.syntax})`)]})}for(let a of i.boundaryLimits)s.push({id:`architecture:limit:${a.boundary}:${a.kind}`,rule:"architecture",evidence:"derived",score:a.observed,summary:`${a.boundary}: ${a.observed} ${a.kind} exceeds the declared limit ${a.limit}.`,sites:e.filter(c=>o.get(c)===a.boundary).map(c=>({file:c,line:1})),details:["A configured bound is a project rule, not proof that a group has multiple responsibilities."]});if(i.policyCoverage.requiresCompleteCoverage){for(let a of i.coverage.unmappedFiles)s.push({id:`architecture:unmapped:${a}`,rule:"architecture",evidence:"derived",score:1,summary:`${a} has no declared boundary and violates requireCompleteCoverage.`,sites:[{file:a,line:1}],details:[]});for(let a of i.coverage.ambiguousFiles)s.push({id:`architecture:ambiguous:${a.file}`,rule:"architecture",evidence:"derived",score:a.boundaries.length,summary:`${a.file} matches multiple declared boundaries and violates requireCompleteCoverage.`,sites:[{file:a.file,line:1}],details:a.boundaries})}return{rules:i,findings:s}}function vP(e){return e.filter(t=>t.resolution==="missing"||t.resolution==="ambiguous").map(t=>({id:`broken-dependency:${t.file}:${t.specifier}`,rule:"broken-dependency",evidence:"candidate",summary:`${JSON.stringify(t.specifier)} ${t.resolution==="ambiguous"?"has conflicting project resolutions":"does not resolve in the captured internal source"}.`,sites:[{file:t.file,line:t.line}],score:1,details:[`Configuration: ${t.configs.join(", ")||"default compiler resolution"}.`,"Check the import, project configuration, generated files and custom loaders before treating this as a broken build."]}))}function CP(e,t){let n=o=>{let s=new Map;for(let a of o){let c=s.get(a.file)??[];c.push(JSON.stringify([a.specifier,a.target,a.resolution,a.kind,a.role,a.syntax,a.alternatives])),s.set(a.file,c)}return new Map([...s].map(([a,c])=>[a,c.sort().join(`
|
|
336
|
+
`)]))},r=n(e),i=n(t);return[...new Set([...r.keys(),...i.keys()])].filter(o=>r.get(o)!==i.get(o)).sort()}function xP(e){return e.rule==="dependency-cycle"||e.id.startsWith("architecture:group-cycle:")}function kr(e,t){let n={"broken-dependency":0,architecture:1,"dependency-cycle":2,responsibility:3,duplication:4,crap:5,complexity:6};return n[e.rule]-n[t.rule]||t.score-e.score||e.id.localeCompare(t.id)}function RP(e,t,n,r){return ane(e,t,n,r).filter(i=>i.highestPriority!==void 0)}function ane(e,t,n,r){let{groups:i,owners:o}=cne(e,r),{outgoing:s,incoming:a}=lne(t,o,r),c=[...n].filter(u=>u.status!=="resolved"&&!xP(u)).sort(kr),l=new Map(c.map((u,d)=>[u.id,d]));return une(c,i,o),[...i.values()].map(u=>({...u,files:u.files.sort(),consumers:[...a.get(u.id)??[]].sort(),dependencies:[...s.get(u.id)??[]].sort()})).sort((u,d)=>(l.get(u.primaryFindingIds[0])??1/0)-(l.get(d.primaryFindingIds[0])??1/0)||u.id.localeCompare(d.id))}function cne(e,t){let n=new Map,r=new Map;for(let i of e){let o=Tr(t,i),s=o?`boundary:${o}`:`directory:${sne.posix.dirname(i)}`;r.set(i,s),n.has(s)||n.set(s,{id:s,basis:o?"declared-boundary":"directory",files:[],consumers:[],dependencies:[],findingIds:[],primaryFindingIds:[],interpretation:"Grouping identifies declared membership or a shared directory. Review the observed contracts before changing ownership."}),n.get(s).files.push(i)}return{groups:n,owners:r}}function lne(e,t,n){let r=new Map,i=new Map;for(let o of Bs(e,n)){if(o.resolution!=="internal"||!o.target)continue;let s=t.get(o.file),a=t.get(o.target);if(!s||!a||s===a)continue;let c=r.get(s)??new Set;c.add(o.target),r.set(s,c);let l=i.get(a)??new Set;l.add(o.file),i.set(a,l)}return{outgoing:r,incoming:i}}function une(e,t,n){for(let r of e){let i=r.sites.map(o=>n.get(o.file)).find(o=>o!==void 0);i&&t.get(i).primaryFindingIds.push(r.id);for(let o of new Set(r.sites.map(s=>n.get(s.file)).filter(s=>!!s))){let s=t.get(o);s.findingIds.length||(s.highestPriority=r.rule),s.findingIds.push(r.id)}}}function EP(e){let t=e.flatMap(r=>r.consumers),n=[];for(let r of e){if(r.functions.length<4)continue;let i=r.functions[0].fn.file,o=dne(r.functions).map(a=>{let c=a.filter(u=>u.exports.length&&u.fn.tokenCount>=60),l=new Set(c.flatMap(u=>u.exports));return{functions:c,dependencies:[...new Set(a.flatMap(u=>u.dependencies))],consumers:t.filter(u=>u.target===i&&(l.has(u.name)||u.name==="*"))}}).filter(a=>a.functions.length>=2&&a.dependencies.length&&a.consumers.length),s=o.filter(a=>o.every(c=>a===c||!c.consumers.some(l=>a.consumers.some(u=>u.file===l.file))));s.length<2||n.push({id:`responsibility:${i}`,rule:"responsibility",evidence:"candidate",score:s.length,summary:`${i} contains ${s.length} substantial exported function groups with separate observed dependencies and named consumers.`,sites:s.flatMap(a=>a.functions.map(({fn:c})=>({file:i,line:c.startLine,name:c.name}))),details:s.map((a,c)=>`Group ${c+1}: ${a.functions.map(l=>l.fn.name).join(", ")}; dependencies: ${a.dependencies.join(", ")}; named importers: ${a.consumers.map(l=>`${l.file}:${l.line} (${l.name})`).join(", ")}.`).concat(["No shared same-file binding or imported module connects these groups in the covered top-level functions. Nested closures contribute their binding references to their containing function.","A shared public contract can justify keeping these groups together. Classes, indirect re-exports, dynamic consumers, external users and runtime resource identity are not established by this provider. Read those contracts before proposing a split."])})}return n}function dne(e){let t=new Map(e.map((r,i)=>[String(i),new Set])),n=new Map;return e.forEach((r,i)=>{let o=String(i);for(let s of[...[r.declaration,...r.bindings].map(a=>`binding:${a}`),...r.dependencies.map(a=>`import:${a}`)]){let a=n.get(s);a!==void 0?(t.get(o).add(a),t.get(a).add(o)):n.set(s,o)}}),ut(t).components.map(r=>r.map(i=>e[Number(i)]))}import{isDeepStrictEqual as mne}from"util";function IP(e,t,n,r){let{suppressions:i,conflicts:o}=gne(hne(e,t,r)),s={now:Date.now(),contentHash(l){try{return $t(t.files.get(l)??t.project.inputs.get(l)??te(e,l))}catch{return}}},a=i.map(l=>pne(l,n,o,s)),c=new Set(a.filter(l=>l.outcome==="accepted").map(l=>l.id));if(Gb(c.size,n.length))for(let l of a)l.outcome==="accepted"&&(l.outcome="escalated",l.reasons=["Automatic suppression rate requires policy review."]);return a}function pne(e,t,n,r){let i={id:e.id,check:e.check,file:e.file},o=t.find(c=>c.id===e.id&&c.status!=="resolved");if(!o)return{...i,outcome:"unmatched",reasons:["No exact current finding in the requested scope."]};if(n.has(yr(e)))return{...i,outcome:"escalated",reasons:["Conflicting stored/configured suppression records require review."]};let s=fne(e,o);if(s)return{...i,outcome:"escalated",reasons:[s]};let a=Kb(e,{id:o.id,check:o.rule,evidence:o.evidence,actionTier:o.evidence==="derived"?"direct":"signal",file:o.sites[0]?.file,targetFiles:o.sites.map(c=>c.file)},r);return{...i,outcome:a.kind,reasons:a.kind==="accepted"?[]:a.reasons}}function fne(e,t){if(e.check&&e.check!==t.rule||e.file&&!t.sites.some(n=>n.file===e.file))return"Suppression detector/file scope does not match the finding.";if(e.expiresAt&&!Number.isFinite(Date.parse(e.expiresAt)))return"Invalid suppression expiry."}function gne(e){let t=new Map,n=new Set;for(let r of e){let i=yr(r),o=t.get(i);o&&!mne(o,r)?n.add(i):t.set(i,r)}return{suppressions:[...t.values()],conflicts:n}}function hne(e,t,n){let r=[];try{let i=dc(e);r.push(...i.suppressions),n.push(...i.warnings.map(o=>`Suppression storage: ${o}`))}catch(i){n.push(`Suppression storage unavailable: ${i instanceof Error?i.message:String(i)}`)}return[...r,...yne(t,n)]}function yne(e,t){let n=[],r=e.project.inputs.get(".scipquery.json");if(r===void 0)return n;let i=mr(r);if(i.kind==="malformed"||i.kind==="unsupported")return n;let o=i.config.suppressions;if(o!==void 0&&!Array.isArray(o))return t.push(".scipquery.json suppressions must be an array."),n;for(let s of o??[]){let a=$d(s);"error"in a?t.push(`Configured suppression: ${a.error}`):n.push(a.suppression)}return n}function wP(e,t){if(!t)return{files:{},problem:"No source-matched coverage artifact supplied."};try{let n=JSON.parse(eo(e,t).toString("utf8"));return n.schemaVersion!==1||!n.files||typeof n.files!="object"||Array.isArray(n.files)?{files:{},problem:"Expected a version 1 source-matched coverage artifact; use scripts/record-review-coverage.mjs."}:{files:n.files}}catch(n){return{files:{},problem:`Cannot read coverage: ${n instanceof Error?n.message:String(n)}`}}}function PP(e,t,n,r){let i=m=>({status:"unavailable",reason:m});if(r.problem)return i(r.problem);let o=r.files[e.file];if(!o||o.sourceHash!==$t(n))return i("Coverage missing or source hash does not match current bytes.");let{statementMap:s,s:a}=o.coverage??{};if(!k(s)||!k(a))return i("Malformed statement coverage.");let c=bne(s,a,n);if(!c)return i("Malformed statement coverage locations or counts.");let l=Sne(e,t,c);if(l.size===0)return i("No measured executable lines in this function.");let u=[...l.values()].filter(Boolean).length,d=u/l.size;return{status:"available",basis:"istanbul-statement-start-lines",coveredLines:u,measuredLines:l.size,fraction:d,crap:Number((e.cyclomatic**2*(1-d)**3+e.cyclomatic).toFixed(2))}}function bne(e,t,n){let r=[0];for(let o=0;o<n.length;o++)n[o]===`
|
|
337
|
+
`&&r.push(o+1);let i=[];for(let[o,s]of Object.entries(e)){let a=s?.start?.line,c=s?.start?.column,l=t[o];if(!vne(a,c,l,r,n.length))return;i.push({line:a,offset:r[a-1]+c,count:l})}return i}function Sne(e,t,n){let r=t.filter(o=>o!==e&&o.startOffset>e.startOffset&&o.endOffset<=e.endOffset),i=new Map;for(let{line:o,offset:s,count:a}of n)s<e.startOffset||s>=e.endOffset||r.some(c=>s>=c.startOffset&&s<c.endOffset)||i.set(o,(i.get(o)??!1)||a>0);return i}function vne(e,t,n,r,i){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(n)||e<1||e>r.length||t<0||n<0)return!1;let o=r[e-1]+t,s=r[e]??i;return o<s}import{execFileSync as Cne}from"child_process";var Nr={maxFiles:1e4,maxFileBytes:1024*1024},$s=128*1024*1024,xne=[{option:"includeGenerated",reason:"generated",matches:e=>/(^|\/)(__generated__|generated)(\/|$)/.test(e)},{option:"includeReferences",reason:"reference",matches:e=>/^(docs|agent_docs|\.agents|\.claude|\.codex)\/|(^|\/)(vendor|third_party|third-party)(\/|$)/.test(e)},{option:"includeTests",reason:"test",matches:e=>F(e)==="test"||/(^|\/)(fixtures|benchmarks)(\/|$)/.test(e)}];function cf(e,t={}){if(!/\.[cm]?[jt]sx?$/.test(e))return"unsupported-language";if(/\.d\.[cm]?ts$/.test(e))return"declaration";if(ca(e))return"managed-output";for(let n of xne)if(!t[n.option]&&n.matches(e))return n.reason}function LP(e,t={}){NP(t);let n=kP(e);return FP("working-tree",n,t,r=>eo(e,r,{maxBytes:t.maxFileBytes??Nr.maxFileBytes}).toString("utf8"))}function Rne(e,t){return Yi(e,["rev-parse","--verify","--end-of-options",`${t}^{commit}`]).toString("utf8").trim()}function MP(e,t,n={}){NP(n);let r=Rne(e,t),i=Yi(e,["ls-tree","-r","-z",r]).toString("utf8").split("\0").filter(Boolean),o=new Map;for(let l of i){let u=/^(100\d+) blob ([a-f0-9]+)\t([\s\S]+)$/.exec(l);u&&o.set(u[3],u[2])}let s=[...o.keys()].filter(l=>!cf(l,n)).sort().slice(0,n.maxFiles??Nr.maxFiles),a=new Map,c=0;for(let l=0;l<s.length;l+=32){let u=s.slice(l,l+32),{readable:d,output:m}=Ene(e,u,o,n.maxFileBytes??Nr.maxFileBytes);if(d.length!==0){if(c+=m.length,c>$s)break;Ine(d,m,a)}}return FP(r,[...o.keys()],n,l=>{let u=a.get(l);if(u!==void 0)return u;let d=o.get(l);if(l.endsWith(".json")&&d){if(Number(Yi(e,["cat-file","-s",d]).toString("utf8").trim())>(n.maxFileBytes??Nr.maxFileBytes))throw new Error("configuration exceeds file byte limit");return Yi(e,["cat-file","blob",d]).toString("utf8")}throw new Error("omitted by the Git source snapshot file/total byte limits")})}function Ene(e,t,n,r){let i=Yi(e,["cat-file","--batch-check"],t.map(a=>n.get(a)).join(`
|
|
338
|
+
`)+`
|
|
339
|
+
`).toString("utf8").trim().split(`
|
|
340
|
+
`),o=t.filter((a,c)=>Number(i[c]?.split(" ")[2])<=r);if(o.length===0)return{readable:o,output:Buffer.alloc(0)};let s=Yi(e,["cat-file","--batch"],o.map(a=>n.get(a)).join(`
|
|
341
|
+
`)+`
|
|
342
|
+
`);return{readable:o,output:s}}function Ine(e,t,n){let r=0;for(let i of e){let o=t.indexOf(10,r),s=Number(t.subarray(r,o).toString("utf8").split(" ")[2]);if(o<0||!Number.isSafeInteger(s)||s<0||o+1+s>t.length)throw new Error("Invalid Git blob response while reading review base");n.set(i,t.subarray(o+1,o+1+s).toString("utf8")),r=o+1+s+1}}function DP(e,t,n={}){let r=kP(e),i=r.filter(s=>!cf(s,n)).sort(),o=[];(i.length!==t.eligibleFiles||i.slice(0,n.maxFiles??Nr.maxFiles).some(s=>!t.files.has(s)))&&o.push("Eligible source file set changed or was incomplete during analysis; rerun after edits settle."),TP(r).join(`
|
|
343
|
+
`)!==TP([...t.project.inventory]).join(`
|
|
344
|
+
`)&&o.push("Project configuration file set changed during analysis; rerun after edits settle.");for(let[s,a]of[...t.files,...t.project.inputs])try{eo(e,s,{maxBytes:n.maxFileBytes??Nr.maxFileBytes}).toString("utf8")!==a&&o.push(`${s}: source changed during analysis; rerun after edits settle.`)}catch{o.push(`${s}: source unavailable during final freshness check.`)}return o}function FP(e,t,n,r){let i={},o=t.filter(d=>{let m=cf(d,n);return m&&(i[m]=(i[m]??0)+1),!m}).sort(),s=new Map,a=[],c=o.slice(0,n.maxFiles??Nr.maxFiles);c.length<o.length&&a.push(`${o.length-c.length} eligible files omitted by max-files; increase --max-files to cover them.`);let l=0;for(let d of c)try{let m=r(d);if(l+=Buffer.byteLength(m),l>$s){a.push(`Snapshot exceeds ${$s} bytes; ${c.length-s.size} remaining files omitted.`);break}s.set(d,m)}catch(m){a.push(`${d}: ${m instanceof Error?m.message:String(m)}`)}let u=nl(t,o,d=>{let m=r(d);if(l+=Buffer.byteLength(m),l>$s)throw new Error("source and configuration snapshot exceeds total byte limit");return m});return{revision:e,files:s,fingerprint:$t([...s,...u.inputs].sort(([d],[m])=>d.localeCompare(m)).map(([d,m])=>`${JSON.stringify(d)}:${$t(m)}`).join(`
|
|
345
|
+
`)),eligibleFiles:o.length,excludedFiles:t.length-o.length,exclusions:i,project:u,problems:a}}function TP(e){return e.filter(t=>/(^|\/)((ts|js)config[^/]*\.json|package\.json|\.scipquery\.json)$/.test(t)).sort()}function Yi(e,t,n){return Cne("git",t,{cwd:e,input:n,maxBuffer:$s,timeout:3e4,stdio:["pipe","pipe","pipe"]})}function kP(e){return Br(e).filter(t=>{try{return Ae(e,t)}catch{return!0}})}function NP(e){for(let t of["maxFiles","maxFileBytes"]){let n=e[t];if(n!==void 0&&(!Number.isSafeInteger(n)||n<1))throw new Error(`${t} must be a positive safe integer.`)}}var AP=[`TS/JS implemented functions; metric rules ${fa}. Cognitive counts structural nesting and logical sequences; recursion and interprocedural behavior are not measured.`,"Duplication compares whole function body tokens (at least 60 tokens), retaining literals and property names. Renamed local bindings are candidates; similarity does not prove interchangeable behavior or justify deletion.","Dependencies use compiler resolution over captured source and project configuration, including aliases, repository package exports, literal dynamic imports and unshadowed CommonJS calls. External packages, excluded targets and unresolved imports are distinguished. Production file cycles use static value imports; type/test/deferred relationships remain separate. Runtime handoffs and custom loaders are not inferred.","Ownership and mixed responsibilities require evidence about callers, state and business rules; this scan does not infer a correct owner or an architectural grade."];function lf(e,t={files:{},problem:"No source-matched coverage supplied."},n){n??=e.project.architecture;let r=[],i=[],o=[],s=[],a=[...e.problems];for(let[m,p]of e.files){let f=ot(m,p);if(a.push(...f.errors),f.errors.length>0)continue;i.push(...f.exports),r.push(...f.functions.map(h=>({...h,coverage:PP(h,f.functions,p,t)})));let g=qm(f.sourceFile,e.files,e.project,f.checker);for(let h of g)h.role=Os(m,n)?"test":"production";o.push(...g),Os(m,n)||s.push(rC(f,g))}let c=[...e.files.keys()],l=Hl(c,o),u=SP(c,o,n),d=[...wne(r),...Pne(r),...bP(c,Bs(o,n)),...u.findings,...vP(o),...EP(s)];return{functions:r,exports:i,findings:d.sort(kr),imports:o,graph:l,problems:a,architecture:u.rules}}function wne(e){let t=[];for(let n of e){let r={file:n.file,line:n.startLine,name:n.name};(n.cyclomatic>10||n.cognitive>15)&&t.push({id:`complexity:${n.file}:${n.name}`,rule:"complexity",evidence:"derived",summary:`${n.name}: cyclomatic ${n.cyclomatic}, cognitive ${n.cognitive}.`,sites:[r],score:Math.max(n.cyclomatic/10,n.cognitive/15),details:["Review branching and nesting while preserving decisions, effects, and error handling.",...n.contributions.filter(i=>i.cognitive>1).map(i=>`${n.file}:${i.line}:${i.column} ${i.kind}: +${i.cognitive} cognitive`)]}),n.coverage.status==="available"&&n.coverage.crap>=30&&t.push({id:`crap:${n.file}:${n.name}`,rule:"crap",evidence:"derived",score:n.coverage.crap,sites:[r],summary:`${n.name}: CRAP ${n.coverage.crap}, measured line coverage ${Math.round(n.coverage.fraction*100)}%.`,details:["CRAP = cyclomatic\xB2 \xD7 (1 \u2212 measured coverage)\xB3 + cyclomatic. Improve tests and simplify behavior where justified."]})}return t}function Pne(e){let t=new Map;for(let n of e){if(n.tokenCount<60)continue;let r=n.renamedBodyHash,i=t.get(r)??[];i.push(n),t.set(r,i)}return[...t.values()].filter(n=>n.length>1).map(n=>{let r=new Set(n.map(o=>o.bodyHash)).size===1,i=n.map(o=>({file:o.file,line:o.startLine,name:o.name}));return{id:`duplication:${n[0].renamedBodyHash}`,rule:"duplication",evidence:"candidate",summary:`${n.length} functions share ${r?"identical body tokens":"body tokens after local binding renaming"}.`,sites:i,score:n.length,details:[`${n[0].tokenCount} tokens per body; comments and whitespace excluded; literals retained.`,"Read both contracts and callers. If these implementations own the same rule, reuse one owner; otherwise retain the separate responsibilities."]}})}function Tne(e,t={}){let{current:n,coverageInput:r,analysis:i,base:o,before:s,changedFiles:a,configurationChanges:c,relationshipChangedFiles:l,problems:u,scope:d,inScope:m,sourceComparable:p,changed:f,functionChanges:g}=Mne(e,t),h=(s?g.flatMap(R=>R.after?[R.after]:[]):i.functions).filter(R=>m(R.file)),y=Nne(h,!!t.coverage,r.problem),I=kne(s,i,f,p,!n.project.problems.length&&!o?.project.problems.length).filter(R=>!d||R.sites.some(P=>m(P.file))).sort(kr),x=RP([...n.files.keys()],i.imports,I,t.architecture??n.project.architecture),E=yP(i.imports);Lne(y,E,u);let b=IP(e,n,I,u),v=new Set(b.filter(R=>R.outcome==="accepted").map(R=>R.id)),C=I.filter(R=>R.evidence==="derived"&&!v.has(R.id)&&(!o||R.status==="introduced"||R.status==="worsened")).map(R=>R.id);return{mode:o?"review":"health",...o?{base:o.revision}:{},current:n.fingerprint,metricRules:"typescript-function-local-v1",changedFiles:a.filter(m),configurationChanges:c,relationshipChangedFiles:l.filter(m),architecture:hP(i.architecture),functions:g.filter(R=>m((R.after??R.before).file)).map(R=>p?R:{status:"uncomparable",before:R.before,after:R.after}),findings:I,suppressionDecisions:b,blockingFindingIds:C,modules:x,affectedFiles:Fne(s,i,a,l,m),coverage:{status:u.length?"incomplete":"accounted",analyzedFiles:n.files.size,eligibleFiles:n.eligibleFiles,excludedFiles:n.excludedFiles,exclusions:n.exclusions,dependencies:E,analyzedFunctions:i.functions.length,unresolvedImports:E.resolutions.missing+E.resolutions.ambiguous,testCoverage:y,problems:u,limits:[...AP,"Default exclusions: tests/fixtures/benchmarks, reference/vendor copies, generated files, declarations and build output. Use --include-tests, --include-references or --include-generated for the corresponding source roles.","Diff is the selected Git commit versus current files, including untracked files; staged-only review and inferred rename/split identity are not claimed.","Coverage without matching source hashes is unavailable, never zero. Base CRAP is unavailable unless independently measured against that base.","Affected files are transitive importers in the covered source graph. Use fresh diff-impact/evidence for symbol consumers and runtime effects."]}}}function Lne(e,t,n){e.requested&&e.reasons.length&&n.push(`Requested test coverage is incomplete: ${e.reasons.join("; ")}`),(t.resolutions.missing||t.resolutions.ambiguous)&&n.push(`${t.resolutions.missing} internal imports unresolved; ${t.resolutions.ambiguous} ambiguous. Inspect coverage.dependencies.unresolved or scoped findings.`)}function Mne(e,t){let n=LP(e,t),r=wP(e,t.coverage),i=lf(n,r,t.architecture),o=t.base===void 0?void 0:MP(e,t.base,t),s=o?lf(o,void 0,t.architecture):void 0,{changedFiles:a,configurationChanges:c,relationshipChangedFiles:l,changed:u,files:d,functionChanges:m}=Dne(n,o,s,i,t.architecture),p=[...i.problems,...s?.problems.map(y=>`base: ${y}`)??[],...DP(e,n,t)],f=t.scope?.replaceAll("\\","/").replace(/^\.\//,"").replace(/\/$/,""),g=y=>!f||f==="."||y===f||y.startsWith(f+"/");f&&!d.some(g)&&p.push(`Scope ${JSON.stringify(f)} matches no analyzed source file; check the path and exclusions.`);let h=p.length===0;return p.push(...n.project.problems,...o?.project.problems.map(y=>`base: ${y}`)??[]),{current:n,coverageInput:r,analysis:i,base:o,before:s,changedFiles:a,configurationChanges:c,relationshipChangedFiles:l,problems:p,scope:f,inScope:g,sourceComparable:h,changed:u,functionChanges:m}}function Dne(e,t,n,r,i){let o=_P(t?.files,e.files),s=_P(t?.project.inputs,e.project.inputs),a=n?CP(n.imports,r.imports):[],c=t&&JSON.stringify(i??t.project.architecture)!==JSON.stringify(i??e.project.architecture),l=[...new Set([...e.files.keys(),...t?.files.keys()??[]])],u=new Set([...o,...a]);if(c)for(let m of l)u.add(m);let d=n?Ane(n.functions,r.functions):[];return{changedFiles:o,configurationChanges:s,relationshipChangedFiles:a,changed:u,files:l,functionChanges:d}}function Fne(e,t,n,r,i){return e?[...new Set([...r.filter(o=>i(o)&&!n.includes(o)),...OP(e.graph,new Set([...n,...r].filter(i))),...OP(t.graph,new Set([...n,...r].filter(i)))])].sort():[]}function _P(e,t){return e?[...new Set([...e.keys(),...t.keys()])].filter(n=>e.get(n)!==t.get(n)).sort():[]}function kne(e,t,n,r,i){let o=e?One(e,t,n,r,i):t.findings;if(e)for(let s of Hne(e,t,n,r&&i)){let a=o.findIndex(c=>c.id===s.id);a>=0?o[a]=s:o.push(s)}return o}function Nne(e,t,n){let r=0,i=new Set;for(let o of e)o.coverage.status==="available"?r++:i.add(o.coverage.reason);return t&&n&&i.add(n),{requested:t,available:r,unavailable:e.length-r,reasons:[...i]}}function Ane(e,t){let n=a=>`${a.file}:${a.name}`,r=a=>{let c=new Map;for(let l of a)c.set(n(l),[...c.get(n(l))??[],l]);return c},i=r(e),o=r(t),s=[];for(let a of[...new Set([...i.keys(),...o.keys()])].sort()){let c=i.get(a)??[],l=o.get(a)??[];s.push(..._ne(c,l))}return s}function _ne(e,t){let n=[];return e.length>1||t.length>1?e.map(r=>r.sourceHash).join()!==t.map(r=>r.sourceHash).join()&&n.push(...e.map(r=>({status:"uncomparable",before:r})),...t.map(r=>({status:"uncomparable",after:r}))):e[0]&&t[0]?e[0].sourceHash!==t[0].sourceHash&&n.push({status:"modified",before:e[0],after:t[0],delta:{cyclomatic:t[0].cyclomatic-e[0].cyclomatic,cognitive:t[0].cognitive-e[0].cognitive}}):t[0]?n.push({status:"added",after:t[0]}):e[0]&&n.push({status:"removed",before:e[0]}),n}function One(e,t,n,r,i=!0){let o=new Map(e.findings.map(u=>[u.id,u])),s=new Map(t.findings.map(u=>[u.id,u])),a=[],c=jne(e.functions,t.functions),l=$ne(e.functions,t.functions);for(let u of t.findings){if(u.sites.length&&!u.sites.some(p=>n.has(p.file)))continue;let d=o.get(u.id),m=Bne(u,d,r,i,c,l);a.push({...u,status:m})}for(let u of e.findings)!s.has(u.id)&&u.sites.some(d=>n.has(d.file))&&a.push({...u,status:r&&(i||!["architecture","dependency-cycle","broken-dependency","responsibility"].includes(u.rule))?"resolved":"uncomparable"});return a}function Bne(e,t,n,r,i,o){let s="existing";return!n||e.rule==="crap"||!r&&["architecture","dependency-cycle","broken-dependency","responsibility"].includes(e.rule)||e.sites.some(a=>i.has(`${a.file}:${a.name}`))?s="uncomparable":t?(e.score>t.score||o.has(e.id))&&(s="worsened"):s="introduced",s}function $ne(e,t){let n=new Map(e.map(i=>[`complexity:${i.file}:${i.name}`,i])),r=new Set;for(let i of t){let o=`complexity:${i.file}:${i.name}`,s=n.get(o);s&&(i.cyclomatic>s.cyclomatic||i.cognitive>s.cognitive)&&r.add(o)}return r}function jne(e,t){let n=o=>{let s=new Map;for(let a of o){let c=`${a.file}:${a.name}`;s.set(c,(s.get(c)??0)+1)}return s},r=n(e),i=n(t);return new Set([...r.keys(),...i.keys()].filter(o=>(r.get(o)??0)>1||(i.get(o)??0)>1))}function Hne(e,t,n,r){let i=new Map(e.imports.map(s=>[`${s.file}:${s.specifier}`,s])),o=[];for(let s of t.imports){if(s.target)continue;let a=i.get(`${s.file}:${s.specifier}`);!a?.target||!n.has(a.target)||t.graph.has(a.target)||o.push({id:`broken-dependency:${s.file}:${s.specifier}`,rule:"broken-dependency",evidence:"derived",status:r?"introduced":"uncomparable",summary:"An unchanged import still refers to a removed source file.",sites:[{file:s.file,line:s.line},{file:a.target,line:1}],score:1,details:[`${s.specifier} resolved to ${a.target} at the base commit and no longer resolves in current source.`]})}return o}function OP(e,t){let n=new Map;for(let[o,s]of e)for(let a of s){let c=n.get(a)??new Set;c.add(o),n.set(a,c)}let r=new Set(t),i=[...t];for(let o=0;o<i.length;o++)for(let s of n.get(i[o])??[])r.has(s)||(r.add(s),i.push(s));return[...r].filter(o=>!t.has(o)).sort()}async function BP(e,t,n={}){let r=Math.max(1,Math.floor(n.batchSize??64)),i=n.collectGarbage??ao,o=[],s=0;for(let a=0;a<t.length;a+=r){for(let c of t.slice(a,a+r)){for(let l of D(e,c))e.isIgnored(l.relativePath)||o.push(l);ug(e,c),Ot(e,c),sg(e,c),s+=1}n.onBatch?.({files:s,total:t.length,definitions:o.length}),i(),await n.yieldToEventLoop?.()}return{files:s,definitions:o}}import{spawnSync as EMe}from"child_process";import{execFileSync as YLe}from"child_process";import{createHash as QLe}from"crypto";import{lstatSync as eMe,readlinkSync as tMe,realpathSync as nMe,statSync as rMe}from"fs";import{dirname as oMe,isAbsolute as sMe,join as aMe,posix as cMe,relative as lMe,resolve as uMe,sep as dMe}from"path";var pMe=512*1024*1024;function $P(e){return or({version:e.version,...e.base?{base:e.base}:{},files:[...e.files].sort((t,n)=>t.path.localeCompare(n.path))})}function uf(e){return JSON.stringify({...e.clojureConfigPath?{clojureConfigPath:e.clojureConfigPath}:{},files:[...e.files].sort((t,n)=>t.path.localeCompare(n.path)).map(t=>({hash:t.hash,path:t.path,size:t.size})),languages:[...e.languages].sort(),pnpmWorkspaces:e.pnpmWorkspaces,typescriptProjectMode:e.typescriptProjectMode,typescriptProjects:[...e.typescriptProjects].sort(),version:e.version})}var qne="scip-query:collaboration-domain",zne="scip-query:workspace-instance",Gne="scip-query:index-generation",Kne="scip-query:repository-content",jP="scip-query:index-inputs",Wne="scip-query:index-inputs";function Ar(e){let t=e.snapshot,n=e.observedSourceKinds?new Set(e.observedSourceKinds):void 0,r=e.gitContext??t?.gitContext??(n?.has("live-workspace")?Ql(e.projectRoot):void 0),i=Vne(e,r),o=n??Jne(i),s=Yne(i,o);return{schemaVersion:An,observedAt:(e.observedAt??(t?new Date(t.capturedAt):new Date)).toISOString(),facts:i,...s,...r?{diagnostics:Xne(r)}:{}}}function Vne(e,t){let n={},r=e.collaborationDomainId??e.db?.config.collaborationDomainId;if(r&&(n.collaborationDomain=fr(qne,1,r)),t&&(n.workspaceInstance=fr(zne,1,t.worktreeId)),e.snapshot&&(n.wholeContent=fr(Kne,1,$P(e.snapshot.repositoryContent)),n.relevantInputs=[{subject:Wne,identity:fr(jP,e.snapshot.indexInputs.version,uf(e.snapshot.indexInputs))}]),e.db){let i=e.snapshot?Zne(e.db.generation.metadataRaw):void 0;n.index={generation:fr(Gne,1,e.db.generation.identity),...i?{inputs:i}:{},source:e.db.generation.source}}return n}function Jne(e){let t=new Set;return e.index&&t.add("index-generation"),e.wholeContent?t.add("repository-snapshot"):e.workspaceInstance&&t.add("live-workspace"),t}function Yne(e,t){let n=[],r=[],i=(o,s)=>{n.push(o),r.push({source:o.kind,kind:s})};return e.index&&t.has("index-generation")&&i({kind:"index-generation",identity:e.index.generation},e.index.source==="immutable"?"immutable":"not-established"),e.wholeContent&&t.has("repository-snapshot")&&i({kind:"repository-snapshot",identity:e.wholeContent},"fixed-snapshot"),e.workspaceInstance&&t.has("live-workspace")&&i({kind:"live-workspace",identity:e.workspaceInstance},"not-established"),t.has("process")&&i({kind:"process"},"not-established"),n.length===0&&i({kind:"process"},"not-established"),{observedSources:n,stabilityProofs:r}}function Xne(e){return{clean:e.clean,...e.headCommit?{headCommit:e.headCommit}:{},...e.treeOid?{treeOid:e.treeOid}:{}}}function Qne(e){return Ar({projectRoot:e.projectRoot,db:e.db,...e.gitContext?{gitContext:e.gitContext}:{},...e.observedAt?{observedAt:e.observedAt}:{},observedSourceKinds:["index-generation"]})}function CMe(){let e=pc();if(!e)return Ar({projectRoot:mc(),observedSourceKinds:["process"]});let t=e.config.projectRoot,n=Ql(t);return Qne({projectRoot:t,db:e,...n?{gitContext:n}:{}})}function Zne(e){if(!e)return;let t=to(e);if(t.kind!=="legacy"&&t.kind!=="supported")return;let n=Zi(t.metadata.fingerprint);return n&&Number.isSafeInteger(n.version)&&n.version>0?fr(jP,n.version,uf(n)):void 0}var mf="scip-query-isolated-analysis",pf=1;function ere(e){let t=[...e??[]];return t.includes("--json")?t:["--json",...t]}var nn=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 FMe(e,t){let n=pc(),r={protocol:mf,schemaVersion:pf,producer:{name:"scip-query",version:Zn},command:e,result:t,...n?{observationReceipt:Ar({projectRoot:n.config.projectRoot,db:n,observedSourceKinds:["index-generation"]})}:{}};zd(JSON.stringify(r))}function js(e){let t=e.timeoutMs??sh.analysis,n=e.maxBuffer??10*1024*1024;return ch({command:process.execPath,args:[...process.execArgv,e.cliPath,e.command,...ere(e.args)],cwd:process.cwd(),env:e.env??process.env,label:e.label,timeoutMs:t,maxStdoutBytes:n,maxStderrBytes:n}).catch(r=>{throw r instanceof ah&&r.kind==="timeout"?new nn(e.label,t,r.reaped):r}).then(r=>{let i=r.stderr.trim();if(r.status!==0)throw new Error(`${e.label} failed${i?`:
|
|
346
|
+
${i}`:""}`);return tre(r.stdout,e)})}function tre(e,t){let n;try{n=JSON.parse(e)}catch(i){throw new Error(`${t.label} returned invalid JSON: ${i instanceof Error?i.message:i}`,{cause:i})}if(!k(n))throw new Error(`${t.label} returned a non-object isolated-analysis message.`);nre(n,t);let r=n.observationReceipt;if(r!==void 0&&(!tc(r)||r.schemaVersion!==2))throw new Error(`${t.label} returned an invalid observation receipt.`);return{result:n.result,...r?{observationReceipt:r}:{}}}function df(e){return typeof e=="string"?JSON.stringify(e):String(e)}async function Ul(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 HP(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}function nre(e,t){if(e.protocol!==mf)throw new Error(`${t.label} returned protocol ${df(e.protocol)}; expected ${mf}.`);if(e.schemaVersion!==pf)throw new Error(`${t.label} returned unsupported isolated-analysis schemaVersion ${df(e.schemaVersion)}; expected ${pf}.`);if(!Uf(e.producer))throw new Error(`${t.label} did not identify a scip-query producer version.`);if(e.command!==t.command)throw new Error(`${t.label} returned result for command ${df(e.command)}; expected ${t.command}.`);if(!Object.hasOwn(e,"result"))throw new Error(`${t.label} omitted the isolated-analysis result.`)}import{spawnSync as rre}from"child_process";import{existsSync as ire,mkdirSync as ore,renameSync as sre,writeFileSync as are}from"fs";import{dirname as qP,join as cre}from"path";var ql=14,lre="health-report-cache.json";function ff(e,t,n,r=pre()){let i=nt(e);return i?{version:ql,projectFingerprint:i,cliVersion:n,scope:t.scope??null,full:t.full===!0,phaseTimeoutMs:t.phaseTimeoutMs??null,gitHead:r.gitHead(e.config.projectRoot),buildIdentity:(r.buildIdentity??Af)()}:null}function zP(e,t,n=VP()){let r=KP(e),i=WP(t),o=!1;return M("health.report-cache.read",()=>{if(!n.existsSync(r))return null;try{let s=JSON.parse(n.readFile(r));return!ure(s)||s.keyHash!==i?null:(o=!0,s.report)}catch{return null}},()=>({available:!0,hit:o,keyHash:i}))}function GP(e,t,n,r=VP()){let i=KP(e),o={version:ql,keyHash:WP(t),key:t,writtenAt:r.nowIso(),report:n};r.mkdirSync(qP(i),{recursive:!0});let s=`${i}.${process.pid}.${Date.now()}.tmp`;r.writeFileSync(s,JSON.stringify(o)),r.renameSync(s,i)}function KP(e){return cre(qP(e.config.dbPath),lre)}function WP(e){return At(JSON.stringify(e))}function ure(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===ql&&typeof t.keyHash=="string"&&dre(t.key)&&typeof t.writtenAt=="string"&&mre(t.report)}function dre(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===ql&&typeof t.projectFingerprint=="string"&&typeof t.cliVersion=="string"&&UP(t.scope)&&typeof t.full=="boolean"&&fre(t.phaseTimeoutMs)&&UP(t.gitHead)&&typeof t.buildIdentity=="string"}function mre(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.overview=="object"&&typeof t.findings=="object"&&Array.isArray(t.actions)&&Array.isArray(t.detectorEvidence)}function pre(){return{gitHead(e){let t=rre("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:3e4,killSignal:"SIGKILL"});return t.status===0?t.stdout.trim():null}}}function VP(){return{existsSync:ire,mkdirSync:ore,readFile:e=>Ye(e,"health report cache"),renameSync:sre,writeFileSync:are,nowIso:()=>new Date().toISOString()}}function UP(e){return e===null||typeof e=="string"}function fre(e){return e===null||typeof e=="number"}var eT="__health-phase",hre="__health-semantic-prewarm",yre="__diff-impact-batch",bre=128,Sre=1,vre=1,Cre=6144,xre=2048,Rre=10*6e4,Ere=25e3,Ire=2500,gf=2500,wre=4,Pre=12,Tre=1,Lre=4,Mre=7*1024*1024*1024,Dre=6144,Fre=10*6e4,kre=3e4,Nre=16384,Are=2048,_re=10*6e4,tT=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),nT=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]),Ore=new Set([...nT,"suppressions"]),Bre=new Set(["similar"]),Us=2,hf=er({kind:"health-semantic-prewarm",invalidation:Re("health-semantic-prewarm"),serialize:e=>JSON.stringify(e),deserialize:$re});function $re(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return n.version!==Us||!Hs(n.definitions)||!Hs(n.referenceCacheWrites)||!Hs(n.referenceIncomplete)||!Hs(n.calleeRows)||!Hs(n.warmedAt)?null:{version:Us,definitions:n.definitions,referenceCacheWrites:n.referenceCacheWrites,referenceIncomplete:n.referenceIncomplete,calleeRows:n.calleeRows,warmedAt:n.warmedAt}}catch{return null}}function Hs(e){return typeof e=="number"&&Number.isFinite(e)}function jre(e,t){return!t||t.count<=1?[...e]:e.filter((n,r)=>r%t.count===t.index)}function pDe(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
|
|
347
|
+
`)}function Hre(e){let t=Wo(e);return t.symbols>=Ere||t.documents>=Ire}function fDe(e,t,n,r={}){if(!Hre(e))return{semantic:!0};if(n)return t==="dead"?(r.quiet||console.error("Large index detected; dead is scanning all candidates with semantic enrichment disabled to keep memory bounded."),{semantic:!1}):(r.quiet||console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0});if(!r.quiet){let i=Die(t);console.error(`Large index detected; ${t} is using its bounded default analysis with semantic enrichment disabled. Candidate scans, when this command uses one, are capped at ${gf}. `+i)}return{scanLimit:gf,semantic:!1,analysisBudget:{scanLimit:gf,semanticEnrichment:!1,reason:t==="dead"?"large index default budget; pass --full for an unbounded memory-safe candidate scan":"large index default budget; pass --full for unbounded semantic analysis"}}}var Ure={env:process.env,projectFingerprint:nt,semanticEngineFingerprint:iT,readMarker:(e,t,n)=>hf.read(e,t,n),writeMarker:(e,t,n,r)=>hf.write(e,t,n,r),projectFiles:(e,t)=>jre(q(e,{scope:t.scope,includeIgnored:!1}),t.shard),candidateDefinitions:async(e,t,n)=>{let r=await BP(e,n,{collectGarbage:ao,yieldToEventLoop:()=>new Promise(a=>setImmediate(a))}),i=new Set(n),o=new Set(r.definitions.map(a=>a.symbolId)),s=[];for(let a of[{},{requireCallableSymbol:!0},{requireFunctionLikeSymbol:!0}])for(let c of bc(e,{...a,scope:t.scope}))!i.has(c.relativePath)||o.has(c.symbolId)||(o.add(c.symbolId),s.push(c));return[...r.definitions,...s].filter(a=>Se(a.relativePath)!==null)},warmReferenceFragments:(e,t,n)=>Kg(e,r=>un(e,r),{onBatch:t,...n?{files:n}:{}}),materializeReferences:(e,t,n)=>Gt(e).materializeReferences(t,n),materializeCallees:Id,releaseSemanticMemory:e=>no(e,{groups:["semantic-provider"]}),heapUsedFraction:()=>{let e=gre();return e.heap_size_limit>0?e.used_heap_size/e.heap_size_limit:0},collectGarbage:ao,yieldToEventLoop:()=>new Promise(e=>setImmediate(e))},qre=256,zre=.75;function JP(e,t=qre){if(!Number.isSafeInteger(t)||t<1)throw new Error(`Prewarm batch size must be a positive safe integer; received ${t}.`);let n=new Map;for(let s of e){let a=n.get(s.relativePath);a?a.push(s):n.set(s.relativePath,[s])}let r=[],i=[],o=0;for(let s of n.values())o>=t&&(r.push(i),i=[],o=0),i.push(...s),o+=1;return i.length>0&&r.push(i),r}async function gDe(e,t,n=Ure){if(t.full!==!0)return Kn("default-mode");if((n.env??process.env).SCIP_QUERY_HEALTH_SEMANTIC_PREWARM==="0")return Kn("disabled");let r=Kn("error");return qr("health.semantic-prewarm",async()=>{try{r=await Wre(e,t,n)}catch(i){r=Kn("error",{error:i instanceof Error?i.message:String(i)})}return r},()=>Vre(r))}function Gre(e,t){let n=0,r=0,i=()=>(t.heapUsedFraction?.()??0)>=zre;return{relieve({release:o}){i()&&(t.collectGarbage?.()&&(n+=1,!i())||o&&(t.releaseSemanticMemory?.(e),r+=1))},get collections(){return n},get releases(){return r}}}function Kre(e,t){e.definitions+=t.definitions,e.cacheHits+=t.cacheHits,e.cacheWrites+=t.cacheWrites,e.inMemoryHits+=t.inMemoryHits,e.misses+=t.misses,e.unkeyed+=t.unkeyed,e.incomplete+=t.incomplete}async function Wre(e,t,n){let r=n.projectFingerprint(e);if(!r)return Kn("missing-project-fingerprint");let i=rT(t,n.semanticEngineFingerprint(e)),o=n.readMarker(e,i,r);if(o&&o.referenceIncomplete===0)return Kn("cache-hit");let s=n.projectFiles(e,t),a=[];if(a=await qr("health.semantic-prewarm.candidate-definitions",async()=>(a=await n.candidateDefinitions(e,t,s),a),()=>({definitions:a.length,files:s.length,shard:t.shard??null})),a.length===0)return Kn("no-semantic-definitions");let c=Gre(e,n),l=async()=>{await n.yieldToEventLoop?.()},u=a.filter(S=>Se(S.relativePath)==="typescript"),d=null;if(u.length>0){let S=null;d=await qr("health.semantic-prewarm.reference-fragments",async()=>(S=await n.warmReferenceFragments(e,()=>c.relieve({release:!0}),s),S),()=>({definitions:u.length,rows:S?.computedFiles??0,files:S?.files??0,cacheHits:S?.cacheHits??0,available:S!==null}))}let m=d?a.filter(S=>Se(S.relativePath)!=="typescript"):a,p={definitions:0,cacheHits:0,cacheWrites:0,inMemoryHits:0,misses:0,unkeyed:0,incomplete:0},f=0;await qr("health.semantic-prewarm.references",async()=>{for(let S of JP(m))Kre(p,n.materializeReferences(e,S,{prefetchCallees:!1})),c.relieve({release:!0}),await l();f=p.cacheHits+p.cacheWrites+p.inMemoryHits},()=>({definitions:m.length,rows:f,releases:c.releases}));let g=d?u.length:0;if(f+g===0&&p.misses+p.unkeyed>0)return Kn("provider-unavailable",{definitions:a.length,referenceMisses:p.misses});M("health.semantic-prewarm.release-reference-memory",()=>n.releaseSemanticMemory?.(e));let h=0,y=c.releases;return await qr("health.semantic-prewarm.callees",async()=>{for(let S of JP(a))h+=n.materializeCallees(e,S).size,c.relieve({release:!0}),await l()},()=>({definitions:a.length,rows:h,releases:c.releases-y,collections:c.collections})),Fie({db:e,opts:t,runtime:n,cacheKey:i,fingerprint:r,definitionCount:a.length,warmedFiles:s.length,references:p,fragments:d,calleeRows:h})}function rT(e,t){return JSON.stringify({version:Us,cliVersion:Zn,semanticEngineFingerprint:t,scope:e.scope??null})}function iT(e){return At(JSON.stringify({kind:"health-semantic-prewarm-engine",rust:lr(e.config.projectRoot)}))}function Kn(e,t={}){return{status:"skipped",reason:e,definitions:0,referenceCacheHits:0,referenceCacheWrites:0,referenceMisses:0,referenceIncomplete:0,calleeRows:0,...t}}function Vre(e){return{status:e.status,reason:e.reason,definitions:e.definitions,referenceCacheHits:e.referenceCacheHits,referenceCacheWrites:e.referenceCacheWrites,referenceMisses:e.referenceMisses,referenceIncomplete:e.referenceIncomplete,calleeRows:e.calleeRows,error:e.error}}function yf(e){return fc(t=>{let n=Ar({projectRoot:t.config.projectRoot,db:t,observedSourceKinds:["index-generation"]});return{value:e(t),anchor:{database:{config:t.config,generation:t.generation},generationDigest:n.facts.index.generation.digest}}})}function zl(e,t,n){let r=e[0];if(!r)throw new Error("An evidence-bound analysis requires at least one index observation anchor.");let i=r.generationDigest,o=e.every(a=>a.generationDigest===i),s=t.every(a=>a?.facts.index?.generation.digest===i);return Ar({projectRoot:r.database.config.projectRoot,...o&&s?{db:r.database}:{},observedSourceKinds:n})}async function hDe(e){return(await Jre(e)).result}async function Jre(e){let t=pie(e),n={...e,phaseTimeoutMs:t??null},r=yf(y=>{let S=ff(y,n,Zn);if(!S)return null;let I=zP(y,S);return I||null});if(r.value)return{result:r.value,observationReceipt:zl([r.anchor],[],["index-generation","live-workspace"])};let i=yf(y=>({applicability:sie(y,e),overview:nf(y,"overview",e)})),{applicability:o,overview:s}=i.value,a=[r.anchor,i.anchor],c=new Map;c.set("overview",s);let l=$l.filter(y=>y==="overview"?!1:aie(y,o)?!0:(c.set(y,_r(y)),!1)),u=uie(cie(l)),d=[],m=[];if(e.full)try{m=await eie(e)}catch(y){d.push(`Health semantic prewarm omitted: ${bf(y)}.`)}let p=e.full?hie(u.length):gie(u.length),f=await Ul(u,p,y=>die(y,e,t));if(f.flatMap(y=>y.result).forEach(y=>{y.healthPhaseMeta&&d.push(e.full?`Health phase "${y.phase}" omitted after a bounded worker failure: ${y.healthPhaseMeta.reason}.`:`Health phase "${y.phase}" deferred: ${y.healthPhaseMeta.reason}. Run health --full for exhaustive analysis.`),c.set(y.phase,y)}),d.length>0){let y=c.get("overview");c.set("overview",{...y,warnings:[...y.warnings,...d]})}return{result:fc(y=>{let S=rf($l.map(x=>c.get(x)),y),I=ff(y,n,Zn);return I&&GP(y,I,S),S}),observationReceipt:zl(a,[...m.map(y=>y.observationReceipt),...f.map(y=>y.observationReceipt)],["index-generation","live-workspace"])}}var YP=12288,Yre=2048,Xre=8192,Qre=4;function Zre(e=process.env,t=ZP(),n=Gl()){let r={shards:1,heapMb:nie(e,n)},i=Number.isFinite(n)&&n>0?n/(1024*1024):0,o=Math.floor(Math.max(0,i-Xre)/(YP+Yre)),s=Number.isFinite(t)?Math.max(1,t-1):1,a=Number.parseInt(e.SCIP_QUERY_HEALTH_PREWARM_SHARDS??"",10),c=Number.isSafeInteger(a)&&a>0?a:Number.POSITIVE_INFINITY,l=Math.min(Qre,o,s,c);return!Number.isFinite(l)||l<2?r:{shards:l,heapMb:YP}}function XP(e,t){let n=process.argv[1]??Kl(import.meta.url),r=["--full"];return e.scope&&r.push("--scope",e.scope),e.shard&&r.push("--shard-index",String(e.shard.index),"--shard-count",String(e.shard.count)),js({cliPath:n,command:hre,args:r,env:{...process.env,NODE_OPTIONS:wa(process.env.NODE_OPTIONS,t)},label:e.shard?`Health semantic prewarm ${e.shard.index+1}/${e.shard.count}`:"Health semantic prewarm",timeoutMs:iie()})}async function eie(e,t=Zre()){if(t.shards<2)return[await XP(e,t.heapMb)];let n=Array.from({length:t.shards},(o,s)=>({index:s,count:t.shards})),r=await Ul(n,t.shards,o=>XP({...e,shard:o},t.heapMb)),i=tie(r.map(o=>o.result));return i.status==="warmed"&&fc(o=>{let s=nt(o);s&&hf.write(o,rT(e,iT(o)),s,{version:Us,definitions:i.definitions,referenceCacheWrites:i.referenceCacheWrites,referenceIncomplete:i.referenceIncomplete,calleeRows:i.calleeRows,warmedAt:Date.now()})}),r}function tie(e){let t=i=>e.reduce((o,s)=>o+(i(s)??0),0),n={definitions:t(i=>i.definitions),referenceCacheHits:t(i=>i.referenceCacheHits),referenceCacheWrites:t(i=>i.referenceCacheWrites),referenceMisses:t(i=>i.referenceMisses),referenceIncomplete:t(i=>i.referenceIncomplete),calleeRows:t(i=>i.calleeRows),warmedFiles:t(i=>i.warmedFiles),referenceFragmentFiles:t(i=>i.referenceFragmentFiles),referenceFragmentComputedFiles:t(i=>i.referenceFragmentComputedFiles)},r=e.find(i=>i.status==="partial")??e.find(i=>i.status==="skipped"&&i.reason!=="cache-hit");return r?{...n,status:r.status,reason:r.reason,...r.error?{error:r.error}:{}}:e.length>0&&e.every(i=>i.status==="skipped")?{...n,status:"skipped",reason:"cache-hit"}:{...n,status:"warmed",reason:"cache-miss"}}function nie(e=process.env,t=Gl()){let n=Number.parseInt(e.SCIP_QUERY_HEALTH_SEMANTIC_PREWARM_HEAP_MB??"",10);return Number.isSafeInteger(n)&&n>0?n:rie(t)}function rie(e){return oT(e,{min:Are,max:Nre})}function oT(e,t){let n=Math.floor(e/2097152);return!Number.isFinite(n)||n<=0?t.max:Math.max(t.min,Math.min(t.max,n))}function iie(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_HEALTH_SEMANTIC_PREWARM_TIMEOUT_MS??"",10);return Number.isSafeInteger(t)&&t>0?t:_re}function oie(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_HEALTH_FULL_PHASE_HEAP_MB??"",10);return Number.isSafeInteger(t)&&t>0?t:Dre}function sie(e,t){return Qs(e,{scope:t.scope})}function aie(e,t){return tT.has(e)?t.react:nT.has(e)?t.vue:!0}function cie(e){return HP(e,[tT,Ore,Bre])}var lie={"passthrough-candidates":31,similar:29,dead:20,"react-component-duplicates":10,"react-hook-candidates":10,cycles:8};function uie(e){let t=n=>n.reduce((r,i)=>r+(lie[i]??1),0);return e.map((n,r)=>({task:n,index:r,weight:t(n)})).sort((n,r)=>r.weight-n.weight||n.index-r.index).map(n=>n.task)}function _r(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 die(e,t,n){if(e.length===1)return mie(e[0],t,n).then(s=>({result:[s.result],...s.observationReceipt?{observationReceipt:s.observationReceipt}:{}}));let r=e.join(","),i=process.argv[1]??Kl(import.meta.url),o=[r];return t.scope&&o.push("--scope",t.scope),t.full&&o.push("--full"),js({cliPath:i,command:eT,args:o,...t.full?{env:sT()}:{},label:`Health phases "${r}"`,timeoutMs:n}).catch(s=>{if(!t.full&&!(s instanceof nn))throw s;let a=s instanceof nn?s.timeoutMs:n??0;return{result:e.map(c=>aT(c,a,s instanceof nn?`timed out after ${s.timeoutMs}ms`:bf(s)))}})}function mie(e,t,n){let r=process.argv[1]??Kl(import.meta.url),i=[e];return t.scope&&i.push("--scope",t.scope),t.full&&i.push("--full"),js({cliPath:r,command:eT,args:i,...t.full?{env:sT()}:{},label:`Health phase "${e}"`,timeoutMs:n}).catch(o=>{if(!t.full&&!(o instanceof nn))throw o;let s=o instanceof nn?o.timeoutMs:n??0;return{result:aT(e,s,o instanceof nn?`timed out after ${o.timeoutMs}ms`:bf(o))}})}function bf(e){let t=e instanceof Error?e.message:String(e);if(/heap out of memory|reaching memory limit/i.test(t))return"exceeded its isolated memory limit";let n=t.split(/\r?\n/,1)[0]?.trim()||"isolated worker failed";return n.length<=240?n:`${n.slice(0,237)}...`}function sT(e=process.env){return{...e,NODE_OPTIONS:wa(e.NODE_OPTIONS,oie(e))}}function pie(e,t=process.env){let n=e.full?Fre:kre,r=t.SCIP_QUERY_HEALTH_PHASE_TIMEOUT_MS;if(!r)return n;let i=parseInt(r,10);return!Number.isFinite(i)||i<0?n:i===0?void 0:i}function aT(e,t,n){let r={healthPhaseMeta:{status:"deferred",reason:n,timeoutMs:t}};if(e==="overview")throw new Error("Overview health phase cannot be deferred.");if(typeof e!="string")return;let i=fie().get(e);if(i)return{...i(),...r}}function fie(){let e={dead:()=>({phase:"dead",dead:{count:0,loc:0,files:[]}}),cycles:()=>({phase:"cycles",realCycleCount:0,cycleExclusions:[]}),similar:()=>({phase:"similar",similarCount:0}),"duplicate-bodies":()=>({phase:"duplicate-bodies",duplicateBodies:{count:0,loc:0,files:[]}}),"twin-drift":()=>({phase:"twin-drift",twinDrift:{count:0,loc:0,files:[]}}),"react-component-duplicates":()=>_r("react-component-duplicates"),"react-hook-candidates":()=>_r("react-hook-candidates"),"react-large-component-pressure":()=>_r("react-large-component-pressure"),"vue-component-duplicates":()=>_r("vue-component-duplicates"),"vue-composable-candidates":()=>_r("vue-composable-candidates"),"vue-large-view-pressure":()=>_r("vue-large-view-pressure"),"passthrough-candidates":()=>({phase:"passthrough-candidates",passthroughs:{count:0,loc:0,files:[]}}),drift:()=>({phase:"drift",drift:{count:0,unusedImports:0,architectureViolations:0,layerViolations:0,direct:0,signal:0}}),"git-evidence":()=>({phase:"git-evidence",gitEvidence:null}),suppressions:()=>({phase:"suppressions",suppressions:{total:0,byCategory:{}}}),"coverage-contracts":()=>({phase:"coverage-contracts",coverageContracts:{count:0,loc:0,files:[]}})};return new Map(Object.entries(e))}var gie=Sf({envKey:"SCIP_QUERY_HEALTH_CONCURRENCY",defaultMinimum:wre,defaultMaximum:Pre}),hie=Sf({envKey:"SCIP_QUERY_HEALTH_FULL_CONCURRENCY",defaultMinimum:Tre,defaultMaximum:Lre,memoryPerTaskBytes:Mre});function yie(e){let t=e.generation,n=[t.mode,t.publishedAt?`published ${t.publishedAt}`:null].filter(i=>i!==null).join(", "),r=e.git?`git ${e.git.head.slice(0,12)}${e.git.branch?` on ${e.git.branch}`:" (detached)"}, ${e.git.dirtyPaths} uncommitted path(s)`:"git: not a repository";return`Input: generation ${t.identity.slice(0,12)}${n?` (${n})`:""}; ${r}`}function yDe(e){if(console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${Ud(e.overview.indexSizeBytes)}`),e.provenance&&console.log(` ${yie(e.provenance)}`),console.log(""),e.warnings&&e.warnings.length>0){console.log(" Warnings:");for(let t of e.warnings)console.log(` ${t}`);console.log("")}bie(e.findings),Sie(e),vie(e),Cie(e),Rie(e),e.actions.length===0&&console.log(e.warnings&&e.warnings.length>0?`
|
|
348
|
+
No findings from completed analyses. Review warnings before interpreting this result as clean.`:`
|
|
349
|
+
No findings from completed analyses. Review coverage before drawing conclusions.`)}function bie(e){console.log(" Findings:");let t=[[e.deadSymbols,()=>` Dead code: ${e.deadSymbols} symbols (${e.deadLoc} LOC)`],[e.cycles,()=>` Circular deps: ${e.cycles}`],[e.similarPairs,()=>` Similar pairs: ${e.similarPairs}`],[e.twinDriftGroups,()=>` Drifted twins: ${e.twinDriftGroups} group(s)`],[e.reactComponentDuplicatePairs,()=>` React components: ${e.reactComponentDuplicatePairs} duplicate pair(s)`],[e.reactHookCandidatePairs,()=>` React hook reuse: ${QP(e.reactHookCandidatePairs,e.reactHookCandidateScoreCount)} candidate pair(s)`],[e.reactLargeComponentPressureFiles,()=>` React large comps: ${e.reactLargeComponentPressureFiles} component(s)`],[e.vueComponentDuplicatePairs,()=>` Vue components: ${e.vueComponentDuplicatePairs} duplicate pair(s)`],[e.vueComposableCandidatePairs,()=>` Vue composables: ${QP(e.vueComposableCandidatePairs,e.vueComposableCandidateScoreCount)} candidate pair(s)`],[e.vueLargeViewPressureFiles,()=>` Vue large views: ${e.vueLargeViewPressureFiles} file(s)`],[e.passthroughs,()=>` Passthroughs: ${e.passthroughs}`],[e.driftedFiles,()=>` Pattern drift: ${e.driftedFiles} files`]];for(let[n,r]of t)n>0&&console.log(r())}function Sie(e){let t=e.policyExclusions??[];if(t.length>0){console.log(`
|
|
350
|
+
Policy exclusions (listed by the detector command, not counted above):`);for(let n of t)console.log(` ${n.detector}: ${n.count} ${n.detail}`)}}function vie(e){if(e.actions.length>0){console.log(`
|
|
351
|
+
Prioritized Actions (highest impact + lowest effort first):`);for(let t=0;t<e.actions.length;t++){let n=e.actions[t],r=n.locRecoverable>0?` (~${n.locRecoverable} LOC involved)`:"";console.log(` ${t+1}. [${n.effort} effort / ${n.impact} impact] ${n.description}${r}`)}}}function Cie(e){if(e.detectorEvidence.length>0){console.log(`
|
|
352
|
+
Detector Evidence Calibration:`);for(let t of e.detectorEvidence){let n=t.unavailableRequirements.length>0?`; unavailable: ${t.unavailableRequirements.join(", ")}`:"";console.log(` ${t.detector}: ${t.status}/${t.providerCoverage}${n}`)}console.log(" Full claims, non-claims, providers, and recovery commands are available in health --json.")}}function QP(e,t){return Math.abs(e-t)<.01?String(e):`${e} (combined pair weight ${xie(t)})`}function xie(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function Rie(e){let t=e.axes;if(console.log(`
|
|
353
|
+
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)}%)`)}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 bDe(e){let t=yf(o=>{let s=zi(o,{base:e.base});return s.note?{kind:"complete",result:vl(o,{base:e.base})}:s.changedFiles.length===0?{kind:"complete",result:vl(o,{base:e.base})}:{kind:"batched",plan:s}}),n=t.value;if(n.kind==="complete")return{result:n.result,observationReceipt:zl([t.anchor],[],["index-generation","live-workspace"])};let r=Iie(n.plan.changedFiles),i=await Ul(r,Eie(r.length),o=>Tie(o,e));return{result:Cl(n.plan.changedFiles,i.map(o=>o.result),n.plan.changedFileLines.filter(o=>!n.plan.changedFiles.includes(o))),observationReceipt:zl([t.anchor],i.map(o=>o.observationReceipt),["index-generation","live-workspace"])}}var Eie=Sf({envKey:"SCIP_QUERY_DIFF_IMPACT_CONCURRENCY",defaultMinimum:Sre,defaultMaximum:vre});function Iie(e){return yo(e,bre)}function Sf(e){return(t,n=process.env,r=ZP,i=Gl())=>wie(t,n,r,i,e)}function wie(e,t,n,r,i){let o=t[i.envKey],s=Pie(n,r,i),a=o?parseInt(o,10):s;return!Number.isFinite(a)||a<1?Math.min(s,e):Math.min(a,e)}function Pie(e,t,n){let r=e(),i=Number.isFinite(r)?Math.max(n.defaultMinimum,r-1):0,o=n.memoryPerTaskBytes!==void 0&&Number.isFinite(t)&&t>0?Math.floor(t/2/n.memoryPerTaskBytes):Number.POSITIVE_INFINITY;return Math.min(n.defaultMaximum,o,Math.max(n.defaultMinimum,i))}function Tie(e,t){let n=process.argv[1]??Kl(import.meta.url),r=[];return t.base&&r.push("--base",t.base),js({cliPath:n,command:yre,args:r,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e),NODE_OPTIONS:wa(process.env.NODE_OPTIONS,Mie())},label:"Diff-impact batch",timeoutMs:Lie()})}function Lie(e=process.env){let t=Number.parseInt(e.SCIP_QUERY_DIFF_IMPACT_BATCH_TIMEOUT_MS??"",10);return Number.isSafeInteger(t)&&t>0?t:Rre}function Mie(e=process.env,t=Gl()){let n=Number.parseInt(e.SCIP_QUERY_DIFF_IMPACT_BATCH_HEAP_MB??"",10);return Number.isSafeInteger(n)&&n>0?n:oT(t,{min:xre,max:Cre})}function SDe(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:"),Kd.list(e.changedSymbols,n=>` ${n.file} ${n.shortName} (fan-in: ${n.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
|
|
354
|
+
Affected consumer files:`),Kd.list(e.affectedConsumers,n=>` ${n.file} (${n.consumedSymbols} symbol(s))`))}function Die(e){return e==="inspect"?"Use --full only when every omitted semantic candidate can change the decision; it does not override source or behavior materialization ceilings.":e==="dead"?'Run "scip-query dead --full" for an unbounded candidate scan; semantic enrichment remains disabled on large indexes to keep memory bounded.':`Run "scip-query ${e} --full" for the unbounded semantic pass.`}function Fie({db:e,opts:t,runtime:n,cacheKey:r,fingerprint:i,definitionCount:o,warmedFiles:s,references:a,fragments:c,calleeRows:l}){let u={warmedFiles:s,...c?{referenceFragmentFiles:c.files,referenceFragmentComputedFiles:c.computedFiles}:{}};return a.incomplete>0?{status:"partial",reason:"incomplete-references",definitions:o,referenceCacheHits:a.cacheHits,referenceCacheWrites:a.cacheWrites,referenceMisses:a.misses,referenceIncomplete:a.incomplete,...u,calleeRows:l}:(t.shard||M("health.semantic-prewarm.marker-write",()=>n.writeMarker(e,r,i,{version:Us,definitions:o,referenceCacheWrites:a.cacheWrites,referenceIncomplete:a.incomplete,calleeRows:l,warmedAt:Date.now()})),{status:"warmed",reason:"cache-miss",definitions:o,referenceCacheHits:a.cacheHits,referenceCacheWrites:a.cacheWrites,referenceMisses:a.misses,referenceIncomplete:a.incomplete,...u,calleeRows:l})}import{AsyncLocalStorage as kie}from"async_hooks";import{createHash as Cf}from"crypto";import{existsSync as Nie,mkdirSync as Aie}from"fs";import{tmpdir as _ie}from"os";import{isAbsolute as Oie,join as mT,resolve as pT}from"path";var vf=2,Bie="SCIP_QUERY_SESSION",cT="SCIP_QUERY_SESSION_DIR",$ie=128,Xi=new kie;function FDe(e,t){let n=e.sessionEnabled===!1||e.json?void 0:aoe(),r={enabled:n!==void 0,reemit:e.reemit===!0,command:e.command,projectRoot:pT(e.cwd),sessionIdentity:n,staged:[],stagedEvidence:[],finalized:!1};return Xi.run(r,t)}function kDe(e){let t=Xi.getStore();!t||t.finalized||(t.generationIdentity=e)}function NDe(e){let t=Xi.getStore();if(!t||t.finalized)return;t.finalized=!0;let n=t.state;if(!n){t.staged.length=0,t.stagedEvidence.length=0;return}try{if(e&&(t.staged.length>0||t.stagedEvidence.length>0)){let r=n.ledger.nextOrdinal,i=noe(t.staged).map(s=>({...s,ordinal:r,command:t.command})),o=ioe(t.stagedEvidence).map(s=>({...s,ordinal:r,command:t.command}));n.ledger.ranges.push(...i),n.ledger.evidence.push(...o),n.ledger.nextOrdinal+=1,n.ledger.updatedAt=new Date().toISOString(),hu(n.ledgerPath,n.ledger,{spacing:2,trailingNewline:!0})}}catch{}finally{n.lock.release(),t.state=null,t.staged.length=0,t.stagedEvidence.length=0}}function ADe(e){let t=e.source.split(`
|
|
355
|
+
`);if(t.length===0)return"";let n=jie(e.relativePath,e.startLine,t,e.ownerSymbol,e.sessionPolicy??"exact-unit"),r=e.indent??" ",i=e.sourceIndent??" ",o=e.focusLines??new Set;return n.map(s=>{let a=Gd(e.relativePath,s.startLine,s.endLine);if(s.kind==="covered"){let u=s.ordinal===null?"this command":`session #${s.ordinal} via ${s.command}`;return[`${r}${a} [source previously emitted: ${u}; not repeated]`,...e.afterHeader??[]].join(`
|
|
356
|
+
`)}let c=e.headerSuffix??"",l=s.lines.map((u,d)=>{let m=s.startLine+d,p=e.showFocusMarker===!1?"":o.has(m)?">":" ",f=e.lineNumberWidth??5;return`${i}${p}${String(gc(m)).padStart(f)} ${u}`});return[`${r}${a}${c}`,...e.blankAfterHeader?[""]:[],...e.afterHeader??[],...l].join(`
|
|
357
|
+
`)}).join(`
|
|
358
|
+
`)}function _De(e){let t=Xi.getStore();if(!t||!t.enabled)return e.content;let n=xf(t);if(!n)return e.content;let r=fT(e.content),i=Wl(n.ledger.evidence,o=>o.kind===e.kind&&o.identity===e.identity&&o.contentHash===r);if(i&&!t.reemit){let o=e.label?`; ${dT(e.label)}`:"";return`${e.indent??""}[${e.kind} evidence previously emitted: receipt ${i.receiptId}; session #${i.ordinal} via ${i.command}${o}; not repeated]`}return t.stagedEvidence.push({kind:e.kind,identity:e.identity,contentHash:r,receiptId:coe(e.kind,e.identity,r),...e.label?{label:dT(e.label)}:{}}),e.content}function ODe(e=!1){let t=Xi.getStore();if(!t?.enabled)return{enabled:!1,reason:"No explicit SCIP_QUERY_SESSION is active; source packets render independently.",uniqueLines:0,evidenceItems:0,emissions:0,rows:[]};let n=xf(t);if(!n)return{enabled:!1,reason:"The exploration-session ledger was unavailable or contended; evidence output is fail-open for this command.",uniqueLines:0,evidenceItems:0,emissions:0,rows:[]};if(e){n.ledger.ranges=[],n.ledger.evidence=[],n.ledger.nextOrdinal=1,n.ledger.updatedAt=new Date().toISOString();try{hu(n.ledgerPath,n.ledger,{spacing:2,trailingNewline:!0})}catch{return{enabled:!1,reason:"The exploration-session ledger could not be reset; evidence output remains fail-open.",uniqueLines:0,evidenceItems:0,emissions:0,rows:[]}}}let r=new Map;for(let a of n.ledger.ranges){let c=r.get(a.ordinal)??[];c.push(a),r.set(a.ordinal,c)}let i=new Map;for(let a of n.ledger.evidence){let c=i.get(a.ordinal)??[];c.push(a),i.set(a.ordinal,c)}let s=[...new Set([...r.keys(),...i.keys()])].sort((a,c)=>a-c).map(a=>{let c=r.get(a)??[],l=i.get(a)??[],u=c[0]?.command??l[0]?.command??"unknown",d=c.length===0?null:(()=>{let f=c.slice(0,8).map(h=>Gd(h.relativePath,h.startLine,h.endLine)).join(", "),g=c.length>8?`, ... ${c.length-8} more range(s)`:"";return` #${a} ${u}: ${f}${g}`})();if(l.length===0)return d;let m=l.slice(0,8).map(f=>`${f.receiptId} ${f.kind}${f.label?` ${f.label}`:""}`).join(", "),p=l.length>8?`, ... ${l.length-8} more item(s)`:"";return d?`${d}
|
|
359
|
+
evidence: ${m}${p}`:` #${a} ${u}: ${m}${p}`});return{enabled:!0,uniqueLines:ooe(n.ledger.ranges),evidenceItems:n.ledger.evidence.length,emissions:new Set([...r.keys(),...i.keys()]).size,rows:s}}function jie(e,t,n,r,i){let o=Xi.getStore(),s=t+n.length-1;if(!o)return[{kind:"source",startLine:t,endLine:s,lines:[...n]}];let c=(o.enabled?xf(o):null)?.ledger.ranges??[],l=n.map(fT);if(i==="exact-unit"&&!o.reemit){let m=Hie(c,e,t,s,r,l);if(m)return[{kind:"covered",startLine:t,endLine:s,ordinal:m.ordinal,command:m.command}]}let u=n.map((m,p)=>qie(c,e,t+p,l[p]));return i==="preview"&&!o.reemit&&u.every(m=>m!==void 0)?Uie(t,n.length,u):(o.staged.push({relativePath:e,startLine:t,endLine:s,ownerSymbol:r,policy:i,lineHashes:l}),[{kind:"source",startLine:t,endLine:s,lines:[...n]}])}function Hie(e,t,n,r,i,o){return Wl(e,a=>a.policy==="exact-unit"&&a.relativePath===t&&a.startLine===n&&a.endLine===r&&a.ownerSymbol===i&&loe(a.lineHashes,o))??zie(e,t,n,r,o)}function Uie(e,t,n){let r=[],i=0;for(;i<t;){let o=n[i],s=i;for(;s+1<t&&Gie(o,n[s+1]);)s+=1;let a=e+i,c=e+s;r.push({kind:"covered",startLine:a,endLine:c,ordinal:o.ordinal,command:o.command}),i=s+1}return r}function qie(e,t,n,r){let i=Wl(e,o=>o.relativePath===t&&o.startLine<=n&&n<=o.endLine&&o.lineHashes[n-o.startLine]===r);if(i)return{ordinal:i.ordinal,command:i.command}}function zie(e,t,n,r,i){let o=Wl(e,s=>s.policy==="exact-unit"&&s.relativePath===t&&s.startLine<=n&&s.endLine>=r&&i.every((a,c)=>s.lineHashes[n-s.startLine+c]===a));return o?{ordinal:o.ordinal,command:o.command}:void 0}function Gie(e,t){return!e||!t?e===t:e.ordinal===t.ordinal&&e.command===t.command}function xf(e){if(e.state!==void 0)return e.state;if(!e.sessionIdentity||!e.generationIdentity)return e.state=null,null;try{let t=soe();Aie(t,{recursive:!0,mode:448});let n=Cf("sha256").update(e.projectRoot).update("\0").update(e.generationIdentity).update("\0").update(e.sessionIdentity).digest("hex"),r=mT(t,`${n}.json`),i=Ia(`${r}.lock`,{kind:"source-emission-session",detail:{session:n.slice(0,12)}});if(i.kind!=="acquired")return e.state=null,null;let o;try{o=Nie(r)?Vie(JSON.parse(Ye(r,"source emission session ledger")),{projectRoot:e.projectRoot,generationIdentity:e.generationIdentity,sessionIdentity:e.sessionIdentity}):Kie(e)}catch{return i.lock.release(),e.state=null,null}return e.state={ledgerPath:r,lock:i.lock,ledger:o},e.state}catch{return e.state=null,null}}function Kie(e){return{version:vf,projectRoot:e.projectRoot,generationIdentity:e.generationIdentity,sessionIdentity:e.sessionIdentity,nextOrdinal:1,updatedAt:new Date().toISOString(),ranges:[],evidence:[]}}function lT(e,t){return e.projectRoot===t.projectRoot&&e.generationIdentity===t.generationIdentity&&e.sessionIdentity===t.sessionIdentity}function uT(e){return Number.isSafeInteger(e.nextOrdinal)&&(e.nextOrdinal??0)>0}function Wie(e){return Array.isArray(e.ranges)&&e.ranges.every(Jie)&&Array.isArray(e.evidence)&&e.evidence.every(Zie)}function Vie(e,t){if(!k(e))throw new Error("Invalid source emission ledger.");let n=e;if(e.version===1&&lT(n,t)&&uT(n))return{version:vf,projectRoot:t.projectRoot,generationIdentity:t.generationIdentity,sessionIdentity:t.sessionIdentity,nextOrdinal:n.nextOrdinal,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:new Date().toISOString(),ranges:[],evidence:[]};if(n.version!==vf||!lT(n,t)||!uT(n)||!Wie(n))throw new Error("Invalid source emission ledger.");return n}function Jie(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return Yie(t)&&Xie(t)&&Qie(t)}function Yie(e){return typeof e.relativePath=="string"&&e.relativePath!==""&&Number.isSafeInteger(e.startLine)&&(e.startLine??-1)>=0&&Number.isSafeInteger(e.endLine)&&(e.endLine??-1)>=(e.startLine??0)}function Xie(e){return Number.isSafeInteger(e.ordinal)&&(e.ordinal??0)>0&&typeof e.command=="string"&&e.command!==""&&(e.policy==="exact-unit"||e.policy==="preview")}function Qie(e){return Array.isArray(e.lineHashes)&&e.lineHashes.length===(e.endLine??0)-(e.startLine??0)+1&&e.lineHashes.every(jr)&&(e.ownerSymbol===void 0||typeof e.ownerSymbol=="string")}function Zie(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return eoe(t)&&toe(t)}function eoe(e){return(e.kind==="unit"||e.kind==="edge")&&typeof e.identity=="string"&&e.identity!==""&&typeof e.contentHash=="string"&&jr(e.contentHash)}function toe(e){return typeof e.receiptId=="string"&&/^ev-[0-9a-f]{12}$/u.test(e.receiptId)&&Number.isSafeInteger(e.ordinal)&&(e.ordinal??0)>0&&typeof e.command=="string"&&e.command!==""&&(e.label===void 0||typeof e.label=="string")}function noe(e){let t=[...e].sort((r,i)=>r.relativePath.localeCompare(i.relativePath)||r.startLine-i.startLine||r.endLine-i.endLine),n=[];for(let r of t){let i=n[n.length-1];if(i&&i.relativePath===r.relativePath&&i.ownerSymbol===r.ownerSymbol&&i.policy===r.policy&&r.startLine<=i.endLine+1&&roe(i,r)){let o=r.startLine-i.startLine;for(let s=0;s<r.lineHashes.length;s+=1)i.lineHashes[o+s]??=r.lineHashes[s];i.endLine=Math.max(i.endLine,r.endLine)}else n.push({...r,lineHashes:[...r.lineHashes]})}return n}function roe(e,t){let n=Math.max(e.startLine,t.startLine),r=Math.min(e.endLine,t.endLine);for(let i=n;i<=r;i+=1)if(e.lineHashes[i-e.startLine]!==t.lineHashes[i-t.startLine])return!1;return!0}function ioe(e){let t=new Set,n=[];for(let r of e){let i=`${r.kind}\0${r.identity}\0${r.contentHash}`;t.has(i)||(t.add(i),n.push(r))}return n}function ooe(e){let t=new Map;for(let r of e){let i=t.get(r.relativePath)??[];i.push(r),t.set(r.relativePath,i)}let n=0;for(let r of t.values()){r.sort((s,a)=>s.startLine-a.startLine||s.endLine-a.endLine);let i=-1,o=-1;for(let s of r)i<0?(i=s.startLine,o=s.endLine):s.startLine<=o+1?o=Math.max(o,s.endLine):(n+=o-i+1,i=s.startLine,o=s.endLine);i>=0&&(n+=o-i+1)}return n}function soe(){let e=process.env[cT];if(!e)return mT(_ie(),`scip-query-source-sessions-${process.getuid?.()??"user"}`);if(!Oie(e))throw new Error(`${cT} must be an absolute path.`);return pT(e)}function aoe(){let e=process.env[Bie]?.trim();if(e&&!(e.length>$ie||!/^[A-Za-z0-9._:-]+$/.test(e)))return`explicit:${e}`}function coe(e,t,n){return`ev-${Cf("sha256").update(e).update("\0").update(t).update("\0").update(n).digest("hex").slice(0,12)}`}function dT(e){let t=e.replace(/[\r\n\t]+/gu," ").replace(/\s+/gu," ").trim();return t.length<=160?t:`${t.slice(0,157)}...`}function fT(e){return Cf("sha256").update(e).digest("hex")}function loe(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}function Wl(e,t){for(let n=e.length-1;n>=0;n-=1){let r=e[n];if(t(r))return r}}export{Wo as a,RO as b,OO as c,O as d,qa as e,jae as f,mF as g,fi as h,cb as i,lle as j,Jo as k,mh as l,ase as m,Yo as n,Xo as o,L$ as p,lj as q,bue as r,Wk as s,Dge as t,gj as u,Cj as v,Mt as w,Qx as x,tK as y,Nm as z,wK as A,Pr as B,_W as C,$W as D,jW as E,HW as F,nV as G,oV as H,sV as I,aV as J,lV as K,uV as L,dV as M,Hm as N,hs as O,zm as P,n2 as Q,o2 as R,s2 as S,u2 as T,y2 as U,b2 as V,S2 as W,cl as X,Ss as Y,ZJ as Z,vs as _,e4 as $,op as aa,ap as ba,L4 as ca,Cs as da,xs as ea,up as fa,XX as ga,E5 as ha,bp as ia,j5 as ja,zi as ka,CI as la,E3 as ma,Rs as na,FQ as oa,QQ as pa,Is as qa,cZ as ra,CZ as sa,_Z as ta,o8 as ua,jp as va,N8 as wa,Ms as xa,w9 as ya,P9 as za,L9 as Aa,$9 as Ba,$l as Ca,nf as Da,Kee as Ea,xte as Fa,Lte as Ga,$te as Ha,hP as Ia,Bs as Ja,yP as Ka,ane as La,aN as Ma,Tue as Na,qo as Oa,dS as Pa,gS as Qa,uc as Ra,hS as Sa,yr as Ta,Od as Ua,_de as Va,$d as Wa,dc as Xa,LP as Ya,DP as Za,lf as _a,Tne as $a,Go as ab,sS as bb,rde as cb,ide as db,ode as eb,sde as fb,ade as gb,cde as hb,Ide as ib,uS as jb,wde as kb,mc as lb,Jde as mb,pc as nb,SS as ob,Yde as pb,Xde as qb,Qde as rb,Zde as sb,O0 as tb,fc as ub,eme as vb,tme as wb,Ud as xb,nme as yb,ime as zb,ome as Ab,sme as Bb,ame as Cb,CS as Db,Rt as Eb,zd as Fb,cme as Gb,Ar as Hb,CMe as Ib,FMe as Jb,gc as Kb,J0 as Lb,Gd as Mb,dme as Nb,Kd as Ob,eT as Pb,hre as Qb,yre as Rb,pDe as Sb,fDe as Tb,gDe as Ub,hDe as Vb,Jre as Wb,yDe as Xb,bDe as Yb,SDe as Zb,FDe as _b,kDe as $b,NDe as ac,ADe as bc,_De as cc,ODe as dc};
|
|
360
|
+
//# sourceMappingURL=chunk-JYWEX7RR.js.map
|