scip-query 0.19.4 → 0.19.6
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 +75 -1
- package/README.md +242 -49
- package/dist/augment-vue-worker.js +1 -1
- package/dist/{chunk-2YU7I3QO.js → chunk-24QNP7MN.js} +2 -2
- package/dist/{chunk-CNKAGUPL.js → chunk-26X7KCJR.js} +2 -2
- package/dist/{chunk-GPBBJ5Y4.js → chunk-273W2U4Y.js} +3 -3
- package/dist/{chunk-7GXM52MI.js → chunk-2CVXCGL4.js} +2 -2
- package/dist/{chunk-ABMYA4TN.js → chunk-2EZSOTSY.js} +2 -2
- package/dist/{chunk-HKEHS2AS.js → chunk-2GSQR6YA.js} +2 -2
- package/dist/{chunk-FECYOO5O.js → chunk-2OXVAGGT.js} +2 -2
- package/dist/chunk-2ZOCHAL2.js +8 -0
- package/dist/{chunk-QGXBRIM5.js → chunk-336DC5NJ.js} +2 -2
- package/dist/chunk-35SQLYCQ.js +2 -0
- package/dist/{chunk-VXQNNXJE.js → chunk-3OIKRYU5.js} +2 -2
- package/dist/{chunk-52ZYCAEO.js → chunk-47X75ZKH.js} +2 -2
- package/dist/{chunk-NPKYOIFM.js → chunk-4CGVLUDP.js} +2 -2
- package/dist/chunk-4RI4BJGT.js +8 -0
- package/dist/{chunk-P2PC2WGR.js → chunk-52HQTTPB.js} +2 -2
- package/dist/{chunk-YNRNA5LK.js → chunk-5OC3HWP5.js} +2 -2
- package/dist/{chunk-STOL2BTL.js → chunk-6XFC7PQ5.js} +2 -2
- package/dist/{chunk-J77UIT3I.js → chunk-6XHTISLI.js} +2 -2
- package/dist/chunk-6YTSKJJ3.js +2 -0
- package/dist/{chunk-BTEE5NZQ.js → chunk-7E3TH5ZN.js} +2 -2
- package/dist/{chunk-X6D5IC6I.js → chunk-7LABSJSR.js} +2 -2
- package/dist/chunk-7Q6VYYCH.js +2 -0
- package/dist/{chunk-FWUUZTIO.js → chunk-A43URCQ3.js} +2 -2
- package/dist/chunk-A63U2W3P.js +3 -0
- package/dist/{chunk-3MJ5YA4Y.js → chunk-ADFSIJP2.js} +2 -2
- package/dist/chunk-AOLE4DYM.js +6 -0
- package/dist/chunk-APMMR5Y2.js +2 -0
- package/dist/chunk-B5MHCHP3.js +107 -0
- package/dist/{chunk-4RSI5EMG.js → chunk-CSTYYXKC.js} +2 -2
- package/dist/{chunk-25LPM4DG.js → chunk-CYJM7CYF.js} +2 -2
- package/dist/{chunk-S44IULR6.js → chunk-DD5BOU5I.js} +2 -2
- package/dist/{chunk-YGAGTIDK.js → chunk-DGMCFMPG.js} +7 -7
- package/dist/{chunk-UOAV44HR.js → chunk-E2ZXPB7J.js} +2 -2
- package/dist/{chunk-IZKFSVBV.js → chunk-EVOC5I5I.js} +2 -2
- package/dist/{chunk-XTX6QHOF.js → chunk-F42A3AKG.js} +2 -2
- package/dist/{chunk-Q4IIEGXJ.js → chunk-FHCTEANE.js} +2 -2
- package/dist/{chunk-3SVWW4PN.js → chunk-FKGN4A4E.js} +2 -2
- package/dist/{chunk-IG7N5ZIK.js → chunk-FQTPPXNA.js} +2 -2
- package/dist/{chunk-F6O7AAC3.js → chunk-G4UQL4CP.js} +2 -2
- package/dist/chunk-GA64UPMI.js +6 -0
- package/dist/{chunk-ZXJYMGD3.js → chunk-GK3GRUJX.js} +2 -2
- package/dist/chunk-HEBAY673.js +2 -0
- package/dist/chunk-HELS7KFF.js +2 -0
- package/dist/{chunk-B5NLK2B3.js → chunk-IPDCSB6N.js} +2 -2
- package/dist/{chunk-M7MTH5NR.js → chunk-IYAOX36F.js} +2 -2
- package/dist/{chunk-YVVCVR2L.js → chunk-J7VT2CRB.js} +2 -2
- package/dist/{chunk-4333ETTV.js → chunk-JELJLXEE.js} +2 -2
- package/dist/{chunk-LBMJEAEW.js → chunk-JERWGHQT.js} +2 -2
- package/dist/chunk-JJJCO4QC.js +945 -0
- package/dist/{chunk-6E7UTQY7.js → chunk-JZNLMHWY.js} +2 -2
- package/dist/{chunk-R4FQGQ4X.js → chunk-K42M2KWT.js} +2 -2
- package/dist/{chunk-H7UKLTWJ.js → chunk-KLVJABXA.js} +2 -2
- package/dist/chunk-KP4KBDVF.js +3 -0
- package/dist/{chunk-RV2FQIX3.js → chunk-LMFVTUW2.js} +2 -2
- package/dist/chunk-LRTP3DKL.js +3 -0
- package/dist/{chunk-U6WNH5GC.js → chunk-MGBJHRFB.js} +2 -2
- package/dist/{chunk-QDV6RDCP.js → chunk-MLGTCX56.js} +2 -2
- package/dist/{chunk-54HA4ZXH.js → chunk-N3SE646F.js} +2 -2
- package/dist/{chunk-KP6XRY5Z.js → chunk-NBRUH7OE.js} +2 -2
- package/dist/{chunk-M7AIS73L.js → chunk-NN4ZIRPK.js} +2 -2
- package/dist/{chunk-I5RJM53C.js → chunk-NQLSSVOB.js} +2 -2
- package/dist/{chunk-4SALD7RU.js → chunk-OBKDTVZ3.js} +2 -2
- package/dist/{chunk-GBQ5NYPR.js → chunk-OHWZKLVA.js} +6 -6
- package/dist/{chunk-6NSFJYRC.js → chunk-OP3MTFJR.js} +2 -2
- package/dist/{chunk-EOOJGLDU.js → chunk-OQ2A4G2G.js} +2 -2
- package/dist/{chunk-DLWR3NUU.js → chunk-P6HBYNBE.js} +2 -2
- package/dist/{chunk-QVWS2VWZ.js → chunk-PC44K7RF.js} +2 -2
- package/dist/{chunk-A2EZV2UM.js → chunk-QBYYWGAT.js} +2 -2
- package/dist/{chunk-QRGV2F7L.js → chunk-QHKUY4FW.js} +2 -2
- package/dist/chunk-QHRL4LKM.js +2 -0
- package/dist/{chunk-I5AWSI2G.js → chunk-QQWOFXNW.js} +2 -2
- package/dist/{chunk-WQTAC523.js → chunk-RBFFD4V2.js} +2 -2
- package/dist/{chunk-SOAT6NLA.js → chunk-RJHCPSZ7.js} +2 -2
- package/dist/{chunk-VGRICIQI.js → chunk-RWRLUZ6U.js} +2 -2
- package/dist/{chunk-4T3LTWUS.js → chunk-S2GP3CU3.js} +2 -2
- package/dist/{chunk-HEXVUYFQ.js → chunk-SHKZ7OVJ.js} +2 -2
- package/dist/{chunk-NSS46APD.js → chunk-TFUU5MQQ.js} +2 -2
- package/dist/{chunk-IUFDSKGG.js → chunk-TYQ76QHQ.js} +2 -2
- package/dist/{chunk-NRCXJDHL.js → chunk-U5CNPPTZ.js} +2 -2
- package/dist/{chunk-MITTUCEH.js → chunk-UQK5CRUK.js} +2 -2
- package/dist/{chunk-XLTP42QA.js → chunk-UUJBLG6J.js} +2 -2
- package/dist/chunk-UXP636P5.js +144 -0
- package/dist/{chunk-64RFXJT5.js → chunk-VEVBIAOJ.js} +6 -6
- package/dist/chunk-VKRQDBW5.js +9 -0
- package/dist/{chunk-C7NIYIQ4.js → chunk-VOQFGC2W.js} +4 -4
- package/dist/{chunk-DZ74OMG6.js → chunk-VP542C25.js} +2 -2
- package/dist/{chunk-Q3AFUTGB.js → chunk-WMXRRBII.js} +2 -2
- package/dist/{chunk-ZGZUZ7XE.js → chunk-WXAAURU7.js} +2 -2
- package/dist/chunk-X3NLZHPA.js +20 -0
- package/dist/{chunk-WER3B7MI.js → chunk-XF3KLXN3.js} +2 -2
- package/dist/{chunk-NH5ALKPW.js → chunk-XVJ3V7LM.js} +2 -2
- package/dist/{chunk-4XTA5OMB.js → chunk-YGQN3XGZ.js} +2 -2
- package/dist/{chunk-CFMXJPHH.js → chunk-YHXBD52M.js} +2 -2
- package/dist/{chunk-7B3UPBVA.js → chunk-YLVE3SXZ.js} +2 -2
- package/dist/{chunk-YIJ7ZAA4.js → chunk-YTUD45PU.js} +2 -2
- package/dist/{chunk-VTKGCT3V.js → chunk-YWB2EBNB.js} +2 -2
- package/dist/{chunk-UKZBVX4U.js → chunk-Z2LHPIOM.js} +2 -2
- package/dist/chunk-Z5QQPJ3U.js +30 -0
- package/dist/{chunk-NZL2DBT7.js → chunk-ZLJLE6LK.js} +2 -2
- package/dist/{chunk-XYADIZHU.js → chunk-ZTTISZ7J.js} +2 -2
- package/dist/cli.js +3 -3
- package/dist/command-descriptors-SJDZ7QGR.js +617 -0
- package/dist/{config-types-D20KuvvZ.d.ts → config-types-BWQ5xPGI.d.ts} +4 -0
- package/dist/{db-G_II8yXU.d.ts → db-B0r1o7Vt.d.ts} +18 -1
- package/dist/direct-navigation-HTKOZEOM.js +3 -0
- package/dist/{health-oblXYgkF.d.ts → health-CFnlCiTz.d.ts} +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/postinstall.js +1 -1
- package/dist/queries/affected.d.ts +2 -2
- package/dist/queries/affected.js +1 -1
- package/dist/queries/architecture.d.ts +2 -2
- package/dist/queries/architecture.js +1 -1
- package/dist/queries/bottlenecks.d.ts +2 -2
- package/dist/queries/bottlenecks.js +1 -1
- package/dist/queries/by-kind.d.ts +2 -2
- package/dist/queries/by-kind.js +1 -1
- package/dist/queries/call-graph.d.ts +2 -2
- package/dist/queries/call-graph.js +1 -1
- package/dist/queries/change-surface.d.ts +2 -2
- package/dist/queries/change-surface.js +1 -1
- package/dist/queries/cleanup-plan.d.ts +2 -2
- package/dist/queries/cleanup-plan.js +1 -1
- package/dist/queries/co-change.d.ts +2 -2
- package/dist/queries/co-change.js +1 -1
- package/dist/queries/code.d.ts +2 -2
- package/dist/queries/code.js +1 -1
- package/dist/queries/complexity-hotspots.d.ts +2 -2
- package/dist/queries/complexity-hotspots.js +1 -1
- package/dist/queries/complexity.d.ts +2 -2
- package/dist/queries/complexity.js +1 -1
- package/dist/queries/convergence.d.ts +2 -2
- package/dist/queries/convergence.js +1 -1
- package/dist/queries/coupling.d.ts +2 -2
- package/dist/queries/coupling.js +1 -1
- package/dist/queries/cycles.d.ts +2 -2
- package/dist/queries/cycles.js +1 -1
- package/dist/queries/dataflow.d.ts +2 -2
- package/dist/queries/dataflow.js +1 -1
- package/dist/queries/dead.d.ts +2 -2
- package/dist/queries/dead.js +1 -1
- package/dist/queries/decorative-checkers.d.ts +3 -3
- package/dist/queries/decorative-checkers.js +1 -1
- package/dist/queries/deep-chains.d.ts +2 -2
- package/dist/queries/deep-chains.js +1 -1
- package/dist/queries/deps.d.ts +2 -2
- package/dist/queries/deps.js +1 -1
- package/dist/queries/diff-gate.d.ts +30 -2
- package/dist/queries/diff-gate.js +1 -1
- package/dist/queries/diff-impact.d.ts +2 -2
- package/dist/queries/diff-impact.js +1 -1
- package/dist/queries/doc-drift.d.ts +2 -2
- package/dist/queries/doc-drift.js +1 -1
- package/dist/queries/drift.d.ts +2 -2
- package/dist/queries/drift.js +1 -1
- package/dist/queries/duplicate-bodies.d.ts +2 -2
- package/dist/queries/duplicate-bodies.js +1 -1
- package/dist/queries/extract-candidates.d.ts +2 -2
- package/dist/queries/extract-candidates.js +1 -1
- package/dist/queries/fan.d.ts +2 -2
- package/dist/queries/fan.js +1 -1
- package/dist/queries/files.d.ts +2 -2
- package/dist/queries/health.d.ts +3 -3
- package/dist/queries/health.js +1 -1
- package/dist/queries/hierarchy.d.ts +2 -2
- package/dist/queries/hierarchy.js +1 -1
- package/dist/queries/hotspots.d.ts +2 -2
- package/dist/queries/hotspots.js +1 -1
- package/dist/queries/imports.d.ts +2 -2
- package/dist/queries/imports.js +1 -1
- package/dist/queries/incomplete-migration.d.ts +2 -2
- package/dist/queries/incomplete-migration.js +1 -1
- package/dist/queries/index.d.ts +17 -3
- package/dist/queries/index.js +1 -1
- package/dist/queries/isolated.d.ts +2 -2
- package/dist/queries/isolated.js +1 -1
- package/dist/queries/locality-candidates.d.ts +2 -2
- package/dist/queries/locality-candidates.js +1 -1
- package/dist/queries/members.d.ts +2 -2
- package/dist/queries/members.js +1 -1
- package/dist/queries/methods.d.ts +2 -2
- package/dist/queries/methods.js +1 -1
- package/dist/queries/not-implemented.d.ts +3 -3
- package/dist/queries/not-implemented.js +1 -1
- package/dist/queries/outline.d.ts +2 -2
- package/dist/queries/outline.js +1 -1
- package/dist/queries/passthrough-candidates.d.ts +2 -2
- package/dist/queries/passthrough-candidates.js +1 -1
- package/dist/queries/plan-context.d.ts +2 -2
- package/dist/queries/plan-context.js +1 -1
- package/dist/queries/react-component-duplicates.d.ts +2 -2
- package/dist/queries/react-component-duplicates.js +1 -1
- package/dist/queries/react-hook-candidates.d.ts +2 -2
- package/dist/queries/react-hook-candidates.js +1 -1
- package/dist/queries/react-large-component-pressure.d.ts +2 -2
- package/dist/queries/react-large-component-pressure.js +1 -1
- package/dist/queries/recent-duplicates.d.ts +2 -2
- package/dist/queries/recent-duplicates.js +1 -1
- package/dist/queries/redundant-reexports.d.ts +2 -2
- package/dist/queries/redundant-reexports.js +1 -1
- package/dist/queries/refs.d.ts +2 -2
- package/dist/queries/refs.js +1 -1
- package/dist/queries/self-audit.d.ts +2 -2
- package/dist/queries/self-audit.js +1 -1
- package/dist/queries/similar-chains.d.ts +2 -2
- package/dist/queries/similar-chains.js +1 -1
- package/dist/queries/similar-files.d.ts +2 -2
- package/dist/queries/similar-files.js +1 -1
- package/dist/queries/similar-signatures.d.ts +2 -2
- package/dist/queries/similar-signatures.js +1 -1
- package/dist/queries/similar.d.ts +2 -2
- package/dist/queries/similar.js +1 -1
- package/dist/queries/slice.d.ts +2 -2
- package/dist/queries/slice.js +1 -1
- package/dist/queries/stale-abstractions.d.ts +2 -2
- package/dist/queries/stale-abstractions.js +1 -1
- package/dist/queries/stats.d.ts +2 -2
- package/dist/queries/stats.js +1 -1
- package/dist/queries/surface.d.ts +2 -2
- package/dist/queries/surface.js +1 -1
- package/dist/queries/symbols.d.ts +2 -2
- package/dist/queries/symbols.js +1 -1
- package/dist/queries/system.d.ts +2 -2
- package/dist/queries/system.js +1 -1
- package/dist/queries/test-quality.d.ts +2 -2
- package/dist/queries/test-quality.js +1 -1
- package/dist/queries/trace.d.ts +2 -2
- package/dist/queries/trace.js +1 -1
- package/dist/queries/twin-ab.d.ts +3 -3
- package/dist/queries/twin-ab.js +1 -1
- package/dist/queries/twin-drift.d.ts +2 -2
- package/dist/queries/twin-drift.js +1 -1
- package/dist/queries/unused-imports.d.ts +2 -2
- package/dist/queries/unused-imports.js +1 -1
- package/dist/queries/unused-params.d.ts +2 -2
- package/dist/queries/unused-params.js +1 -1
- package/dist/queries/vue-component-duplicates.d.ts +2 -2
- package/dist/queries/vue-component-duplicates.js +1 -1
- package/dist/queries/vue-composable-candidates.d.ts +2 -2
- package/dist/queries/vue-composable-candidates.js +1 -1
- package/dist/queries/vue-large-view-pressure.d.ts +2 -2
- package/dist/queries/vue-large-view-pressure.js +1 -1
- package/dist/queries/wrapper-candidates.d.ts +2 -2
- package/dist/queries/wrapper-candidates.js +1 -1
- package/dist/reindex-worker.js +23 -24
- package/dist/reindex.d.ts +10 -4
- package/dist/reindex.js +33 -38
- package/dist/runtime.d.ts +167 -11
- package/dist/runtime.js +3 -2
- package/dist/rust-semantic-session-server.js +1 -1
- package/dist/rust-semantic-session-worker.js +1 -1
- package/dist/rust-semantic-worker.js +1 -1
- package/dist/{scip-cli-kRpaexVJ.d.ts → scip-cli-DCvnlZCu.d.ts} +5 -1
- package/dist/watch-server.js +5 -5
- package/docs/AGENT_GUIDE.md +1 -1
- package/docs/AI_FAILURE_MODES.md +18 -18
- package/docs/API_EVOLUTION.md +71 -0
- package/docs/CLI_JSON_OUTPUT.md +83 -0
- package/docs/COMMAND_REFERENCE.md +10 -8
- package/docs/COMMITTED_RECORD_COMPATIBILITY.md +117 -0
- package/docs/CONFIGURATION_WRITE_SAFETY.md +130 -0
- package/docs/DETECTOR_GUIDE.md +47 -47
- package/docs/DURABILITY.md +103 -0
- package/docs/INDEX_GENERATIONS.md +121 -0
- package/docs/LOCK_PROTOCOL.md +133 -0
- package/docs/MAILBOX_LIFECYCLE.md +197 -0
- package/docs/REINDEX_METADATA_COMPATIBILITY.md +84 -0
- package/docs/RUST_DURABLE_SESSION_PROTOCOL.md +126 -0
- package/docs/TELEMETRY_RETENTION.md +72 -0
- package/docs/TIME_SEMANTICS.md +77 -0
- package/docs/WATCH_REFRESH_REQUESTS.md +110 -0
- package/docs/WINDOWS_SIDECAR_RELEASE.md +298 -0
- package/docs/analyzer-validation-ledger.md +24 -23
- package/docs/schemas/cli-json-envelope.schema.json +53 -0
- package/docs/schemas/npm-release-state.schema.json +146 -0
- package/docs/schemas/outcome-event-record.schema.json +39 -0
- package/docs/schemas/project-config.schema.json +247 -0
- package/docs/schemas/suppression-record.schema.json +31 -0
- package/docs/schemas/windows-sidecar-provenance.schema.json +137 -0
- package/package.json +15 -5
- package/scripts/build-scip-windows.mjs +180 -61
- package/scripts/scip-windows-provenance.mjs +364 -0
- package/scripts/verify-scip-windows.mjs +29 -0
- package/skills/_shared/SKILL.md +91 -242
- package/skills/_shared/agents/openai.yaml +1 -1
- package/skills/_shared/references/agent-contract-catalog.md +105 -0
- package/skills/_shared/references/command-catalog.md +118 -0
- package/skills/_shared/references/detector-precision-and-diffgate.md +59 -0
- package/skills/_shared/references/evidence-and-dead-code.md +25 -0
- package/skills/scip-audit/SKILL.md +76 -0
- package/skills/scip-audit/agents/openai.yaml +4 -0
- package/skills/scip-audit/references/claims.md +98 -0
- package/skills/scip-audit/references/cleanup.md +101 -0
- package/skills/scip-audit/references/directory.md +222 -0
- package/skills/scip-audit/references/frontend.md +130 -0
- package/skills/scip-audit/references/integrity.md +154 -0
- package/skills/scip-audit/references/maintainability.md +162 -0
- package/skills/scip-audit/references/twin-drift.md +104 -0
- package/skills/scip-diagnose/SKILL.md +52 -0
- package/skills/scip-diagnose/agents/openai.yaml +4 -0
- package/skills/scip-diagnose/references/debug.md +117 -0
- package/skills/{scip-probe-reachability/SKILL.md → scip-diagnose/references/probe-reachability.md} +12 -27
- package/skills/scip-diagnose/references/root-cause.md +145 -0
- package/skills/scip-diagnose/references/triage.md +119 -0
- package/skills/scip-explore/SKILL.md +53 -84
- package/skills/scip-explore/agents/openai.yaml +2 -2
- package/skills/scip-explore/references/diagrams.md +40 -0
- package/skills/scip-explore/references/language-playbook.md +49 -0
- package/skills/scip-improve/SKILL.md +56 -0
- package/skills/scip-improve/agents/openai.yaml +4 -0
- package/skills/scip-improve/references/cleanup-batches.md +53 -0
- package/skills/scip-improve/references/directory-moves.md +53 -0
- package/skills/scip-improve/references/doc-reconcile.md +30 -0
- package/skills/scip-improve/references/frontend-extraction.md +39 -0
- package/skills/scip-improve/references/maintainability-mechanism.md +43 -0
- package/skills/scip-improve/references/twin-drift.md +35 -0
- package/skills/scip-plan/SKILL.md +68 -0
- package/skills/scip-plan/agents/openai.yaml +4 -0
- package/skills/scip-plan/references/api-impact.md +19 -0
- package/skills/scip-plan/references/conductor.md +41 -0
- package/skills/scip-plan/references/high-assurance.md +43 -0
- package/skills/scip-plan/references/hyper-optimization.md +50 -0
- package/skills/scip-plan/references/tla-model.md +88 -0
- package/skills/scip-query/SKILL.md +52 -97
- package/skills/scip-query/agents/openai.yaml +2 -2
- package/skills/scip-setup/SKILL.md +65 -176
- package/skills/scip-setup/agents/openai.yaml +3 -3
- package/skills/scip-setup/references/bootstrap-workflow.md +120 -0
- package/skills/scip-setup/references/language-verification.md +61 -0
- package/skills/scip-setup/references/lifecycle-commands.md +119 -0
- package/skills/scip-setup/references/per-repo-triage.md +24 -0
- package/skills/scip-verify/SKILL.md +123 -70
- package/skills/scip-verify/agents/openai.yaml +2 -2
- package/skills/scip-verify/references/calibrate-detectors.md +170 -0
- package/dist/chunk-2CTX5CMX.js +0 -4
- package/dist/chunk-2Y373BDD.js +0 -2
- package/dist/chunk-C2QSK7E7.js +0 -2
- package/dist/chunk-D4U5Q3FT.js +0 -7
- package/dist/chunk-K2ERX4UT.js +0 -3
- package/dist/chunk-KHE7J5ZN.js +0 -3
- package/dist/chunk-L7SPDE73.js +0 -84
- package/dist/chunk-LHMNRHGV.js +0 -3
- package/dist/chunk-LM72NQ7T.js +0 -3
- package/dist/chunk-MSWVMDAH.js +0 -122
- package/dist/chunk-NH7WNNQC.js +0 -20
- package/dist/chunk-OMPZHGHO.js +0 -2
- package/dist/chunk-SVLTAG5O.js +0 -927
- package/dist/chunk-U7DSEKOM.js +0 -30
- package/dist/chunk-V27BEQJN.js +0 -7
- package/dist/chunk-VMNZB6WI.js +0 -4
- package/dist/chunk-XBN5VO53.js +0 -2
- package/dist/chunk-ZAIILQNP.js +0 -5
- package/dist/command-descriptors-MFU4BCJ7.js +0 -612
- package/dist/direct-navigation-MRMQFIRB.js +0 -3
- package/skills/scip-api-impact/SKILL.md +0 -139
- package/skills/scip-api-impact/agents/openai.yaml +0 -4
- package/skills/scip-calibrate/SKILL.md +0 -131
- package/skills/scip-calibrate/agents/openai.yaml +0 -4
- package/skills/scip-claim-audit/SKILL.md +0 -106
- package/skills/scip-claim-audit/agents/openai.yaml +0 -4
- package/skills/scip-cleanup-audit/SKILL.md +0 -126
- package/skills/scip-cleanup-audit/agents/openai.yaml +0 -4
- package/skills/scip-cleanup-improve/SKILL.md +0 -84
- package/skills/scip-cleanup-improve/agents/openai.yaml +0 -4
- package/skills/scip-concrete-plan/SKILL.md +0 -262
- package/skills/scip-concrete-plan/agents/openai.yaml +0 -4
- package/skills/scip-conductor/SKILL.md +0 -133
- package/skills/scip-conductor/agents/openai.yaml +0 -4
- package/skills/scip-debug/SKILL.md +0 -130
- package/skills/scip-debug/agents/openai.yaml +0 -4
- package/skills/scip-diagram/SKILL.md +0 -110
- package/skills/scip-diagram/agents/openai.yaml +0 -4
- package/skills/scip-directory-architecture/SKILL.md +0 -254
- package/skills/scip-directory-architecture/agents/openai.yaml +0 -4
- package/skills/scip-doc-reconcile/SKILL.md +0 -89
- package/skills/scip-doc-reconcile/agents/openai.yaml +0 -4
- package/skills/scip-hyper-optimization/SKILL.md +0 -156
- package/skills/scip-hyper-optimization/agents/openai.yaml +0 -4
- package/skills/scip-integrity-audit/SKILL.md +0 -152
- package/skills/scip-integrity-audit/agents/openai.yaml +0 -4
- package/skills/scip-language-playbook/SKILL.md +0 -106
- package/skills/scip-language-playbook/agents/openai.yaml +0 -4
- package/skills/scip-maintainability/SKILL.md +0 -158
- package/skills/scip-maintainability/agents/openai.yaml +0 -4
- package/skills/scip-probe-reachability/agents/openai.yaml +0 -4
- package/skills/scip-react-maintainability/SKILL.md +0 -101
- package/skills/scip-react-maintainability/agents/openai.yaml +0 -4
- package/skills/scip-root-cause/SKILL.md +0 -150
- package/skills/scip-root-cause/agents/openai.yaml +0 -4
- package/skills/scip-tla-model-system/SKILL.md +0 -148
- package/skills/scip-tla-model-system/agents/openai.yaml +0 -4
- package/skills/scip-triage-issue/SKILL.md +0 -126
- package/skills/scip-triage-issue/agents/openai.yaml +0 -4
- package/skills/scip-twin-drift/SKILL.md +0 -107
- package/skills/scip-twin-drift/agents/openai.yaml +0 -4
- package/skills/scip-vue-maintainability/SKILL.md +0 -107
- package/skills/scip-vue-maintainability/agents/openai.yaml +0 -4
|
@@ -0,0 +1,945 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{createHash as nE}from"crypto";import{existsSync as rE,mkdirSync as iE}from"fs";import{dirname as _p,join as oE}from"path";import Dl from"better-sqlite3";function Cl(e,t){let n=e.split("/").at(-1)??e;if(Dp.has(n)||n===".scipquery.json"||/^tsconfig(?:\..+)?\.json$/.test(n))return"config";if(/\.d\.(?:ts|mts|cts)$/.test(e.toLowerCase()))return"ambient";let r=e.includes(".")?`.${e.split(".").at(-1).toLowerCase()}`:"";return t.some(i=>(kp[i]??[]).includes(r))?"source":"other"}function wp(e,t,n){let r=e.split("/").at(-1)??e;if(n?.includes(e)||n?.includes(r)||Dp.has(r))return!0;let i=e.includes(".")?`.${e.split(".").at(-1).toLowerCase()}`:"";return(kp[t]??[]).includes(i)}function Ep(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.version!="number"||!Rp(t.languages)||typeof t.pnpmWorkspaces!="boolean"||typeof t.typescriptProjectMode!="string"||!Rp(t.typescriptProjects)||t.clojureConfigPath!==void 0&&typeof t.clojureConfigPath!="string"||!Array.isArray(t.files)||!t.files.every(Rl)?null:t}function H4(e,t){let n=new Map((e?.files??[]).map(a=>[a.path,a])),r=new Map(t.files.map(a=>[a.path,a])),i=new Set([...n.keys(),...r.keys()]),o=[];for(let a of[...i].sort()){let c=n.get(a),l=r.get(a),u=Cl(a,t.languages);!c&&l?o.push({kind:"added",path:a,inputKind:u,after:l}):c&&!l?o.push({kind:"deleted",path:a,inputKind:u,before:c}):c&&l&&(c.hash!==l.hash||c.size!==l.size)&&o.push({kind:"modified",path:a,inputKind:u,before:c,after:l})}let s=new Set;return e||s.add("prior-snapshot-unavailable"),e&&e.version!==t.version&&s.add("snapshot-version-changed"),(vp(e?.files??[])||vp(t.files))&&s.add("duplicate-input-path"),[...e?.files??[],...t.files].some(Ww)&&s.add("unreadable-input"),{version:1,changes:o,projectIdentityChanged:e?!zw(e,t):!0,uncertainty:[...s].sort()}}function Rp(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function vp(e){return new Set(e.map(t=>t.path)).size!==e.length}function Rl(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.path=="string"&&typeof t.size=="number"&&Number.isFinite(t.size)&&typeof t.hash=="string"}function Ww(e){return e.hash==="unreadable"||e.size<0}function zw(e,t){return Ip(e.languages,t.languages)&&e.pnpmWorkspaces===t.pnpmWorkspaces&&e.typescriptProjectMode===t.typescriptProjectMode&&Ip(e.typescriptProjects,t.typescriptProjects)&&e.clojureConfigPath===t.clojureConfigPath}function Ip(e,t){if(e.length!==t.length)return!1;let n=[...e].sort(),r=[...t].sort();return n.every((i,o)=>i===r[o])}var Dp=new Set(["package.json","package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lockb","tsconfig.json","tsconfig.base.json","pyproject.toml","setup.py","setup.cfg","Cargo.toml","Cargo.lock","go.mod","go.sum","pom.xml","build.gradle","build.gradle.kts","build.sbt","compile_commands.json","CMakeLists.txt","Makefile","Gemfile","Gemfile.lock","composer.json","composer.lock","pubspec.yaml","pubspec.lock","deps.edn","project.clj","bb.edn","shadow-cljs.edn"]),kp={typescript:[".ts",".tsx",".mts",".cts"],javascript:[".js",".jsx",".mjs",".cjs"],java:[".java"],scala:[".scala"],kotlin:[".kt",".kts"],rust:[".rs"],python:[".py",".pyi"],ruby:[".rb"],go:[".go"],cpp:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"],c:[".c",".h"],csharp:[".cs"],vb:[".vb"],dart:[".dart"],php:[".php"],clojure:[".clj",".cljs",".cljc"]};function q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Is(e){return typeof e=="string"&&Number.isFinite(Date.parse(e))}function j(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}var Oi=["typescript","javascript","java","scala","kotlin","rust","python","ruby","go","cpp","c","csharp","vb","dart","php","clojure"];var vl=2,ws=3;var Il=new Set(Oi);function Tt(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(s){return{kind:"malformed",reason:`invalid JSON: ${eE(s)}`}}if(!q(t))return{kind:"malformed",reason:"metadata must be a JSON object"};let n=t.version;if(!Number.isInteger(n))return{kind:"malformed",reason:"version must be an integer"};if(n!==vl&&n!==ws)return{kind:"unsupported",version:n,direction:n<vl?"older":"future"};let r=Jw(t,n);if(r)return{kind:"malformed",reason:r};let i=t,o={metadata:i,capabilities:Kw(i)};return n===vl?{kind:"legacy",...o,metadata:i}:{kind:"supported",...o,metadata:i}}function K4(e){return e.kind==="legacy"||e.kind==="supported"?e.metadata:null}function Pp(e){if(e.kind!=="legacy"&&e.kind!=="supported"||!e.capabilities.stableGenerationIdentity)return null;let t=e.metadata;return JSON.stringify({version:t.version,status:t.status,updatedAt:t.updatedAt,fingerprint:t.fingerprint,indexedLanguages:t.indexedLanguages,scipCompanion:t.scipCompanion})}function Kw(e){let t=e.fingerprint!==void 0,n=q(e.fingerprint),r=e.indexedLanguages!==void 0,i=e.status==="complete",o=e.version===ws?e:null;return{usableForQuery:r,usableForEvidenceCache:t,publishableGeneration:i&&n&&r,stableGenerationIdentity:i&&t&&typeof e.updatedAt=="string",languageShardReuse:!!o?.languageFingerprints,typescriptProjectShardReuse:!!o?.typescriptProjectShards}}function Jw(e,t){if(e.status!=="complete"&&e.status!=="partial")return"status must be complete or partial";if(e.updatedAt!==void 0&&!Is(e.updatedAt))return"updatedAt must be a valid timestamp";for(let n of["requestedLanguages","indexedLanguages"])if(e[n]!==void 0&&!Yw(e[n]))return`${n} must contain unique supported languages`;return e.skipped!==void 0&&!Xw(e.skipped)?"skipped must contain supported language/reason pairs":e.scipCompanion!==void 0&&e.scipCompanion!=="current"&&e.scipCompanion!=="deferred"?"scipCompanion must be current or deferred":t===ws&&e.languageFingerprints!==void 0&&!Qw(e.languageFingerprints)?"languageFingerprints must map supported languages to fingerprint objects":t===ws&&e.typescriptProjectShards!==void 0&&!Zw(e.typescriptProjectShards)?"typescriptProjectShards must map project names to file fingerprints":null}function Yw(e){return!Array.isArray(e)||!e.every(t=>typeof t=="string"&&Il.has(t))?!1:new Set(e).size===e.length}function Xw(e){return Array.isArray(e)&&e.every(t=>q(t)&&typeof t.language=="string"&&Il.has(t.language)&&typeof t.reason=="string")}function Qw(e){return q(e)&&Object.entries(e).every(([t,n])=>Il.has(t)&&q(n))}function Zw(e){return q(e)&&Object.values(e).every(t=>q(t)&&Array.isArray(t.files)&&t.files.every(Rl))}function eE(e){return e instanceof Error?e.message:String(e)}var Fp=[];function Cn(e){e.groups.length>0&&Fp.push(e)}function wl(e,t){let n=new Set(t.groups);for(let r of Fp)r.groups.some(i=>n.has(i))&&(t.file!==void 0&&r.clearFile?r.clearFile(e,t.file):r.clearAll(e))}function Tp(){let e=new WeakMap;return{cache:e,ensure(t){let n=e.get(t);return n||(n=new Map,e.set(t,n)),n}}}function B(e,t){let{cache:n,ensure:r}=Tp(),i={get(o,s,a){let c=r(o);if(c.has(s))return c.get(s);let l=a();return c.set(s,l),l},invalidate(o,s){n.get(o)?.delete(s)},invalidateAll(o){n.delete(o)},size(o){return n.get(o)?.size??0}};return Cn({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}function Z(e,t){let n=new WeakMap,r={get(i,o){let s=n.get(i);if(s)return s.value;let a=o();return n.set(i,{value:a}),a},invalidate(i){n.delete(i)},has(i){return n.has(i)}};return Cn({name:e,groups:t.clearGroups,clearAll:i=>r.invalidate(i)}),r}var tE={clearGroups:["whole-project","source-file"]};function Rn(e){return Zn(e,tE)}function Zn(e,t){let{cache:n,ensure:r}=Tp(),i={get(o,s,a,c){let l=r(o),u=l.get(s);if(u&&u.source===a)return u.value;let d=c();return l.set(s,{source:a,value:d}),d},invalidate(o,s){n.get(o)?.delete(s)},invalidateAll(o){n.delete(o)}};return Cn({name:e,groups:t.clearGroups,clearAll:o=>i.invalidateAll(o),clearFile:(o,s)=>i.invalidate(o,s)}),i}var sE="evidence.db";var aE=["source-facts","definition-exclusions","doc-path-tokens","react-component-behavior-profiles"],kl=new Set(aE),cE=25e4,lE=512*1024*1024,uE=5e3,Es=new WeakMap,dE=B("evidence-content-hash",{clearGroups:["whole-project","source-file"]}),mE=B("evidence-project-fingerprint",{clearGroups:["whole-project"]}),it="evidence-v1",Lr="version NOT LIKE 'evidence-%'";function Ce(e){return nE("sha256").update(e).digest("hex")}function me(e,t,n){return dE.get(e,t,()=>Ce(n))}function Ne(e){return mE.get(e,"current",()=>{try{if(!e.generation.metadataRaw)return null;let t=Tt(e.generation.metadataRaw);if(t.kind!=="legacy"&&t.kind!=="supported"||!t.capabilities.usableForEvidenceCache)return null;let n=t.metadata,r=[...n.indexedLanguages??[]].sort();return Ce(JSON.stringify({fingerprint:n.fingerprint,indexedLanguages:r,status:n.status}))}catch(t){return Mr("project fingerprint unavailable",t),null}})}function Mr(e,t){process.env.SCIP_QUERY_DEBUG&&console.error(`evidence-cache: ${e}: ${t instanceof Error?t.message:String(t)}`)}function St(e){if(Es.has(e))return Es.get(e)??null;let t=null;try{let n=new Dl(oE(_p(e.config.dbPath),sE));n.pragma("journal_mode = WAL"),n.pragma("busy_timeout = 5000"),n.pragma("synchronous = NORMAL"),n.exec(`
|
|
3
|
+
CREATE TABLE IF NOT EXISTS file_evidence (
|
|
4
|
+
kind TEXT NOT NULL,
|
|
5
|
+
relative_path TEXT NOT NULL,
|
|
6
|
+
content_hash TEXT NOT NULL,
|
|
7
|
+
version TEXT NOT NULL,
|
|
8
|
+
payload TEXT NOT NULL,
|
|
9
|
+
PRIMARY KEY (kind, relative_path)
|
|
10
|
+
);
|
|
11
|
+
CREATE TABLE IF NOT EXISTS project_evidence (
|
|
12
|
+
kind TEXT NOT NULL,
|
|
13
|
+
cache_key TEXT NOT NULL,
|
|
14
|
+
project_fingerprint TEXT NOT NULL,
|
|
15
|
+
version TEXT NOT NULL,
|
|
16
|
+
payload TEXT NOT NULL,
|
|
17
|
+
PRIMARY KEY (kind, cache_key)
|
|
18
|
+
);
|
|
19
|
+
CREATE TABLE IF NOT EXISTS semantic_callees (
|
|
20
|
+
relative_path TEXT NOT NULL,
|
|
21
|
+
symbol TEXT NOT NULL,
|
|
22
|
+
content_hash TEXT NOT NULL,
|
|
23
|
+
deps_digest TEXT NOT NULL,
|
|
24
|
+
version TEXT NOT NULL,
|
|
25
|
+
payload TEXT NOT NULL,
|
|
26
|
+
PRIMARY KEY (relative_path, symbol)
|
|
27
|
+
);
|
|
28
|
+
CREATE TABLE IF NOT EXISTS semantic_references (
|
|
29
|
+
relative_path TEXT NOT NULL,
|
|
30
|
+
symbol TEXT NOT NULL,
|
|
31
|
+
project_fingerprint TEXT NOT NULL,
|
|
32
|
+
version TEXT NOT NULL,
|
|
33
|
+
payload TEXT NOT NULL,
|
|
34
|
+
PRIMARY KEY (relative_path, symbol)
|
|
35
|
+
);
|
|
36
|
+
CREATE TABLE IF NOT EXISTS finding_outcome_ledger (
|
|
37
|
+
check_name TEXT NOT NULL,
|
|
38
|
+
finding_id TEXT NOT NULL,
|
|
39
|
+
first_seen INTEGER NOT NULL,
|
|
40
|
+
last_seen INTEGER NOT NULL,
|
|
41
|
+
times_shown INTEGER NOT NULL,
|
|
42
|
+
outcome TEXT NOT NULL,
|
|
43
|
+
PRIMARY KEY (check_name, finding_id)
|
|
44
|
+
);
|
|
45
|
+
CREATE TABLE IF NOT EXISTS finding_outcome_observations (
|
|
46
|
+
observation_id TEXT PRIMARY KEY,
|
|
47
|
+
fingerprint TEXT NOT NULL,
|
|
48
|
+
observed_at INTEGER NOT NULL
|
|
49
|
+
);
|
|
50
|
+
`),t={evidence:n,shared:fE(e.config.sharedEvidenceDbPath),readFileEvidence:n.prepare("SELECT payload FROM file_evidence WHERE kind = ? AND relative_path = ? AND content_hash = ? AND version = ?"),readLegacyFileEvidence:n.prepare(`SELECT payload FROM file_evidence
|
|
51
|
+
WHERE kind = ? AND relative_path = ? AND content_hash = ? AND ${Lr}
|
|
52
|
+
ORDER BY version DESC
|
|
53
|
+
LIMIT 1`),writeFileEvidence:n.prepare("INSERT OR REPLACE INTO file_evidence (kind, relative_path, content_hash, version, payload) VALUES (?, ?, ?, ?, ?)"),readProjectEvidence:n.prepare("SELECT payload FROM project_evidence WHERE kind = ? AND cache_key = ? AND project_fingerprint = ? AND version = ?"),readLegacyProjectEvidence:n.prepare(`SELECT payload FROM project_evidence
|
|
54
|
+
WHERE kind = ? AND cache_key = ? AND project_fingerprint = ? AND ${Lr}
|
|
55
|
+
ORDER BY version DESC
|
|
56
|
+
LIMIT 1`),writeProjectEvidence:n.prepare("INSERT OR REPLACE INTO project_evidence (kind, cache_key, project_fingerprint, version, payload) VALUES (?, ?, ?, ?, ?)"),readCallees:n.prepare(`SELECT payload FROM semantic_callees
|
|
57
|
+
WHERE relative_path = ? AND symbol = ? AND content_hash = ? AND deps_digest = ? AND version = ?`),readLegacyCallees:n.prepare(`SELECT payload FROM semantic_callees
|
|
58
|
+
WHERE relative_path = ? AND symbol = ? AND content_hash = ? AND deps_digest = ? AND ${Lr}
|
|
59
|
+
ORDER BY version DESC
|
|
60
|
+
LIMIT 1`),readCalleesForFile:n.prepare(`SELECT symbol, payload FROM semantic_callees
|
|
61
|
+
WHERE relative_path = ? AND content_hash = ? AND deps_digest = ? AND version = ?`),readLegacyCalleesForFile:n.prepare(`SELECT symbol, payload FROM semantic_callees
|
|
62
|
+
WHERE relative_path = ? AND content_hash = ? AND deps_digest = ? AND ${Lr}
|
|
63
|
+
ORDER BY symbol, version DESC`),writeCallees:n.prepare(`INSERT OR REPLACE INTO semantic_callees
|
|
64
|
+
(relative_path, symbol, content_hash, deps_digest, version, payload) VALUES (?, ?, ?, ?, ?, ?)`),dropStaleCallees:n.prepare("DELETE FROM semantic_callees WHERE relative_path = ? AND content_hash != ?"),readReferences:n.prepare(`SELECT payload FROM semantic_references
|
|
65
|
+
WHERE relative_path = ? AND symbol = ? AND project_fingerprint = ? AND version = ?`),readLegacyReferences:n.prepare(`SELECT payload FROM semantic_references
|
|
66
|
+
WHERE relative_path = ? AND symbol = ? AND project_fingerprint = ? AND ${Lr}
|
|
67
|
+
ORDER BY version DESC
|
|
68
|
+
LIMIT 1`),readReferencesForFile:n.prepare(`SELECT symbol, payload FROM semantic_references
|
|
69
|
+
WHERE relative_path = ? AND project_fingerprint = ? AND version = ?`),readLegacyReferencesForFile:n.prepare(`SELECT symbol, payload FROM semantic_references
|
|
70
|
+
WHERE relative_path = ? AND project_fingerprint = ? AND ${Lr}
|
|
71
|
+
ORDER BY symbol, version DESC`),writeReferences:n.prepare(`INSERT OR REPLACE INTO semantic_references
|
|
72
|
+
(relative_path, symbol, project_fingerprint, version, payload) VALUES (?, ?, ?, ?, ?)`),dropStaleReferences:n.prepare("DELETE FROM semantic_references WHERE relative_path = ? AND project_fingerprint != ?"),readFindingOutcomeLedger:n.prepare("SELECT check_name, finding_id, first_seen, last_seen, times_shown, outcome FROM finding_outcome_ledger"),claimFindingOutcomeObservation:n.prepare(`INSERT OR IGNORE INTO finding_outcome_observations
|
|
73
|
+
(observation_id, fingerprint, observed_at) VALUES (?, ?, ?)`),readFindingOutcomeObservation:n.prepare("SELECT fingerprint FROM finding_outcome_observations WHERE observation_id = ?"),upsertFindingOutcomeLedgerRow:n.prepare(`INSERT INTO finding_outcome_ledger
|
|
74
|
+
(check_name, finding_id, first_seen, last_seen, times_shown, outcome)
|
|
75
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
76
|
+
ON CONFLICT(check_name, finding_id) DO UPDATE SET
|
|
77
|
+
first_seen = MIN(finding_outcome_ledger.first_seen, excluded.first_seen),
|
|
78
|
+
last_seen = MAX(finding_outcome_ledger.last_seen, excluded.last_seen),
|
|
79
|
+
times_shown = finding_outcome_ledger.times_shown + excluded.times_shown,
|
|
80
|
+
outcome = excluded.outcome`),updateFindingOutcomeLedgerRow:n.prepare(`UPDATE finding_outcome_ledger
|
|
81
|
+
SET first_seen = MIN(first_seen, ?),
|
|
82
|
+
last_seen = MAX(last_seen, ?),
|
|
83
|
+
outcome = ?
|
|
84
|
+
WHERE check_name = ? AND finding_id = ?`),trimFindingOutcomeLedgerCheck:n.prepare(`DELETE FROM finding_outcome_ledger
|
|
85
|
+
WHERE rowid IN (
|
|
86
|
+
SELECT rowid
|
|
87
|
+
FROM finding_outcome_ledger
|
|
88
|
+
WHERE check_name = ?
|
|
89
|
+
ORDER BY last_seen DESC, first_seen DESC, finding_id DESC
|
|
90
|
+
LIMIT -1 OFFSET ?
|
|
91
|
+
)`)}}catch(n){Mr("disabled (open failed)",n)}return Es.set(e,t),t}function xt(e,t,n){Mr(`disabled (${t})`,n),Es.set(e,null)}function fE(e){if(!e)return null;try{iE(_p(e),{recursive:!0});let t=new Dl(e);return t.pragma("journal_mode = WAL"),t.pragma("busy_timeout = 250"),t.pragma("synchronous = NORMAL"),t.exec(`
|
|
92
|
+
CREATE TABLE IF NOT EXISTS file_evidence (
|
|
93
|
+
kind TEXT NOT NULL,
|
|
94
|
+
relative_path TEXT NOT NULL,
|
|
95
|
+
content_hash TEXT NOT NULL,
|
|
96
|
+
version TEXT NOT NULL,
|
|
97
|
+
payload TEXT NOT NULL,
|
|
98
|
+
last_accessed_at INTEGER NOT NULL,
|
|
99
|
+
PRIMARY KEY (kind, relative_path, content_hash, version)
|
|
100
|
+
);
|
|
101
|
+
`),{evidence:t,readFileEvidence:t.prepare("SELECT payload FROM file_evidence WHERE kind = ? AND relative_path = ? AND content_hash = ? AND version = ?"),writeFileEvidence:t.prepare(`INSERT INTO file_evidence (kind, relative_path, content_hash, version, payload, last_accessed_at)
|
|
102
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
103
|
+
ON CONFLICT(kind, relative_path, content_hash, version)
|
|
104
|
+
DO UPDATE SET payload = excluded.payload, last_accessed_at = excluded.last_accessed_at`)}}catch(t){return Mr("shared cache disabled (open failed)",t),null}}function Pl(e,t,n){Mr(`shared cache disabled (${t})`,n);try{e.shared?.evidence.close()}catch{}e.shared=null}function o3(e,t={}){if(!rE(e))return null;let n;try{n=new Dl(e),n.pragma("busy_timeout = 50"),n.pragma("wal_checkpoint(TRUNCATE)");let r=n.prepare("SELECT COUNT(*) AS count FROM file_evidence").get().count,i=t.maxRows??cE,o=t.budgetBytes??lE,s=Number(n.pragma("page_size",{simple:!0})),a=Number(n.pragma("page_count",{simple:!0})),c=Number(n.pragma("freelist_count",{simple:!0})),l=Math.max(0,a-c)*s,u=r>0&&l>o?Math.min(r,Math.ceil((l-o)/Math.max(1,l/r))):0,d=Math.max(r-i,u);return d>0&&(n.prepare(`DELETE FROM file_evidence WHERE rowid IN (
|
|
105
|
+
SELECT rowid FROM file_evidence ORDER BY last_accessed_at ASC, rowid ASC LIMIT ?
|
|
106
|
+
)`).run(d),n.pragma("wal_checkpoint(TRUNCATE)")),{deletedRows:d,remainingRows:r-d}}catch(r){return Mr("shared cache maintenance skipped",r),null}finally{try{n?.close()}catch{}}}function Lp(e,t,n,r){let i=St(e);if(!i)return null;try{let o=i.readFileEvidence.get(t,n,r,it)??i.readLegacyFileEvidence.get(t,n,r);if(o?.payload!==void 0)return o.payload;if(!kl.has(t)||!i.shared)return null;try{return i.shared.readFileEvidence.get(t,n,r,it)?.payload??null}catch(s){return Pl(i,"file_evidence read",s),null}}catch(o){return xt(e,"file_evidence read",o),null}}function Mp(e,t,n,r,i){let o=St(e);if(o)try{if(o.writeFileEvidence.run(t,n,r,it,i),kl.has(t)&&o.shared)try{o.shared.writeFileEvidence.run(t,n,r,it,i,Date.now())}catch(s){Pl(o,"file_evidence write",s)}}catch(s){xt(e,"file_evidence write",s)}}function Ap(e,t){if(t.length===0)return;let n=St(e);if(n)try{n.evidence.transaction(()=>{for(let i of t)n.writeFileEvidence.run(i.kind,i.relativePath,i.contentHash,it,i.payload)})();let r=t.filter(i=>kl.has(i.kind));if(r.length>0&&n.shared)try{n.shared.evidence.transaction(()=>{for(let i of r)n.shared.writeFileEvidence.run(i.kind,i.relativePath,i.contentHash,it,i.payload,Date.now())})()}catch(i){Pl(n,"file_evidence batch write",i)}}catch(r){xt(e,"file_evidence batch write",r)}}function Np(e,t,n,r){let i=St(e);if(!i)return null;try{return(i.readProjectEvidence.get(t,n,r,it)??i.readLegacyProjectEvidence.get(t,n,r))?.payload??null}catch(o){return xt(e,"project_evidence read",o),null}}function Op(e,t,n,r,i){let o=St(e);if(o)try{o.writeProjectEvidence.run(t,n,r,it,i)}catch(s){xt(e,"project_evidence write",s)}}function jp(e,t,n,r){let i=St(e);if(!i)return new Map;try{let o=i.readCalleesForFile.all(t,n,r,it),s=i.readLegacyCalleesForFile.all(t,n,r);return $p([...s,...o])}catch(o){return xt(e,"semantic_callees bulk read",o),new Map}}function Bp(e,t,n){let r=St(e);if(!r)return new Map;try{let i=r.readReferencesForFile.all(t,n,it),o=r.readLegacyReferencesForFile.all(t,n);return $p([...o,...i])}catch(i){return xt(e,"semantic_references bulk read",i),new Map}}function $p(e){let t=new Map;for(let n of e)t.set(n.symbol,n.payload);return t}function Fl(e,t){if(t.length===0)return;let n=St(e);if(n)try{n.evidence.transaction(()=>{let r=new Set;for(let i of t){let o=`${i.relativePath}\0${i.contentHash}`;r.has(o)||(r.add(o),n.dropStaleCallees.run(i.relativePath,i.contentHash)),n.writeCallees.run(i.relativePath,i.symbol,i.contentHash,i.depsDigest,it,i.payload)}})()}catch(r){xt(e,"semantic_callees write",r)}}function Hp(e,t){if(t.length===0)return;let n=St(e);if(n)try{n.evidence.transaction(()=>{let r=new Set;for(let i of t){let o=`${i.relativePath}\0${i.projectFingerprint}`;r.has(o)||(r.add(o),n.dropStaleReferences.run(i.relativePath,i.projectFingerprint)),n.writeReferences.run(i.relativePath,i.symbol,i.projectFingerprint,it,i.payload)}})()}catch(r){xt(e,"semantic_references write",r)}}function Up(e){let t=St(e);if(!t)return[];try{return Ds(t)}catch(n){return xt(e,"finding_outcome_ledger read",n),[]}}function qp(e,t,n,r={}){let i=St(e);if(!i)return{status:"unavailable",previous:[],current:[]};let o=r.busyTimeoutMs,s;try{if(o!==void 0){s=Number(i.evidence.pragma("busy_timeout",{simple:!0}));let c=Math.max(0,Math.min(6e4,Math.floor(o)));i.evidence.pragma(`busy_timeout = ${c}`)}return i.evidence.transaction(()=>{let c=Ds(i);if(i.claimFindingOutcomeObservation.run(t.observationId,t.fingerprint,t.observedAt).changes===0)return{status:i.readFindingOutcomeObservation.get(t.observationId)?.fingerprint===t.fingerprint?"duplicate":"conflict",previous:c,current:c};let u=[...n(c)],d=new Map(c.map(p=>[El(p),p])),m=new Map,f=new Set;for(let p of u){let g=El(p);if(m.has(g))throw new Error(`duplicate finding-outcome row in transition: ${p.check}/${p.findingId}`);m.set(g,p);let y=d.get(g);if(!y){if(p.timesShown<1)throw new Error(`new finding-outcome row has a non-positive count: ${p.check}/${p.findingId}`);f.add(p.check),i.upsertFindingOutcomeLedgerRow.run(p.check,p.findingId,p.firstSeen,p.lastSeen,p.timesShown,p.outcome);continue}let h=p.timesShown-y.timesShown;if(h<0)throw new Error(`finding-outcome count regressed: ${p.check}/${p.findingId}`);h>0?(f.add(p.check),i.upsertFindingOutcomeLedgerRow.run(p.check,p.findingId,p.firstSeen,p.lastSeen,h,p.outcome)):(p.firstSeen!==y.firstSeen||p.lastSeen!==y.lastSeen||p.outcome!==y.outcome)&&(f.add(p.check),i.updateFindingOutcomeLedgerRow.run(p.firstSeen,p.lastSeen,p.outcome,p.check,p.findingId))}for(let p of c)if(!m.has(El(p)))throw new Error(`finding-outcome transition removed a row: ${p.check}/${p.findingId}`);for(let p of f)i.trimFindingOutcomeLedgerCheck.run(p,uE);return{status:"applied",previous:c,current:Ds(i)}}).immediate()}catch(a){if(pE(a)){let c=[];try{c=Ds(i)}catch{}return{status:"busy",previous:c,current:c}}return xt(e,"finding_outcome_ledger transition",a),{status:"unavailable",previous:[],current:[]}}finally{if(s!==void 0)try{i.evidence.pragma(`busy_timeout = ${Math.max(0,Math.floor(s))}`)}catch{}}}function Ds(e){return e.readFindingOutcomeLedger.all().map(n=>({check:n.check_name,findingId:n.finding_id,firstSeen:n.first_seen,lastSeen:n.last_seen,timesShown:n.times_shown,outcome:n.outcome}))}function El(e){return`${e.check}\0${e.findingId}`}function pE(e){if(!e||typeof e!="object")return!1;let t=e.code;return t==="SQLITE_BUSY"||t==="SQLITE_BUSY_TIMEOUT"||t==="SQLITE_LOCKED"}import{appendFileSync as gE,mkdirSync as hE}from"fs";import{createHash as yE,randomUUID as bE}from"crypto";import{dirname as SE}from"path";import{performance as Ar}from"perf_hooks";var zp="SCIP_QUERY_PROFILE",Kp="SCIP_QUERY_PROFILE_OUT",Jp="SCIP_QUERY_PROFILE_COMMAND",Yp="SCIP_QUERY_PROFILE_CACHE_STATE",Tl="SCIP_QUERY_PROFILE_RUN_ID",_l="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY",Ll="SCIP_QUERY_PROFILE_WORKLOAD_IDENTITY_KIND",Xp=[zp,Kp,Jp,Yp,Tl,_l,Ll],d3=new Set(Xp),Gp=new Set,Vp=new Map,Wp=!1;function G(){let e=process.env[zp];return e==="1"||e==="true"}function xE(){return process.env[Kp]}function Qp(){return process.env[Jp]}function CE(){return process.env[Yp]}function Zp(){let e=process.env[Tl];if(e)return e;if(!G())return;let t=bE();return process.env[Tl]=t,t}function eg(){return process.env[_l]}function RE(e){let t=eg();if(t)return t;if(!G())return;let n=Zp();if(!n)return;let r=e.projectFingerprint?"published-project":"run-only",i=ji(["profile-workload-v1",e.toolVersion,e.command,e.projectFingerprint??n]);return process.env[_l]=i,process.env[Ll]=r,i}function ji(e){return yE("sha256").update(JSON.stringify(e)).digest("hex").slice(0,24)}function tg(){return Object.fromEntries(Xp.flatMap(e=>{let t=process.env[e];return t===void 0?[]:[[e,t]]}))}function E(e,t,n){if(!G())return t();let r=Ar.now();try{let i=t();return vn({type:"span",name:e,durationMs:Math.round(Ar.now()-r),ok:!0,...ks(n)??{}}),i}catch(i){throw vn({type:"span",name:e,durationMs:Math.round(Ar.now()-r),ok:!1,error:i instanceof Error?i.message:String(i),...ks(n)??{}}),i}}async function m3(e,t,n){if(!G())return t();let r=Ar.now();try{let i=await t();return vn({type:"span",name:e,durationMs:Math.round(Ar.now()-r),ok:!0,...ks(n)??{}}),i}catch(i){throw vn({type:"span",name:e,durationMs:Math.round(Ar.now()-r),ok:!1,error:i instanceof Error?i.message:String(i),...ks(n)??{}}),i}}function vn(e,t=xE()){let n=vE(e),r={timestamp:new Date().toISOString(),pid:process.pid,runId:Zp(),command:Qp(),cacheState:CE(),...n,...e},i=`${JSON.stringify(r)}
|
|
107
|
+
`;if(t)try{let o=SE(t);Gp.has(o)||(hE(o,{recursive:!0}),Gp.add(o)),gE(t,i);return}catch(o){Wp||(Wp=!0,process.stderr.write(`[profile] failed to write ${t}: ${o instanceof Error?o.message:String(o)}
|
|
108
|
+
`));return}G()&&process.stderr.write(i)}function vE(e){let t=eg()??RE({command:Qp()??"unknown",toolVersion:"unknown",projectFingerprint:null});if(!t)return{};let n=process.env[Ll],r=typeof e.name=="string"?e.name:void 0;if(!r)return{workloadIdentity:t,workloadIdentityKind:n};let i=r.split(/[.:]/,1)[0]??r,o=`${t}\0${r}`,s=Vp.get(o);return s||(s=ji(["profile-subsystem-v1",t,r]),Vp.set(o,s)),{workloadIdentity:t,workloadIdentityKind:n,subsystem:i,subsystemWorkIdentity:s}}function ks(e){return typeof e=="function"?e():e}import{spawnSync as IE}from"child_process";import{createHash as wE}from"crypto";import{existsSync as EE,lstatSync as DE,realpathSync as kE}from"fs";import{dirname as PE,isAbsolute as FE,join as TE,resolve as Fs}from"path";var Bi={run(e,t){let n=rg(e,t);return n.kind==="success"?n.output:void 0},runResult:rg},_E=["rev-parse","--show-toplevel","--absolute-git-dir","--git-common-dir","HEAD","HEAD^{tree}"],ng=/^[0-9a-f]{40,64}$/;function b3(e,t=Bi){let n=t.run(e,["rev-parse","--show-toplevel"])?.trim();return n?_t(n):void 0}function Nr(e,t=Bi){let n=t.runResult(e,_E);if(n.kind==="success"){let r=LE(n.output);if(r)return ME(r,t)}return AE(e,t)}function LE(e){let t=e.split(`
|
|
109
|
+
`).map(c=>c.trim());if(t.length!==5)return;let[n,r,i,o,s]=t;if(!n||!r||!i||!o||!s||!ng.test(o)||!ng.test(s))return;let a=_t(n);return{root:a,gitDir:_t(Ps(a,r)),commonDir:_t(Ps(a,i)),headCommit:o,treeOid:s}}function ME(e,t){let n=t.run(e.root,["status","--porcelain=v1","-z","--untracked-files=all"]);return n===void 0?void 0:{...ig(e.root,e.gitDir),commonDir:e.commonDir,repositoryId:Al("repository",e.commonDir),headCommit:e.headCommit,treeOid:e.treeOid,clean:n.length===0}}function AE(e,t){let n=NE(e,t);if(n.kind!=="worktree")return;let r=n.identity,i=r.projectRoot,o=t.run(i,["rev-parse","--git-common-dir"])?.trim();if(!o)return;let s=_t(Ps(i,o)),a=Ml(t.run(i,["rev-parse","--verify","HEAD"])),c=Ml(t.run(i,["rev-parse","--verify","HEAD^{tree}"])),l=t.run(i,["status","--porcelain=v1","-z","--untracked-files=all"]);if(l!==void 0)return{...r,commonDir:s,repositoryId:Al("repository",s),headCommit:a,treeOid:c,clean:l.length===0}}function NE(e,t=Bi){let n=t.runResult(e,["rev-parse","--show-toplevel"]);if(n.kind==="not-repository")return{kind:"non-git"};if(n.kind==="error")return n;let r=n.output.trim();if(!r)return{kind:"error",message:"Git returned an empty worktree root."};let i=_t(r),o=t.run(i,["rev-parse","--absolute-git-dir"])?.trim();if(!o)return{kind:"error",message:"Git did not return an absolute worktree directory."};let s=_t(Ps(i,o));return{kind:"worktree",identity:ig(i,s)}}function ig(e,t){return{projectRoot:e,gitDir:t,worktreeId:Al("worktree",`${e}\0${t}`)}}function og(e,t=Bi){let n=t.run(e,["worktree","list","--porcelain","-z"]);return n===void 0?[]:OE(n)}function OE(e){let t=[],n;for(let r of e.split("\0")){if(r===""){n&&t.push(n),n=void 0;continue}let i=r.indexOf(" "),o=i<0?r:r.slice(0,i),s=i<0?"":r.slice(i+1);if(o==="worktree"){n&&t.push(n),n={path:_t(s),detached:!1,bare:!1,prunable:!1,locked:!1};continue}n&&(o==="HEAD"?n.head=s:o==="branch"?n.branch=s:o==="detached"?n.detached=!0:o==="bare"?n.bare=!0:o==="prunable"?n.prunable=!0:o==="locked"&&(n.locked=!0))}return n&&t.push(n),t}function S3(e,t,n=Bi){return Ml(n.run(e,t))}function Ps(e,t){return FE(t)?t:Fs(e,t)}function _t(e){try{return kE(e)}catch{return Fs(e)}}function Al(e,t){return wE("sha256").update(`${e}\0${t}`).digest("hex").slice(0,24)}function Ml(e){return e?.trim()||void 0}function rg(e,t){let n=IE("git",["-C",e,...t],{encoding:"utf-8",env:{...process.env,LC_ALL:"C"},maxBuffer:52428800,stdio:["ignore","pipe","pipe"],timeout:3e4,killSignal:"SIGKILL"});if(n.status===0)return{kind:"success",output:n.stdout.trimEnd()};let i=(typeof n.stderr=="string"?n.stderr.trim():"")||n.error?.message||`git exited with status ${n.status??"unknown"}`,o=n.error?.code;return(/not a git repository/i.test(i)||o==="ENOENT"&&EE(Fs(e)))&&!jE(e)?{kind:"not-repository"}:{kind:"error",message:i}}function jE(e){if(process.env.GIT_DIR||process.env.GIT_COMMON_DIR)return!0;let t=Fs(e);for(;;){try{return DE(TE(t,".git")),!0}catch(r){let i=r.code;if(i!=="ENOENT"&&i!=="ENOTDIR")return!0}let n=PE(t);if(n===t)return!1;t=n}}var BE={"/":"namespace","#":"type",".":"term","[":"type-param",":":"meta","!":"macro"};function Re(e){if(e.startsWith("local "))return{kind:"local",id:e.slice(6),raw:e};let t=e.split(" ");if(t.length<4)return{scheme:t[0]??"",manager:t[1]??"",packageName:t[2]??"",version:"",descriptors:[],raw:e};let n=t[0],r=t[1],i=e.slice(n.length+1+r.length+1),o;if(i.startsWith("`")){let l=i.indexOf("`",1);l===-1?(o=i.slice(1),i=""):(o=i.slice(1,l),i=i.slice(l+2))}else{let l=i.indexOf(" ");l===-1?(o=i,i=""):(o=i.slice(0,l),i=i.slice(l+1))}let s,a=i.indexOf(" ");a===-1?(s=i,i=""):(s=i.slice(0,a),i=i.slice(a+1));let c=$E(i);return{scheme:n,manager:r,packageName:o,version:s,descriptors:c,raw:e}}function Lt(e){let t=Re(e);if("kind"in t)return null;for(let n=t.descriptors.length-2;n>=0;n--){let r=t.descriptors[n];if(r?.suffix==="type")return r.name}return null}function $E(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="["){let o=e.indexOf("]",n+1);if(o===-1){t.push({name:e.slice(n+1),suffix:"type-param"});break}t.push({name:e.slice(n+1,o),suffix:"type-param"}),n=o+1;continue}if(e[n]==="("&&(t.length===0||n===0||sg(e[n-1]))){let o=e.indexOf(")",n+1);if(o!==-1&&e[o+1]!=="."){t.push({name:e.slice(n+1,o),suffix:"parameter"}),n=o+1;continue}}let r;if(e[n]==="`"){let o=e.indexOf("`",n+1);if(o===-1){r=e.slice(n+1),t.push({name:r,suffix:"term"});break}r=e.slice(n+1,o),n=o+1}else{let o=n;for(;n<e.length&&!sg(e[n]);)n++;r=e.slice(o,n)}if(n>=e.length){r&&t.push({name:r,suffix:"term"});break}let i=e[n];if(i==="("){let o=e.indexOf(")",n+1);o!==-1&&e[o+1]==="."?(t.push({name:r,suffix:"method"}),n=o+2):o!==-1?(t.push({name:r,suffix:"method"}),n=o+1):(t.push({name:r,suffix:"term"}),n++)}else{let o=BE[i];o&&t.push({name:r,suffix:o}),n+=1}}return t}function sg(e){return e==="/"||e==="#"||e==="."||e==="("||e==="["||e===":"||e==="!"}function I(e){let t=Re(e);if("kind"in t&&t.kind==="local")return`local:${t.id}`;let n=t;if(n.descriptors.length===0)return n.raw;let r=[];for(let i of n.descriptors){let o=HE(i);o&&r.push(o)}return r.join(":")}function HE(e){let t=e.suffix==="namespace"?UE(e.name):e.name;return t?e.suffix==="method"?`${t}()`:t:""}function UE(e){return e.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/,"").replace(/\.(py|pyi)$/,"").replace(/\.(rs)$/,"").replace(/\.(java|scala|kt|kts)$/,"").replace(/\.(rb)$/,"").replace(/\.(go)$/,"").replace(/\.(cs|vb)$/,"").replace(/\.(dart)$/,"").replace(/\.(php)$/,"").replace(/\.(c|cc|cpp|cxx|h|hpp)$/,"")}function F(e){let t=Re(e);if("kind"in t&&t.kind==="local")return t.id;let n=t;return n.descriptors.length===0?"":n.descriptors[n.descriptors.length-1].name}function pe(e){let t=Re(e);if("kind"in t&&t.kind==="local")return null;let n=t;return n.descriptors[n.descriptors.length-1]?.suffix??null}function fe(e){return e.endsWith("().")||pe(e)==="method"}function oe(e){let t=pe(e);return t==="method"?!0:t!=="term"?!1:e.endsWith("().")?!0:e.startsWith("rust-analyzer ")&&e.includes("#")?!1:e.startsWith("scip-typescript ")?!/#[A-Za-z0-9_$]+\.$/.test(e):!0}function In(e){return pe(e)==="namespace"}var qE=/^rust-analyzer\b.*[\s/]impl#\[[^\]]+\]\[[^\]]+\]/;function Fe(e){return qE.test(e)}var GE=new Set(["test","tests","_tests"]);function Or(e){let t=Re(e);if("kind"in t)return!1;for(let n=0;n<t.descriptors.length-1;n+=1){let r=t.descriptors[n];if(r?.suffix==="namespace"&&r.name&&GE.has(r.name))return!0}return!1}function ag(e,t){let n=Re(e),r=Re(t);if("kind"in n||"kind"in r)return!1;let i=n.descriptors,o=r.descriptors;if(o.length!==i.length+1)return!1;for(let s=0;s<i.length;s++){let a=i[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}function cg(e,t){let n=Re(e),r=Re(t);if("kind"in n||"kind"in r)return!1;let i=n.descriptors,o=r.descriptors;if(o.length<=i.length)return!1;for(let s=0;s<i.length;s++){let a=i[s],c=o[s];if(a.name!==c.name||a.suffix!==c.suffix)return!1}return!0}import{extname as lg}from"path";var VE={".rs":"rust",".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".pyi":"python",".java":"java",".kt":"kotlin",".kts":"kotlin",".scala":"scala",".sc":"scala",".rb":"ruby",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".cxx":"cpp",".hpp":"cpp",".hh":"cpp",".hxx":"cpp",".cs":"csharp",".php":"php",".vb":"vb",".clj":"clojure",".cljs":"clojure",".cljc":"clojure"};function N(e){return VE[lg(e).toLowerCase()]??null}function Yt(e){return lg(e).toLowerCase()===".vue"}import{createRequire as WE}from"module";var $e=WE(import.meta.url),$i=null,Nl=!1;function ug(){if(Nl)return null;if($i)return $i;try{return $i=$e("tree-sitter"),$i}catch{return Nl=!0,null}}function w3(e){if(e==="clojure")return"reader";let t=ug();if(!t)return"unavailable";let n=dg(e);if(!n)return"unavailable";try{return new t().setLanguage(n),"ast"}catch{return jr.add(e),"unavailable"}}var Ol=new Map,jr=new Set;function dg(e){if(jr.has(e))return null;let t=Ol.get(e);if(t)return t;let n;try{switch(e){case"rust":n=$e("tree-sitter-rust");break;case"typescript":n=$e("tree-sitter-typescript").typescript;break;case"tsx":n=$e("tree-sitter-typescript").tsx;break;case"javascript":n=$e("tree-sitter-javascript");break;case"python":n=$e("tree-sitter-python");break;case"java":n=$e("tree-sitter-java");break;case"kotlin":n=$e("tree-sitter-kotlin");break;case"scala":n=$e("tree-sitter-scala");break;case"ruby":n=$e("tree-sitter-ruby");break;case"c":n=$e("tree-sitter-c");break;case"cpp":n=$e("tree-sitter-cpp");break;case"csharp":n=$e("tree-sitter-c-sharp");break;case"php":n=$e("tree-sitter-php").php;break;case"vb":{let r=$e("tree-sitter-vb-dotnet");n=r.language??r;break}case"clojure":return jr.add(e),null}}catch{return jr.add(e),null}return Ol.set(e,n),n}var jl=new Map;function E3(){$i=null,Nl=!1,Ol.clear(),jr.clear(),jl.clear(),JE.clear()}function zE(e){let t=jl.get(e);if(t)return t;let n=dg(e);if(!n)return null;let r=ug();if(!r)return null;let i=new r;try{i.setLanguage(n)}catch{return jr.add(e),null}return jl.set(e,i),i}function KE(e,t){return e.parse(r=>r>=t.length?null:t.slice(r,Math.min(t.length,r+16384)))}function Hi(e,t){let n=zE(e);if(!n)return null;try{return KE(n,t)}catch{return null}}var JE=new Map;import{readFileSync as YE}from"fs";import{join as XE}from"path";var QE=B("source-text",{clearGroups:["whole-project","source-file"]}),ZE=B("source-lines",{clearGroups:["whole-project","source-file"]});function P(e,t){let n=t.replace(/\\/g,"/");return QE.get(e,n,()=>{let r=XE(e.config.projectRoot,n);try{return YE(r,"utf-8")}catch(i){if(eD(i))return"";throw i}})}function eD(e){return typeof e=="object"&&e!==null&&"code"in e&&(e.code==="ENOENT"||e.code==="ENOTDIR")}function Ee(e,t){let n=t.replace(/\\/g,"/");return ZE.get(e,n,()=>{let r=P(e,n);return r?r.split(`
|
|
110
|
+
`):[]})}var tD=/^\s*(?:\/\/|#|\/\*+|\*)\s*scip-query[\s:-]*ignore(?:[\s:-]+(dead(?:-code)?|stale|wrapper|passthrough|drift|extract|similar|twin))?\b/i;function Ui(e){let t=tD.exec(e);return t?t[1]??"":null}function Ts(e,t,n){return mg(e,t,n).length>0}function _s(e,t,n,r){let i=r.toLowerCase();return mg(e,t,n).some(o=>o.toLowerCase()===i)}function mg(e,t,n){if(n<=0)return[];let r=Ee(e,t);if(r.length===0)return[];let i=[];for(let o=n-1;o>=0&&o>=n-5;o-=1){let s=(r[o]??"").trim();if(s==="")continue;let a=Ui(s);if(a!==null){i.push(a);continue}if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return i}return i}import{posix as Bl}from"path";import{parse as nD}from"@vue/compiler-sfc";var rD=Rn("vue-sfc-units");function Br(e,t){let n=gg(t),r=P(e,n);return rD.get(e,n,r,()=>$l(e,n,r))}function gg(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function iD(e){let t=e?.toLowerCase();return!t||t==="js"||t==="javascript"||t==="jsx"?"javascript":t==="ts"||t==="typescript"?"typescript":t==="tsx"?"tsx":null}function er(e){return!e||e.body.length===0?0:e.body.split(`
|
|
111
|
+
`).length}function $l(e,t,n){let r={relativePath:t,template:null,scripts:[],styles:[],customBlocks:[],errors:[]};if(!n)return r;let i;try{i=nD(n,{filename:t})}catch(s){return r.errors.push(pg(s)),r}r.errors.push(...i.errors.map(pg));let{descriptor:o}=i;return o.template&&(r.template=Ls(e,t,"template",o.template)),o.script&&r.scripts.push(fg(e,t,o.script,!1)),o.scriptSetup&&r.scripts.push(fg(e,t,o.scriptSetup,!0)),r.styles=o.styles.map(s=>Ls(e,t,"style",s)),r.customBlocks=o.customBlocks.map(s=>Ls(e,t,"custom",s)),r.errors.push(...[r.template,...r.scripts,...r.styles,...r.customBlocks].flatMap(s=>s?.errors??[])),r}function fg(e,t,n,r){let i=Ls(e,t,"script",n);return{...i,kind:"script",setup:r,astLanguage:iD(i.lang)}}function Ls(e,t,n,r){let i=sD(r.attrs),o=typeof i.lang=="string"?i.lang:null,s=typeof i.src=="string"?i.src:typeof r.src=="string"?r.src:void 0;if(s){let c=oD(t,s);if(!c)return{kind:n,ownerPath:t,sourcePath:t,external:!0,src:s,attrs:i,lang:o,body:"",startLine:0,endLine:0,errors:[`Could not resolve Vue ${n} block source: ${s}`]};let l=P(e,c),u=l?Math.max(0,l.split(`
|
|
112
|
+
`).length-1):0;return{kind:n,ownerPath:t,sourcePath:c,external:!0,src:s,attrs:i,lang:o,body:l,startLine:0,endLine:u,errors:l?[]:[`Vue ${n} block source not found: ${c}`]}}let a=Math.max(0,r.loc.start.line-1);return{kind:n,ownerPath:t,sourcePath:t,external:!1,attrs:i,lang:o,body:r.content,startLine:a,endLine:Math.max(a,r.loc.end.line-1),errors:[]}}function oD(e,t){let n=t.split(/[?#]/,1)[0];if(!n||n.startsWith("/")||n.includes("://"))return null;let r=gg(Bl.normalize(Bl.join(Bl.dirname(e),n)));return r===".."||r.startsWith("../")?null:r}function sD(e){return{...e}}function pg(e){return e instanceof Error?e.message:String(e)}function Ms(e,t,n){let i=$l(e,t,n).scripts.filter(s=>s.astLanguage&&s.body.length>0),o=i[0]?.astLanguage;return o?{body:i.map(s=>`${`
|
|
113
|
+
`.repeat(s.startLine)}${s.body}`).join(`
|
|
114
|
+
`),startLine:0,language:o}:null}var hg=Zn("ast-trees",{clearGroups:["whole-project","source-file"]});function Y(e,t){if(Yt(t))return aD(e,t);let n=N(t);if(!n)return null;let r=P(e,t);return r?hg.get(e,t,r,()=>Hi(n,r)):null}function aD(e,t){let n=P(e,t);return n?hg.get(e,t,n,()=>{let r=Ms(e,t,n);if(!r)return null;let i=`
|
|
115
|
+
`.repeat(r.startLine)+r.body;return Hi(r.language,i)}):null}function $r(e,t){let n=cD(e,t);if(!n)return null;let r=tr(n);return r?{calleeLeaf:r,memberAccess:lD(n),line:e.startPosition.row}:null}function cD(e,t){if(t==="rust")return e.type==="call_expression"?e.childForFieldName("function")??e.namedChild(0):e.type==="macro_invocation"?e.childForFieldName("macro")??e.namedChild(0):null;if(t==="python")return e.type!=="call"?null:e.childForFieldName("function")??e.namedChild(0);if(t==="typescript"||t==="tsx"||t==="javascript"){if(e.type==="call_expression")return e.childForFieldName("function")??e.namedChild(0);if(e.type==="new_expression")return e.childForFieldName("constructor")??e.namedChild(0)}return null}function lD(e){switch(e.type){case"field_expression":case"member_expression":case"attribute":return!0;default:return!1}}function tr(e){switch(e.type){case"identifier":case"type_identifier":case"field_identifier":case"property_identifier":case"shorthand_property_identifier":return e.text;case"field_expression":case"member_expression":case"attribute":{let t=e.namedChild(e.namedChildCount-1);return t?tr(t):null}case"generic_function":{let t=e.childForFieldName("function")??e.namedChild(0);return t?tr(t):null}case"scoped_identifier":{let t=e.childForFieldName("name")??e.namedChild(e.namedChildCount-1);return t?tr(t):null}case"super":case"self":case"this":return null;default:return null}}var uD=[We("source-facts",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/source/source-facts.ts"}),We("file-definitions",{dependsOn:["content-hash","project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","contentHash","projectFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/symbols/definition-catalog.ts"}),We("definition-exclusions",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/analysis/framework-patterns.ts"}),We("doc-path-tokens",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-products.test.ts",owner:"tests/storage/evidence-cache.test.ts"}),We("doc-path-evidence",{dependsOn:["content-hash","git-history","git-head","tool-version"],keyParts:["kind","relativePath","contentHash","trackedFiles","historyWindow","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/queries/cleanup/doc-drift.ts"}),We("source-imports",{dependsOn:["content-hash","import-resolution-fingerprint","config","tool-version"],keyParts:["kind","relativePath","contentHash","importResolutionFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/language-parsers/index.ts"}),We("source-reexports",{dependsOn:["content-hash","import-resolution-fingerprint","config","tool-version"],keyParts:["kind","relativePath","contentHash","importResolutionFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/language-parsers/index.ts"}),We("source-fingerprints",{dependsOn:["content-hash","project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","contentHash","projectFingerprint","payloadVersion"],stalenessTest:"tests/symbols/definition-catalog.test.ts",owner:"src/queries/cleanup/similar.ts"}),We("consumer-file-usage",{dependsOn:["content-hash","project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","contentHash","projectFingerprint","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/queries/internal/consumer-evidence.ts"}),We("react-component-behavior-profiles",{dependsOn:["content-hash","tool-version"],keyParts:["kind","relativePath","contentHash","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/source/react-profile.ts"}),We("git-file-adds",{dependsOn:["git-head","git-history","tool-version"],keyParts:["kind","cacheKey","head","historyWindow","payloadVersion"],stalenessTest:"tests/storage/evidence-cache.test.ts",owner:"src/analysis/git-history.ts"}),We("typescript-reference-fragments",{dependsOn:["content-hash","transitive-deps-digest","config","tool-version"],keyParts:["kind","relativePath","semanticIdentity","payloadVersion"],stalenessTest:"tests/semantic/typescript/typescript-reference-fragments.test.ts",owner:"src/semantic/typescript/reference-fragment-shadow.ts"}),We("typescript-import-usage",{dependsOn:["content-hash","transitive-deps-digest","config","tool-version"],keyParts:["kind","relativePath","semanticIdentity","payloadVersion"],stalenessTest:"tests/semantic/typescript/typescript-semantic-provider.test.ts",owner:"src/semantic/shared-primitives.ts"}),We("typescript-signatures",{dependsOn:["content-hash","transitive-deps-digest","config","tool-version"],keyParts:["kind","relativePath","semanticIdentity","payloadVersion"],stalenessTest:"tests/semantic/typescript/typescript-semantic-provider.test.ts",owner:"src/semantic/shared-primitives.ts"}),As("file-dependency-graph",{dependsOn:["project-fingerprint","indexed-language-set","import-resolution-fingerprint","tool-version"],keyParts:["kind","scope","projectFingerprint","payloadVersion"],stalenessTest:"tests/symbols/file-dep-graph.test.ts",owner:"src/symbols/graph/file-dep-graph.ts"}),As("semantic-import-usage",{dependsOn:["project-fingerprint","indexed-language-set","import-resolution-fingerprint","tool-version"],keyParts:["kind","relativePath","projectFingerprint","language","semanticEngine","payloadVersion"],stalenessTest:"tests/semantic/rust/rust-semantic-cache-gate.test.ts",owner:"src/semantic/shared-primitives.ts"}),As("semantic-signatures",{dependsOn:["project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","relativePath","symbol","projectFingerprint","language","semanticEngine","payloadVersion"],stalenessTest:"tests/semantic/rust/rust-semantic-cache-gate.test.ts",owner:"src/semantic/shared-primitives.ts"}),As("health-semantic-prewarm",{dependsOn:["project-fingerprint","indexed-language-set","tool-version"],keyParts:["kind","scope","cliVersion","projectFingerprint","payloadVersion"],stalenessTest:"tests/runtime/cli-support.test.ts",owner:"src/runtime/cli-support.ts"})];function ce(e){let t=new Map;return{kind:e.kind,read(n,r,i){let o=!1,s=0,a;if(G()){let c=Ne(n);if(c){let l=`${c}\0${r}\0${i}`;a=t.get(l),a||(a=ji(["evidence-product-file-read-v1",e.kind,c,r,i]),t.set(l,a))}}return E("evidence-product.file.read",()=>{let c=Lp(n,e.kind,r,i);if(c===null)return null;s=c.length;try{let l=e.deserialize(c);return o=l!==null,l}catch{return null}},()=>({...a?{workIdentity:a,workOutcome:"computed"}:{},scope:"file",kind:e.kind,available:!0,hit:o,payloadBytes:s}))},write(n,r,i,o){Mp(n,e.kind,r,i,e.serialize(o))},writeBatch(n,r){Ap(n,r.map(i=>({kind:e.kind,relativePath:i.relativePath,contentHash:i.contentHash,payload:e.serialize(i.value)})))}}}function nr(e){let t=new Map;return{kind:e.kind,read(n,r,i){let o=!1,s=0,a;if(G()){let c=`${i}\0${r}`;a=t.get(c),a||(a=ji(["evidence-product-project-read-v1",e.kind,i,r]),t.set(c,a))}return E("evidence-product.project.read",()=>{let c=Np(n,e.kind,r,i);if(c===null)return null;s=c.length;try{let l=e.deserialize(c);return o=l!==null,l}catch{return null}},()=>({...a?{workIdentity:a,workOutcome:"computed"}:{},scope:"project",kind:e.kind,available:!0,hit:o,payloadBytes:s}))},write(n,r,i,o){Op(n,e.kind,r,i,e.serialize(o))}}}function X(e){let t=uD.find(n=>n.kind===e);if(!t)throw new Error(`missing evidence product manifest entry for ${e}`);return t.invalidation}function We(e,t){return{scope:"file",kind:e,invalidation:{scope:"file",...t}}}function As(e,t){return{scope:"project",kind:e,invalidation:{scope:"project",...t}}}function qi(e){return e.type==="comment"||e.type==="line_comment"||e.type==="block_comment"}var dD=new Set(["function_declaration","method_definition","method_signature","function_signature"]);function Ns(e,t){let n=fD(e,t);if(n)return{name:n.name,startLine:n.definitionNode.startPosition.row,endLine:n.definitionNode.endPosition.row,paramCount:Sg(n.functionNode),params:yg(n.functionNode),paramsEndLine:bg(n.functionNode),isLiteralPassthrough:xg(n.functionNode,t)};if(!mD(e.type,t))return null;let r=e.childForFieldName("name")??e.namedChildren.find(i=>i.type==="identifier"||i.type==="property_identifier");return r?{name:r.text,startLine:e.startPosition.row,endLine:e.endPosition.row,paramCount:Sg(e),params:yg(e),paramsEndLine:bg(e),isLiteralPassthrough:xg(e,t)}:null}function Cg(e){return e.namedChildren.find(t=>t.type==="parameters"||t.type==="formal_parameters")}function yg(e){let t=Cg(e);if(!t)return[];let n=[];for(let r of t.namedChildren){if(qi(r))continue;if(r.type==="identifier"){n.push({name:r.text,simple:!0});continue}let i=r.namedChildren.some(a=>a.type.endsWith("_modifier"))||/^\s*(?:public|private|protected|readonly|override)\b/.test(r.text),o=r.childForFieldName("pattern");if(!i&&o&&o.type==="identifier"){n.push({name:o.text,simple:!0});continue}let s=r.namedChildren.find(a=>a.type==="identifier");n.push({name:o?.type==="identifier"?o.text:s?.text??"",simple:!1})}return n}function bg(e){let t=Cg(e);return t?t.endPosition.row:e.startPosition.row}function mD(e,t){return t==="rust"?e==="function_item"||e==="function_signature_item":t==="python"?e==="function_definition":t==="typescript"||t==="tsx"||t==="javascript"?dD.has(e):!1}function fD(e,t){if(t!=="typescript"&&t!=="tsx"&&t!=="javascript")return null;if(e.type==="variable_declarator"){let n=e.childForFieldName("name")??e.namedChild(0),r=e.childForFieldName("value")??e.namedChild(1);return!n||!r||r.type!=="arrow_function"&&r.type!=="function_expression"?null:{name:n.text,definitionNode:e,functionNode:r}}if(e.type==="public_field_definition"){let n=e.childForFieldName("name")??e.namedChild(0),r=e.childForFieldName("value")??e.namedChild(1);return!n||!r||r.type!=="arrow_function"&&r.type!=="function_expression"?null:{name:n.text,definitionNode:e,functionNode:r}}return null}function Sg(e){let t=e.namedChildren.find(r=>r.type==="parameters"||r.type==="formal_parameters");if(!t)return 0;let n=0;for(let r of t.namedChildren)qi(r)||(n+=1);return n}function xg(e,t){let n=e.namedChildren.find(d=>d.type==="block"||d.type==="statement_block");if(!n)return!1;let r=n.namedChildren.filter(d=>!qi(d));if(r.length!==1)return!1;let i=r[0],o=null;if(i.type==="return_statement"||i.type==="expression_statement"?o=i.namedChild(0)??null:t==="rust"&&(i.type==="call_expression"||i.type==="macro_invocation")&&(o=i),!o)return!1;let s=t==="python"?"call":"call_expression";if(o.type!==s)return!1;let a=o.namedChildren.find(d=>d.type==="arguments"||d.type==="argument_list");if(!a)return!1;let c=a.namedChildren.filter(d=>!qi(d)),l=e.namedChildren.find(d=>d.type==="parameters"||d.type==="formal_parameters");if(!l)return!1;let u=[];for(let d of l.namedChildren){if(d.type==="identifier"){u.push(d.text);continue}let m=d.namedChildren.find(f=>f.type==="identifier");m&&u.push(m.text)}if(c.length!==u.length)return!1;for(let d=0;d<u.length;d+=1){let m=c[d];if(m.type!=="identifier"||m.text!==u[d])return!1}return!0}var pD=new Set(["identifier","type_identifier","field_identifier"]),gD=new Set(["identifier"]),hD=new Set(["identifier","property_identifier","type_identifier","shorthand_property_identifier","shorthand_property_identifier_pattern"]),yD=new Set(["rust","python"]),bD=/\{([^{}]*)\}/g,SD=/\b([A-Za-z_][\w]*)\b/g;function Rg(e,t){return xD(t).has(e.type)}function vg(e,t){return yD.has(t)&&e.type==="string_content"}function Hl(e){let t=0;for(let r of e.values()){let i=r[r.length-1];i!==void 0&&i>t&&(t=i)}let n=new Array(t+1);for(let r=0;r<=t;r+=1)n[r]=new Set;for(let[r,i]of e)for(let o of i)n[o].add(r);return n}function xD(e){return e==="rust"?pD:e==="python"?gD:hD}function Ig(e,t){let n=e.startPosition.row;for(let r of e.text.matchAll(bD)){let i=r[1]??"";for(let o of i.matchAll(SD))o[1]&&t(o[1],n)}}var CD=[/\bdefault\s*=\s*"([^"]+)"/g,/\bwith\s*=\s*"([^"]+)"/g,/\bserialize_with\s*=\s*"([^"]+)"/g,/\bdeserialize_with\s*=\s*"([^"]+)"/g,/\bskip_serializing_if\s*=\s*"([^"]+)"/g,/\bgetter\s*=\s*"([^"]+)"/g,/\brename_all_with\s*=\s*"([^"]+)"/g,/\bschema_with\s*=\s*"([^"]+)"/g],RD=/^#!?\[\s*serde\s*\(/,vD=/^#!?\[\s*schemars\s*\(/,ID=/^#!?\[\s*validate\s*\(/,wD=new Set(["invoke","invokeTauriCommand","listen","once","emit","subscribe","dispatch","sendCommand","callRust"]);function wg(e,t,n){if(t!=="typescript"&&t!=="tsx"&&t!=="javascript"||e.type!=="call_expression")return;let r=e.childForFieldName("function")??e.namedChild(0);if(!r)return;let i=tr(r);if(!i||!wD.has(i))return;let o=e.namedChildren.find(c=>c.type==="arguments");if(!o)return;let s=o.namedChild(0);if(!s||s.type!=="string")return;let a=s.namedChildren.find(c=>c.type==="string_fragment");a&&n.add(a.text)}function Eg(e,t){let n=RD.test(e),r=vD.test(e),i=ID.test(e);if(!(!n&&!r&&!i))for(let o of CD){o.lastIndex=0;let s;for(;(s=o.exec(e))!==null;){let a=s[1],c=a.split("::").pop()??a;c==="is_none"&&/\bOption\b/.test(a)||c==="is_empty"&&/\b(String|Vec|HashMap|BTreeMap|HashSet|BTreeSet)\b/.test(a)||c&&t.add(c)}}}function Dg(e,t){let n=new Map,r=(s,a)=>{if(s===a)return;let c=n.get(s);c||(c=new Set,n.set(s,c)),c.add(a)},i=t==="python"?new Set(["identifier"]):new Set(["type_identifier"]),o=(s,a)=>{let c=l=>{i.has(l.type)&&l.text!==a&&r(l.text,a);for(let u of l.children)c(u)};for(let l of s.children)c(l)};if(t==="rust")for(let s of e.rootNode.descendantsOfType(["struct_item","enum_item","union_item","type_item"])){let a=s.namedChildren.find(l=>l.type==="type_identifier")?.text;if(!a)continue;let c=s.namedChildren.find(l=>l.type==="field_declaration_list"||l.type==="enum_variant_list"||l.type==="ordered_field_declaration_list");c&&o(c,a),s.type==="type_item"&&o(s,a)}else if(t==="python")for(let s of e.rootNode.descendantsOfType("class_definition")){let a=s.namedChildren.find(u=>u.type==="identifier")?.text;if(!a)continue;let c=s.childForFieldName("superclasses");c&&o(c,a);let l=s.namedChildren.find(u=>u.type==="block");if(l)for(let u of l.descendantsOfType("type"))for(let d of u.descendantsOfType("identifier"))d.text!==a&&r(d.text,a)}else for(let s of e.rootNode.descendantsOfType(["interface_declaration","type_alias_declaration","class_declaration"])){let a=s.namedChildren.find(c=>c.type==="type_identifier")?.text;a&&o(s,a)}return n}var ED=new Map([["defn","function"],["defn-","function"],["defmacro","macro"],["defmacro-","macro"],["defmethod","method"]]),Ul=new Set(["catch","comment","def","defprotocol","defrecord","deftype","defmethod","defmacro","defmacro-","defn","defn-","do","doseq","dotimes","fn","for","if","let","loop","ns","quote","recur","throw","try","extend-protocol","extend-type","when","when-let","when-not"]);function kg(e){let t=[],n=[],r=[],i=new Map,o=[],s=0,a=0,c=(l,u)=>{let d=i.get(l);if(!d){i.set(l,[u]);return}d[d.length-1]!==u&&d.push(u)};for(;a<e.length;){let l=e[a];if(l===`
|
|
116
|
+
`){s+=1,a+=1;continue}if(/\s|,/.test(l)){a+=1;continue}if(l===";"){a=js(e,a);continue}if(l==='"'){let p=Vi(e,a,s);s=p.line,a=p.index;continue}if(l==="("||l==="["||l==="{"){o.push({kind:l,startLine:s,endLine:s,headTokens:[],tokens:[],children:[]}),a+=1;continue}if(l===")"||l==="]"||l==="}"){let p=o.pop();p&&(p.endLine=s,DD(p,{callables:t,callSites:n,clojureMembers:r,recordIdentifier:c}),o[o.length-1]?.children.push(p)),a+=1;continue}if(ql(l)){a+=1;continue}let u=s,d=a;for(;a<e.length&&!Gl(e[a]);)a+=1;let m=e.slice(d,a);if(!m)continue;let f={text:m,line:u};kD(o[o.length-1],f),c(ot(m),u)}return{language:"clojure",callables:t,callSites:n,clojureMembers:r,typeContainerMap:new Map,identifierLineMap:i,identifiersByLine:LD(i),fileIdentifiers:new Set(i.keys()),rustAttrReferencedNames:new Set,crossLanguageDispatchNames:new Set}}function DD(e,t){if(e.kind!=="("||e.headTokens.length===0)return;let n=e.headTokens[0],r=ot(n.text),i=ED.get(n.text);if(i){let s=e.headTokens[1];if(s){let a=ot(s.text);t.recordIdentifier(a,s.line),t.callables.push({name:a,startLine:e.startLine,endLine:e.endLine,paramCount:0,params:[],paramsEndLine:s.line,isLiteralPassthrough:!1,clojureKind:i})}}if(PD(e,t),!r||Ul.has(n.text)||Ul.has(r)||r.startsWith(":"))return;let o=_D(n.text);t.callSites.push({calleeLeaf:o.leaf,calleeQualifier:o.qualifier,calleeText:o.text,memberAccess:!1,line:n.line})}function kD(e,t){e&&(e.headTokens.length<2&&e.headTokens.push(t),e.tokens.length<200&&e.tokens.push(t))}function PD(e,t){let n=ot(e.tokens[0]?.text??"");if(n==="defprotocol"){let r=ot(e.tokens[1]?.text??"");if(!r)return;for(let i of Os(e))Gi(t,r,"protocol",i,"protocol-method");return}if(n==="defrecord"||n==="deftype"){let r=ot(e.tokens[1]?.text??"");if(!r)return;let i=n==="defrecord"?"record":"type",o=n==="defrecord"?"record-method":"type-method";for(let s of Os(e))Gi(t,r,i,s,o);return}if(n==="extend-type"){let r=ot(e.tokens[1]?.text??"");if(!r)return;for(let i of Os(e))Gi(t,r,"extension",i,"extension-method");return}if(n==="extend-protocol"){let r=ot(e.tokens[1]?.text??"");for(let i of Os(e)){r&&Gi(t,r,"extension",i,"extension-method");let o=TD(e,i.startLine);o&&o!==r&&Gi(t,o,"extension",i,"extension-method")}}}function Os(e){return e.children.filter(FD)}function FD(e){if(e.kind!=="(")return!1;let t=ot(e.tokens[0]?.text??"");return!!(t&&!Ul.has(t)&&!t.startsWith(":"))}function Gi(e,t,n,r,i){let o=r.tokens[0],s=ot(o?.text??"");!o||!s||(e.recordIdentifier(s,o.line),e.clojureMembers.push({ownerName:t,ownerKind:n,memberName:s,memberKind:i,startLine:r.startLine,endLine:r.endLine}))}function TD(e,t){let n=null;for(let r=2;r<e.tokens.length;r+=1){let i=e.tokens[r];if(i.line>t)break;let o=ot(i.text);o&&!o.startsWith(":")&&(n=o)}return n}function ot(e){return e.replace(/^#?['`~@]+/,"").split("/").pop()?.replace(/^\./,"")??""}function _D(e){let t=e.replace(/^#?['`~@]+/,""),n=t.lastIndexOf("/"),r=ot(t);if(n<=0)return{leaf:r,text:t};let i=t.slice(0,n);return{leaf:r,qualifier:i,text:t}}function js(e,t){let n=t;for(;n<e.length&&e[n]!==`
|
|
117
|
+
`;)n+=1;return n}function Vi(e,t,n){let r=t+1,i=n;for(;r<e.length;){let o=e[r];if(o==="\\"){r+=2;continue}if(o===`
|
|
118
|
+
`&&(i+=1),r+=1,o==='"')break}return{index:r,line:i}}function ql(e){return e==="'"||e==="`"||e==="~"||e==="@"||e==="^"||e==="#"}function Gl(e){return/\s|,/.test(e)||e==="("||e===")"||e==="["||e==="]"||e==="{"||e==="}"||e==='"'||e===";"}function LD(e){let t=[];for(let[n,r]of e)for(let i of r)t[i]??=new Set,t[i].add(n);return t}var Pg=3,MD=Zn("source-facts",{clearGroups:["whole-project","source-file"]}),Vl=ce({kind:"source-facts",invalidation:X("source-facts"),serialize:OD,deserialize:jD});function z(e,t){return Wl(e,t).facts}function Wl(e,t){let n=P(e,t);if(!n)return{facts:null};let r=AD(e,t,n);return r?MD.get(e,t,n,()=>ND(e,t,r,n)):{facts:null}}function AD(e,t,n){return Yt(t)?Ms(e,t,n)?.language??null:N(t)}function ND(e,t,n,r){let i=me(e,t,r),o=Vl.read(e,t,i);if(o&&o.language===n)return{facts:o};if(n==="clojure"){let c=kg(r);return Vl.write(e,t,i,c),{facts:c}}let s=Y(e,t);if(!s)return{facts:null,unavailable:{language:n,reason:"parser-unavailable"}};let a=$D(s,n);return Vl.write(e,t,i,a),{facts:a}}function OD(e){let t={version:Pg,language:e.language,callables:e.callables,callSites:e.callSites,clojureMembers:e.clojureMembers,typeContainerMap:[...e.typeContainerMap.entries()].map(([n,r])=>[n,[...r]]),identifierLineMap:[...e.identifierLineMap.entries()],rustAttrReferencedNames:[...e.rustAttrReferencedNames],crossLanguageDispatchNames:[...e.crossLanguageDispatchNames]};return JSON.stringify(t)}function jD(e){try{let t=JSON.parse(e);if(t.version!==Pg||t.language==="clojure"&&(t.clojureMembers===void 0||t.callSites.some(r=>r.calleeText===void 0)))return null;let n=new Map(t.identifierLineMap);return{language:t.language,callables:t.callables,callSites:t.callSites,clojureMembers:t.clojureMembers??[],typeContainerMap:new Map(t.typeContainerMap.map(([r,i])=>[r,new Set(i)])),identifierLineMap:n,identifiersByLine:Hl(n),fileIdentifiers:new Set(n.keys()),rustAttrReferencedNames:new Set(t.rustAttrReferencedNames),crossLanguageDispatchNames:new Set(t.crossLanguageDispatchNames)}}catch{return null}}function zl(e,t,n,r){let i=z(e,t);return i?BD(i,n,r)?.isLiteralPassthrough??!0:!0}function Wi(e,t){return t.relativePath.includes(".clj-kondo/hooks/")?!0:z(e,t.relativePath)?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine)?.clojureKind==="macro"}function BD(e,t,n){return e.callables.find(r=>r.startLine===t&&r.endLine===n)??null}function $D(e,t){let n=[],r=[],i=new Set,o=new Set,s=new Map,a=(l,u)=>{let d=s.get(l);if(!d){s.set(l,[u]);return}d[d.length-1]!==u&&d.push(u)},c=l=>{let u=Ns(l,t);u&&n.push(u);let d=$r(l,t);d&&r.push(d),wg(l,t,o),t==="rust"&&(l.type==="attribute_item"||l.type==="inner_attribute_item")&&Eg(l.text,i),Rg(l,t)&&a(l.text,l.startPosition.row),vg(l,t)&&Ig(l,a);for(let m of l.children)c(m)};return c(e.rootNode),{language:t,callables:n,callSites:r,clojureMembers:[],typeContainerMap:Dg(e,t),identifierLineMap:s,identifiersByLine:Hl(s),fileIdentifiers:new Set(s.keys()),rustAttrReferencedNames:i,crossLanguageDispatchNames:o}}var Fg=new Set(["rust","typescript","tsx","javascript","python","clojure"]);function Kl(e,t){let n=z(e,t);return!n||!Fg.has(n.language)?null:n.callables.map(r=>({name:r.name,startLine:r.startLine,endLine:r.endLine}))}function wn(e,t){let n=z(e,t);return!n||!Fg.has(n.language)?null:n.callSites}function Jl(e,t){return z(e,t)?.typeContainerMap??new Map}import{ElementTypes as UD,NodeTypes as Yl,parse as qD}from"@vue/compiler-dom";import{parse as w8}from"@vue/compiler-sfc";var HD=new Set(["children","className","data","e","err","error","ev","event","false","id","idx","index","item","key","null","props","res","result","state","style","true","undefined","val","value"]);function Bs(e){return e.length<=2||HD.has(e)}function $s(e,t){return e.split(t).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}var GD=Rn("vue-template-facts"),VD=new Set(["component","keep-alive","slot","suspense","teleport","template","transition","transition-group"]),WD=new Set(["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","link","main","map","mark","menu","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","param","picture","pre","progress","q","rp","rt","ruby","s","samp","script","search","section","select","slot","small","source","span","strong","style","sub","summary","sup","svg","table","tbody","td","template","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr"]),zD=new Set(["div","span","template"]),KD=new Set(["as","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","export","extends","false","finally","for","from","function","if","import","in","instanceof","let","new","null","of","return","super","switch","this","throw","true","try","typeof","undefined","var","void","while","with","yield"]);function Hs(e,t){let n=t.replace(/\\/g,"/"),r=P(e,n);return GD.get(e,n,r,()=>JD(n,Br(e,n).template))}function JD(e,t){let n={relativePath:e,template:t?{startLine:t.startLine,endLine:t.endLine}:null,componentTags:[],nativeTags:[],builtinTags:[],props:[],events:[],directives:[],slots:[],expressionIdentifiers:[],structuralTokens:[]};if(!t)return n;let r;try{r=qD(t.body,{comments:!1})}catch{return n}let i=new Set,o=s=>{s.trim()&&i.add(s)};return _g(r.children,t.startLine,n,o),n.structuralTokens=[...i].sort(),n}function _g(e,t,n,r){for(let i of e)if(i.type===Yl.ELEMENT)YD(i,t,n,r),_g(i.children,t,n,r);else if(i.type===Yl.INTERPOLATION){r("interpolation");let o=Xl(i.content);o&&Lg(o,t,i.loc.start.line,n,r)}}function YD(e,t,n,r){let i=rk(e.tag),o={tag:e.tag,normalized:i,kind:nk(e),startLine:Hr(t,e.loc.start.line),endLine:Hr(t,e.loc.end.line)};o.kind==="component"?(n.componentTags.push(o),r(`component:${i}`)):o.kind==="builtin"?(n.builtinTags.push(o),r(`builtin:${i}`)):(n.nativeTags.push(o),zD.has(e.tag)||r(`native:${e.tag}`));for(let s of e.props)XD(s,t,n,r)}function XD(e,t,n,r){if(e.type===Yl.ATTRIBUTE){let a=e.value?.content??null,c=Tg("prop",e.name,a,t,e.loc.start.line,e.loc.end.line);n.props.push(c),r(`prop:${e.name}`);return}let i=ZD(e),o=Xl(e.exp),s=Tg(QD(e.name),i,o,t,e.loc.start.line,e.loc.end.line);switch(s.kind){case"prop":n.props.push(s),r(`prop:${i}`);break;case"event":n.events.push(s),r(`event:${i}`);break;case"slot":n.slots.push(s),r(`slot:${i}`);break;case"directive":n.directives.push(s),r(`directive:${i}`);break}o&&Lg(o,t,e.loc.start.line,n,r)}function Tg(e,t,n,r,i,o){return{kind:e,name:t,value:n,startLine:Hr(r,i),endLine:Hr(r,o)}}function QD(e){switch(e){case"bind":case"model":return"prop";case"on":return"event";case"slot":return"slot";default:return"directive"}}function ZD(e){let t=Xl(e.arg);return t||e.name}function Xl(e){if(!e)return null;let t=("content"in e&&typeof e.content=="string"?e.content:e.loc.source).trim();return t||null}function Lg(e,t,n,r,i){for(let o of ek(e)){let s={name:o,startLine:Hr(t,n),endLine:Hr(t,n)};r.expressionIdentifiers.push(s),i(`id:${o}`)}}function ek(e){let t=new Set,n=tk(e),r=/\b[A-Za-z_$][A-Za-z0-9_$]*\b/g,i;for(;i=r.exec(n);){let o=i[0];KD.has(o)||Bs(o)||/^[A-Z_]+$/.test(o)||t.add(o)}return[...t].sort()}function tk(e){return e.replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/.*$/gm," ").replace(/`(?:\\[\s\S]|\$\{([^}]*)\}|[^`\\])*`/g,(t,n)=>n??" ").replace(/'(?:\\[\s\S]|[^'\\])*'/g," ").replace(/"(?:\\[\s\S]|[^"\\])*"/g," ")}function nk(e){let t=e.tag;return e.tagType===UD.COMPONENT?"component":VD.has(t)?"builtin":WD.has(t)?"native":/^[A-Z]/.test(t)||t.includes("-")?"component":"native"}function rk(e){return $s(e,/[-_:]/)}function Hr(e,t){return e+Math.max(0,t-1)}import{createRequire as gk}from"module";import{existsSync as or}from"fs";import{basename as Mg,dirname as Ze,extname as Xt,join as st,relative as rr,resolve as Te,sep as hk}from"path";function M(e,t={}){let n=t.scope?"AND relative_path LIKE ?":"",r=t.like?"AND relative_path LIKE ?":"",i=[...t.scope?[`%${t.scope}%`]:[],...t.like?[t.like]:[]],o=e.all(`SELECT relative_path
|
|
119
|
+
FROM documents
|
|
120
|
+
WHERE 1 = 1
|
|
121
|
+
${e.pathExclusionsFor("documents")}
|
|
122
|
+
${n}
|
|
123
|
+
${r}
|
|
124
|
+
ORDER BY relative_path`,...i).map(a=>a.relative_path),s=t.extensions?o.filter(a=>t.extensions.some(c=>a.toLowerCase().endsWith(c.toLowerCase()))):o;return t.includeIgnored===!1?s.filter(a=>!e.isIgnored(a)):s}import{isAbsolute as ik,relative as ok}from"path";function En(e){return e.replace(/\\/g,"/").replace(/^\.\//,"")}function se(e){return e.replace(/\\/g,"/")}function Qe(e,t){return En(e)===En(t)}function M8(e,t){let n=ok(e,t);return n===""||!n.startsWith("..")&&!ik(n)}import{existsSync as Zl,readFileSync as eu,readdirSync as sk,statSync as ak}from"fs";import{join as Ur,relative as ck}from"path";function qr(e){let t=lk(e)??fk(e);if(!t||t.length===0)return[];let n=[],r=new Set;for(let i of t)for(let o of tu(e,i)){if(r.has(o))continue;r.add(o);let s=pk(e,o);s&&n.push(s)}return n}function lk(e){let t=Ur(e,"pnpm-workspace.yaml");if(!Zl(t))return null;try{return uk(eu(t,"utf8"))}catch{return null}}function uk(e){let t=[],n=!1;for(let r of e.split(/\r?\n/)){let i=dk(r);if(!n){/^packages\s*:\s*$/.test(i.trim())&&(n=!0);continue}let o=/^\s+-\s*(.+)$/.exec(i);if(o){let s=mk(o[1].trim());s&&t.push(s);continue}if(i.trim()!=="")break}return t}function dk(e){let t=e.indexOf("#");return t===-1?e:e.slice(0,t)}function mk(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function fk(e){let t=Ur(e,"package.json");if(!Zl(t))return null;try{let n=JSON.parse(eu(t,"utf8"));return n.workspaces?Array.isArray(n.workspaces)?n.workspaces:n.workspaces.packages??[]:null}catch{return null}}function tu(e,t){if(!t||t.startsWith("!")||t.includes("node_modules"))return[];if(!t.includes("*")){let s=Ur(e,t);return Ql(s)?[s]:[]}let n=t.indexOf("*"),r=t.slice(0,n).replace(/\/$/,""),i=t.slice(n+1).replace(/^\//,""),o=Ur(e,r||".");return Ql(o)?sk(o).map(s=>Ur(o,s,i)).filter(Ql):[]}function Ql(e){try{return ak(e).isDirectory()}catch{return!1}}function pk(e,t){let n=Ur(t,"package.json");if(!Zl(n))return null;try{let r=JSON.parse(eu(n,"utf8"));return typeof r.name!="string"||r.name.length===0?null:{name:r.name,relativeDir:ck(e,t).replace(/\\/g,"/"),exports:r.exports}}catch{return null}}var yk=Z("indexed-paths",{clearGroups:[]}),bk=Z("indexed-path-digest",{clearGroups:[]}),Sk=B("tsconfig-alias-config",{clearGroups:["whole-project"]}),xk=B("tsconfig-alias-config-for-dir",{clearGroups:["whole-project"]}),Ck=gk(import.meta.url),zi;function Rk(){if(zi!==void 0)return zi;try{zi=Ck("typescript")}catch{zi=null}return zi}var vk=["tsconfig.json","tsconfig.app.json","tsconfig.node.json","tsconfig.base.json"],Ik=Z("workspace-packages",{clearGroups:["whole-project"]}),ir=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue"],Us=[".py",".pyi"],et=[".java",".scala",".kt",".kts"],qs=[".rs"],Gs=[".rb"],Vs=[".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx"],Dn=[".cs",".vb"],Ws=[".dart"],sr=[".php"],Gr=[".clj",".cljs",".cljc"],wk=new Set(ir),nu=new Set(Us),Ag=new Set(et),ru=new Set(qs),iu=new Set(Gs),Ng=new Set(Vs),Og=new Set(Dn),ou=new Set(Ws),jg=new Set(sr),Bg=new Set(Gr),Ek=[{extensions:ir,lookup:wk},{extensions:Us,lookup:nu},{extensions:et,lookup:Ag},{extensions:qs,lookup:ru},{extensions:Gs,lookup:iu},{extensions:Vs,lookup:Ng},{extensions:Dn,lookup:Og},{extensions:Ws,lookup:ou},{extensions:sr,lookup:jg},{extensions:Gr,lookup:Bg}];function Qt(e,t){return t.has(Xt(e).toLowerCase())}function Dk(e){return Qt(e,nu)}function kk(e){return Qt(e,Ag)}function Pk(e){return Qt(e,ru)}function Fk(e){return Qt(e,iu)}function Tk(e){return Qt(e,Ng)}function _k(e){return Qt(e,Og)}function $g(e){return Xt(e).toLowerCase()===".vb"}function Lk(e){return Qt(e,ou)}function Mk(e){return Qt(e,jg)}function Ak(e){return Qt(e,Bg)}function su(e){let t=Xt(e).toLowerCase();for(let n of Ek)if(n.lookup.has(t))return n.extensions;return ir}function Nk(e){return kk(e)||_k(e)||Mk(e)}function tt(e,t,n){return Dk(t)?Vr(e,t,n):Pk(t)?Zt(e,t,n):Fk(t)?zs(e,t,n):Tk(t)?Ks(e,t,n):Nk(t)?ve(e,n.replace(/\\/g,"."),su(t)):Lk(t)?Js(e,t,n):Ak(t)?au(e,n):Ok(e,t,n)}function Ok(e,t,n){if(!n.startsWith(".")&&!n.startsWith("/"))return jk(e,t,n)??$k(e,n);let r=Ze(st(e.config.projectRoot,t)),i=Te(r,n),o=en(e);for(let s of lu(i)){let a=se(rr(e.config.projectRoot,s));if(o.has(a)||or(s))return a}return se(rr(e.config.projectRoot,i))}function jk(e,t,n){let r=Wk(e,t);if(!r)return null;let i=en(e);for(let o of Bk(r,n)){let s=Te(r.baseUrl,o);for(let a of lu(s)){let c=se(rr(e.config.projectRoot,a));if(i.has(c)||or(a))return c}}return null}function Bk(e,t){let n=[];for(let[r,i]of Object.entries(e.paths)){let o=r.indexOf("*");if(o===-1){if(t!==r)continue;n.push(...i);continue}let s=r.slice(0,o),a=r.slice(o+1);if(!t.startsWith(s)||!t.endsWith(a)||t.length<s.length+a.length)continue;let c=t.slice(s.length,t.length-a.length);for(let l of i)n.push(l.includes("*")?l.replace("*",c):l)}return n}function $k(e,t){let n=Uk(Hk(e),t);if(!n)return null;let r=en(e);for(let i of qk(n)){let o=Te(e.config.projectRoot,n.pkg.relativeDir,i);for(let s of lu(o)){let a=se(rr(e.config.projectRoot,s));if(r.has(a)||or(s))return a}}return null}function Hk(e){return Ik.get(e,()=>qr(e.config.projectRoot))}function Uk(e,t){let n=null;for(let r of e){let i=null;t===r.name?i="":t.startsWith(`${r.name}/`)&&(i=t.slice(r.name.length+1)),i!==null&&(!n||r.name.length>n.pkg.name.length)&&(n={pkg:r,subpath:i})}return n}function qk(e){let t=[],n=Gk(e.pkg.exports,e.subpath);if(n){let r=Vk(n);r&&t.push(r)}return t.push(e.subpath?`src/${e.subpath}`:"src/index"),t}function Gk(e,t){if(!e||typeof e!="object")return null;let n=t===""?".":`./${t}`;return Hg(e[n])}function Hg(e){if(typeof e=="string")return e;if(!e||typeof e!="object")return null;let t=e;for(let n of["types","import","default","require","node"]){let r=Hg(t[n]);if(r)return r}return null}function Vk(e){let t=e.replace(/^\.\//,"");return t.startsWith("dist/")?`src/${t.slice(5)}`:null}function Wk(e,t){let n=se(Ze(t));return xk.get(e,n,()=>zk(e,n))}function zk(e,t){let n=Rk();if(!n)return null;let r=Te(e.config.projectRoot),i=Te(r,t);for(;i===r||i.startsWith(r+hk);){for(let s of vk){let a=st(i,s);if(!or(a))continue;let c=Sk.get(e,a,()=>Kk(n,a));if(c)return c}let o=Ze(i);if(o===i)break;i=o}return null}function Kk(e,t){try{let n=e.readConfigFile(t,e.sys.readFile);if(n.error||!n.config)return null;let r=e.parseJsonConfigFileContent(n.config,e.sys,Ze(t)),i=r.options.paths;return!i||Object.keys(i).length===0?null:{baseUrl:r.options.baseUrl?Te(Ze(t),r.options.baseUrl):Ze(t),paths:i}}catch{return null}}function Vr(e,t,n){let r=en(e),i;if(n.startsWith(".")){let o=n.match(/^(\.+)(.*)$/);if(!o)return null;let s=o[1].length,a=o[2].replace(/^\./,""),c=Ze(st(e.config.projectRoot,t));for(let l=1;l<s;l++)c=Ze(c);i=a?Te(c,a.replace(/\./g,"/")):c}else i=Te(e.config.projectRoot,n.replace(/\./g,"/"));for(let o of Jk(i)){let s=se(rr(e.config.projectRoot,o));if(r.has(s)||or(o))return s}return null}function Zt(e,t,n){if(!n)return null;let r=n.replace(/\s+as\s+.+$/,"").trim();if(!r.startsWith("crate::")&&!r.startsWith("self::")&&!r.startsWith("super::"))return null;let i=Ze(st(e.config.projectRoot,t)),o;return r.startsWith("crate::")?o=Te(e.config.projectRoot,"src",r.slice(7).replace(/::/g,"/")):r.startsWith("self::")?o=Te(i,r.slice(6).replace(/::/g,"/")):o=Te(Ze(i),r.slice(7).replace(/::/g,"/")),cu(e,Yk(o))}function zs(e,t,n){let r=Ze(st(e.config.projectRoot,t)),i=Te(r,n);return cu(e,Xk(i))}function Ks(e,t,n){let r=Ze(st(e.config.projectRoot,t)),i=[Te(r,n),Te(e.config.projectRoot,n),Te(e.config.projectRoot,"include",n),Te(e.config.projectRoot,"src",n)];return cu(e,i)}function ve(e,t,n){let r=en(e),i=t.replace(/\\/g,".").replace(/::/g,".").replace(/^global::/,""),o=i.replace(/\./g,"/"),s=i.split(".").pop()??i;for(let c of n){let l=`${o}${c}`,u=[...r].find(d=>d.endsWith(l));if(u)return u}for(let c of n){let l=[...r].find(u=>Mg(u)===`${s}${c}`);if(l)return l}let a=[...r].filter(c=>n.includes(Xt(c).toLowerCase())).filter(c=>c.includes(`/${o}/`)||c.includes(`/${s}/`)).sort((c,l)=>c.localeCompare(l));return a.length===1?a[0]:null}function Js(e,t,n){let r=en(e);if(n.startsWith("package:")){let s=n.slice(8),a=s.indexOf("/");if(a<0)return null;let c=s.slice(a+1),l=se(c.startsWith("lib/")?c:`lib/${c}`);return r.has(l)?l:null}let i=Ze(st(e.config.projectRoot,t)),o=Te(i,n);for(let s of Qk(o)){let a=se(rr(e.config.projectRoot,s));if(r.has(a)||or(s))return a}return null}function au(e,t){let n=t.replace(/-/g,"_").replace(/\./g,"/"),r=en(e);for(let i of Gr){let o=`${n}${i}`,s=[...r].find(a=>a.endsWith(o));if(s)return s}for(let i of Gr){let o=[...r].find(s=>Mg(s)===`${n.split("/").pop()}${i}`);if(o)return o}return null}function Jk(e){let t=Xt(e);return nu.has(t)?[e]:[`${e}.py`,`${e}.pyi`,st(e,"__init__.py"),st(e,"__init__.pyi")]}function cu(e,t){let n=en(e);for(let r of t){let i=se(rr(e.config.projectRoot,r));if(n.has(i)||or(r))return i}return null}function Yk(e){let t=Xt(e);return ru.has(t)?[e]:[`${e}.rs`,st(e,"mod.rs")]}function Xk(e){let t=Xt(e);return iu.has(t)?[e]:[`${e}.rb`,st(e,"index.rb")]}function Qk(e){let t=Xt(e);return ou.has(t)?[e]:[`${e}.dart`,e]}function lu(e){let t=Xt(e),n=new Set;if(t){n.add(e);for(let r of ir)n.add(e.slice(0,-t.length)+r)}else for(let r of ir)n.add(`${e}${r}`),n.add(st(e,`index${r}`));return[...n]}function en(e){return yk.get(e,()=>new Set(M(e,{includeIgnored:!1}).map(se)))}function uu(e){return bk.get(e,()=>Ce([...en(e)].sort().join(`
|
|
125
|
+
`)))}import{readdirSync as Zk}from"fs";import{execFileSync as eP}from"child_process";import{extname as Ys,join as tP}from"path";var nP=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".vue",".rs",".py",".pyi",".java",".kt",".kts",".scala",".sc",".clj",".cljs",".cljc",".rb",".c",".h",".cc",".cpp",".cxx",".hpp",".hh",".hxx",".cs",".vb",".php",".dart"],Z8=[".vue"],Ug=[".tsx",".jsx"],qg=[".vue"],rP=[...Ug,...qg],iP=new Set(Ug),oP=new Set(qg),Gg=new Set(nP.map(e=>e.toLowerCase())),sP=[...Gg].sort().join(","),Vg=new Set(["node_modules",".git","target","dist","build",".next",".nuxt",".cache",".turbo",".nbb",".cpcache",".shadow-cljs","out","coverage",".scipquery-cache","__pycache__",".venv","venv",".idea",".vscode"]);function ze(e,t={}){let n=t.includeIndexed??!0,r=t.includeAuxiliary??!0,i=t.extensions?.map(c=>c.toLowerCase()),o=i?new Set(i):Gg,s=i?[...o].sort().join(","):sP,a=`${n?"1":"0"}|${r?"1":"0"}|${s}`;return aP.get(e,a,()=>{let c=new Set;if(n)for(let l of M(e,{includeIgnored:!1}))o.has(Ys(l).toLowerCase())&&c.add(l);if(r)for(let l of cP(e.config.projectRoot,o))e.isIgnored(l)||n&&c.has(l)||c.add(l);return[...c].sort()})}function Xs(e,t={}){let n=!1,r=!1;for(let i of ze(e,{extensions:rP})){if(t.scope&&!i.includes(t.scope))continue;let o=Ys(i).toLowerCase();if(n||=iP.has(o),r||=oP.has(o),n&&r)break}return{react:n,vue:r}}var aP=B("source-files",{clearGroups:[]});function cP(e,t){return lP(e,t)??dP(e,t)}function lP(e,t){try{let n=eP("git",["ls-files","--cached","--others","--exclude-standard"],{cwd:e,encoding:"utf-8",timeout:1e4,killSignal:"SIGKILL",stdio:["ignore","pipe","ignore"]}),r=new Set;for(let i of n.split(`
|
|
126
|
+
`)){let o=i.trim();o&&(uP(o)||t.has(Ys(o).toLowerCase())&&r.add(o))}return r}catch{return null}}function uP(e){return e.split("/").some(t=>Vg.has(t))}function dP(e,t){let n=new Set,r=i=>{let o=i?tP(e,i):e,s;try{s=Zk(o,{withFileTypes:!0})}catch{return}for(let a of s)if(!Vg.has(a.name)){if(a.isDirectory()){r(i?`${i}/${a.name}`:a.name);continue}t.has(Ys(a.name).toLowerCase())&&n.add(i?`${i}/${a.name}`:a.name)}};return r(""),n}var mP=new Set(["ref","shallowRef","reactive","computed","watch","watchEffect"]),fP=new Set(["onBeforeMount","onMounted","onBeforeUpdate","onUpdated","onBeforeUnmount","onUnmounted","onActivated","onDeactivated","onErrorCaptured"]),pP=new Set(["axios","fetch","runRequest","useAsyncData","useFetch","useResource"]),gP=new Set(["defineEmits","defineExpose","defineModel","defineOptions","defineProps","withDefaults"]),hP=new Set(["catch","for","function","if","return","switch","while"]);function Zs(e){let t={imports:[],functions:[],calls:[],composables:[],stores:[],reactivity:[],lifecycle:[],requests:[],macros:[],lineCount:0,externalLineCount:0,externalScriptPaths:[],unresolvedScripts:[]};for(let n of e.scripts){t.lineCount+=er(n),n.external&&(t.externalLineCount+=er(n),t.externalScriptPaths.push(n.sourcePath));for(let i of n.errors)t.unresolvedScripts.push({sourcePath:n.sourcePath,reason:i});if(!n.body||!n.astLanguage){n.astLanguage||t.unresolvedScripts.push({sourcePath:n.sourcePath,reason:`Unsupported Vue script language: ${n.lang??"unknown"}`});continue}t.imports.push(...xP(n));let r=Hi(n.astLanguage,n.body);r?bP(n,r.rootNode,t):SP(n,t)}return yP(t),t.externalScriptPaths=zg(t.externalScriptPaths),t}function yP(e){e.composables=Wr(e,"composable"),e.stores=Wr(e,"store"),e.reactivity=Wr(e,"reactivity"),e.lifecycle=Wr(e,"lifecycle"),e.requests=Wr(e,"request"),e.macros=Wr(e,"macro")}function Wr(e,t){return zg(e.calls.filter(n=>n.categories.includes(t)).map(n=>n.name))}function bP(e,t,n){let r=new Set,i=new Set,o=s=>{let a=Ns(s,e.astLanguage);if(a){let l=`${a.name}:${a.startLine}:${a.endLine}`;i.has(l)||(i.add(l),n.functions.push({name:a.name,sourcePath:e.sourcePath,startLine:e.startLine+a.startLine,endLine:e.startLine+a.endLine,setup:e.setup}))}let c=$r(s,e.astLanguage);if(c){let l=`${c.calleeLeaf}:${c.line}`;r.has(l)||(r.add(l),n.calls.push({name:c.calleeLeaf,sourcePath:e.sourcePath,line:e.startLine+c.line,categories:Wg(c.calleeLeaf),setup:e.setup}))}for(let l of s.children)o(l)};o(t)}function SP(e,t){for(let n of e.body.matchAll(/\b([A-Za-z_$][\w$]*)\s*\(/g)){let r=n[1];!r||hP.has(r)||t.calls.push({name:r,sourcePath:e.sourcePath,line:e.startLine+Qs(e.body,n.index??0),categories:Wg(r),setup:e.setup})}for(let n of e.body.matchAll(/\bfunction\s+([A-Za-z_$][\w$]*)\b/g)){let r=n[1];if(!r)continue;let i=e.startLine+Qs(e.body,n.index??0);t.functions.push({name:r,sourcePath:e.sourcePath,startLine:i,endLine:i,setup:e.setup})}for(let n of e.body.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)/g)){let r=n[1];if(!r)continue;let i=e.startLine+Qs(e.body,n.index??0);t.functions.push({name:r,sourcePath:e.sourcePath,startLine:i,endLine:i,setup:e.setup})}}function xP(e){let t=[];for(let n of e.body.matchAll(/\bimport\s+(?:type\s+)?([^'";]+?)\s+from\s+['"]([^'"]+)['"]/g)){let r=n[1]?.trim(),i=n[2];if(!r||!i)continue;let o=e.startLine+Qs(e.body,n.index??0);for(let s of CP(r))t.push({local:s,source:i,sourcePath:e.sourcePath,line:o,setup:e.setup})}return t}function CP(e){let t=[],r=e.split(",").map(s=>s.trim()).filter(Boolean)[0];r&&!r.startsWith("{")&&!r.startsWith("*")&&t.push(r);let i=/\{([^}]*)\}/.exec(e)?.[1];if(i)for(let s of i.split(",")){let a=s.trim();if(!a)continue;let c=/\bas\s+([A-Za-z_$][\w$]*)$/.exec(a)?.[1];t.push(c??a.replace(/^type\s+/,"").trim())}let o=/\*\s+as\s+([A-Za-z_$][\w$]*)/.exec(e)?.[1];return o&&t.push(o),t.filter(s=>/^[A-Za-z_$][\w$]*$/.test(s))}function Wg(e){let t=["call"];return/^use[A-Z0-9_]/.test(e)&&t.push("composable"),/^use[A-Z0-9_].*Store$/.test(e)&&t.push("store"),mP.has(e)&&t.push("reactivity"),fP.has(e)&&t.push("lifecycle"),pP.has(e)&&t.push("request"),gP.has(e)&&t.push("macro"),t}function Qs(e,t){let n=0;for(let r=0;r<t&&r<e.length;r+=1)e.charCodeAt(r)===10&&(n+=1);return n}function zg(e){return[...new Set(e)].sort()}var RP=new Set(["in","key","of"]),vP=new Set(["computed","defineEmits","defineProps","reactive","ref","watch","watchEffect"]),IP=Rn("vue-component-behavior-profiles");function Kg(e,t={}){let n=ze(e,{extensions:[".vue"]}).filter(i=>!t.scope||i.includes(t.scope)).sort();return(typeof t.scanLimit=="number"&&t.scanLimit>0?n.slice(0,t.scanLimit):n).map(i=>du(e,i)).filter(i=>(t.minTemplateTokens===void 0||i.templateTokens.size>=t.minTemplateTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function du(e,t){let n=t.replace(/\\/g,"/"),r=P(e,n),i=IP.get(e,n,r,()=>wP(e,n,r));return DP(i)}function wP(e,t,n){let r=Br(e,t),i=Hs(e,t),o=Zs(r),s=FP(i),a=i.expressionIdentifiers.map(y=>y.name).filter(y=>!s.includes(y)).filter((y,h,C)=>C.indexOf(y)===h).sort(),c=i.componentTags.map(y=>y.normalized).filter((y,h,C)=>C.indexOf(y)===h).sort(),l=n?n.split(`
|
|
127
|
+
`).length:0,u=er(r.template),d=o.lineCount,m=r.styles.reduce((y,h)=>y+er(h),0),f=r.customBlocks.reduce((y,h)=>y+er(h),0),{lines:p,paths:g}=EP(e,t,o);return{file:t,sfc:r,templateFacts:i,scriptFacts:o,templateTokens:new Set(i.structuralTokens),behaviorTokens:PP(i,o,a),templateBindingNames:a,templateLocalNames:s,componentNames:c,sfcLines:l,totalLines:l+o.externalLineCount,templateLines:u,scriptLines:d,styleLines:m,externalScriptLines:o.externalLineCount,externalScriptPaths:o.externalScriptPaths,customBlockLines:f,delegatedComposableLines:p,delegatedComposablePaths:g}}function EP(e,t,n){let r=new Set;for(let s of n.composables){let a=n.imports.find(l=>l.local===s);if(!a)continue;let c=tt(e,a.sourcePath,a.source);!c||c===t||r.add(c)}let i=[...r].sort();return{lines:i.reduce((s,a)=>{let c=P(e,a);return s+(c?c.split(`
|
|
128
|
+
`).length:0)},0),paths:i}}function DP(e){let t=kP(e.scriptFacts);return{...e,scriptFacts:t,templateTokens:new Set(e.templateTokens),behaviorTokens:new Set(e.behaviorTokens),templateBindingNames:[...e.templateBindingNames],templateLocalNames:[...e.templateLocalNames],componentNames:[...e.componentNames],externalScriptPaths:t.externalScriptPaths,delegatedComposablePaths:[...e.delegatedComposablePaths]}}function kP(e){return{...e,imports:e.imports.map(t=>({...t})),functions:e.functions.map(t=>({...t})),calls:e.calls.map(t=>({...t,categories:[...t.categories]})),composables:[...e.composables],stores:[...e.stores],reactivity:[...e.reactivity],lifecycle:[...e.lifecycle],requests:[...e.requests],macros:[...e.macros],externalScriptPaths:[...e.externalScriptPaths],unresolvedScripts:e.unresolvedScripts.map(t=>({...t}))}}function PP(e,t,n){let r=new Set;for(let i of t.composables)r.add(`composable:${i}`);for(let i of t.stores)r.add(`store:${i}`);for(let i of t.reactivity)r.add(`reactivity:${i}`);for(let i of t.lifecycle)r.add(`lifecycle:${i}`);for(let i of t.requests)r.add(`request:${i}`);for(let i of t.macros)r.add(`macro:${i}`);for(let i of t.functions){if(vP.has(i.name))continue;r.add(`function:${i.name}`);let o=/^[a-z]+/.exec(i.name)?.[0]??null;o&&o.length>2&&o!==i.name&&r.add(`function-verb:${o}`)}for(let i of e.events)r.add(`template-event:${i.name}`);for(let i of n)r.add(`template-binding:${i}`);return r}function FP(e){let t=new Set;for(let n of e.directives)if(n.name==="for"&&n.value)for(let r of TP(n.value))t.add(r);for(let n of e.slots)if(n.value)for(let r of Jg(n.value))t.add(r);return[...t].sort()}function TP(e){let t=/^(.*?)\s+(?:in|of)\s+/.exec(e.trim());return t?Jg(t[1]??""):[]}function Jg(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let r=n[0];RP.has(r)||t.push(r)}return t}import{extname as _P}from"path";function Mt(e){return typeof e=="object"&&e!==null}function He(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")?e:null}var LP=[".tsx",".jsx"],Yg=new Set(["useActionState","useCallback","useContext","useDebugValue","useDeferredValue","useEffect","useId","useImperativeHandle","useInsertionEffect","useLayoutEffect","useMemo","useOptimistic","useReducer","useRef","useState","useSyncExternalStore","useTransition"]),MP=new Set(["useEffect","useInsertionEffect","useLayoutEffect"]),AP=new Set(["useActionState","useOptimistic","useReducer","useRef","useState"]),NP=new Set(["useLocation","useNavigate","useParams","useSearchParams","useTranslation"]),OP=new Set(["axios","fetch","gql","graphql","mutate","query","request","useMutation","useQuery","useSuspenseQuery"]),jP=new Set(["add","apply","cancel","change","clear","close","create","delete","fetch","filter","handle","load","open","refresh","remove","render","reset","save","select","submit","toggle","update"]),BP=new Set(["aria-hidden","className","clipRule","d","fill","fillRule","height","role","stroke","strokeLinecap","strokeLinejoin","strokeWidth","style","viewBox","width","xmlns"]),$P=Rn("react-component-behavior-profiles"),Xg=ce({kind:"react-component-behavior-profiles",invalidation:X("react-component-behavior-profiles"),serialize:GP,deserialize:VP});function th(e,t={}){let n=ze(e,{extensions:LP}).filter(i=>!t.scope||i.includes(t.scope)).sort();return(typeof t.scanLimit=="number"&&t.scanLimit>0?n.slice(0,t.scanLimit):n).flatMap(i=>fu(e,i)).filter(i=>(t.minJsxTokens===void 0||i.jsxTokens.size>=t.minJsxTokens)&&(t.minBehaviorTokens===void 0||i.behaviorTokens.size>=t.minBehaviorTokens))}function fu(e,t){let n=t.replace(/\\/g,"/"),r=P(e,n);return $P.get(e,n,r,()=>HP(e,n,r)).map(qP)}function HP(e,t,n){let r=me(e,t,n),i=Xg.read(e,t,r);if(i)return i;let o=UP(e,t);return Xg.write(e,t,r,o),o}function UP(e,t){let n=zP(t);if(!n)return[];let r=Y(e,t);if(!r)return[];let i=Ee(e,t).length;return KP(r.rootNode,n).filter(s=>s.kind==="hook"||pu(s.bodyNode)).map(s=>{let a=tF(s.bodyNode),c=sF(s.bodyNode,n);return{file:t,name:s.name,kind:s.kind,startLine:s.node.startPosition.row,endLine:s.node.endPosition.row,loc:Math.max(1,s.node.endPosition.row-s.node.startPosition.row+1),fileLines:i,jsxTokens:a.tokens,behaviorTokens:c.tokens,componentNames:tn(a.componentNames),nativeTags:tn(a.nativeTags),propNames:tn(a.propNames),eventNames:tn(a.eventNames),hookNames:tn(c.hookNames),requestNames:tn(c.requestNames),stateNames:tn(c.stateNames),effectNames:tn(c.effectNames),handlerNames:tn(c.handlerNames)}})}function qP(e){return{...e,jsxTokens:new Set(e.jsxTokens),behaviorTokens:new Set(e.behaviorTokens),componentNames:[...e.componentNames],nativeTags:[...e.nativeTags],propNames:[...e.propNames],eventNames:[...e.eventNames],hookNames:[...e.hookNames],requestNames:[...e.requestNames],stateNames:[...e.stateNames],effectNames:[...e.effectNames],handlerNames:[...e.handlerNames]}}function GP(e){return JSON.stringify(e.map(t=>({...t,jsxTokens:[...t.jsxTokens],behaviorTokens:[...t.behaviorTokens]})))}function VP(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=[];for(let r of t){let i=WP(r);if(!i)return null;n.push(i)}return n}catch{return null}}function WP(e){if(!Mt(e))return null;let{file:t,name:n,kind:r,startLine:i,endLine:o,loc:s,fileLines:a,jsxTokens:c,behaviorTokens:l,componentNames:u,nativeTags:d,propNames:m,eventNames:f,hookNames:p,requestNames:g,stateNames:y,effectNames:h,handlerNames:C}=e;if(typeof t!="string"||typeof n!="string"||r!=="component"&&r!=="hook"||!ea(i)||!ea(o)||!ea(s)||!ea(a))return null;let b={jsxTokens:He(c),behaviorTokens:He(l),componentNames:He(u),nativeTags:He(d),propNames:He(m),eventNames:He(f),hookNames:He(p),requestNames:He(g),stateNames:He(y),effectNames:He(h),handlerNames:He(C)};return Object.values(b).some(S=>S===null)?null:{file:t,name:n,kind:r,startLine:i,endLine:o,loc:s,fileLines:a,jsxTokens:new Set(b.jsxTokens),behaviorTokens:new Set(b.behaviorTokens),componentNames:b.componentNames,nativeTags:b.nativeTags,propNames:b.propNames,eventNames:b.eventNames,hookNames:b.hookNames,requestNames:b.requestNames,stateNames:b.stateNames,effectNames:b.effectNames,handlerNames:b.handlerNames}}function ea(e){return typeof e=="number"&&Number.isFinite(e)}function zP(e){let t=_P(e).toLowerCase();return t!==".tsx"&&t!==".jsx"?null:N(e)}function KP(e,t){let n=[],r=new Set,i=o=>{let s=JP(o);if(s&&(!ZP(o)||s.kind==="component")){let a=`${s.name}:${s.node.startIndex}:${s.node.endIndex}`;r.has(a)||(r.add(a),n.push(s))}for(let a of o.namedChildren)i(a)};return(t==="tsx"||t==="javascript")&&i(e),n}function JP(e){if(e.type==="class_declaration"){let o=mu(e);if(!o||!/^[A-Z]/.test(o))return null;let s=YP(e);return!s||!XP(e)&&!pu(s)?null:{name:o,kind:"component",node:e,bodyNode:s}}if(e.type==="function_declaration"){let o=mu(e);return!o||!Qg(o)?null:{name:o,kind:Zg(o),node:e,bodyNode:e}}if(e.type!=="variable_declarator")return null;let t=e.childForFieldName("name")??e.namedChild(0),n=e.childForFieldName("value")??e.namedChild(1),r=Ki(t);if(!r||!n||!Qg(r))return null;let i=QP(n);return i?{name:r,kind:Zg(r),node:e,bodyNode:i}:null}function YP(e){for(let t of e.namedChildren)if(t.type==="class_body")for(let n of t.namedChildren){if(n.type!=="method_definition")continue;if((n.childForFieldName("name")??n.namedChild(0))?.text==="render")return n}return null}function XP(e){return/\b(?:React\.)?(?:Pure)?Component\b/.test(e.text)}function Qg(e){return/^[A-Z]/.test(e)||/^use[A-Z0-9_]/.test(e)}function Zg(e){return/^use[A-Z0-9_]/.test(e)?"hook":"component"}function QP(e){if(e.type==="arrow_function"||e.type==="function_expression")return e;if(e.type!=="call_expression")return null;let t=eF(e);return t!=="memo"&&t!=="forwardRef"?null:e.namedChildren.find(i=>i.type==="arguments")?.namedChildren.find(i=>i.type==="arrow_function"||i.type==="function_expression")??null}function ZP(e){let t=e.parent;for(;t;){if(t.type==="function_declaration"||t.type==="function_expression"||t.type==="arrow_function"||t.type==="method_definition")return!0;t=t.parent}return!1}function mu(e){return Ki(e.childForFieldName("name")??e.namedChild(0))}function eF(e){let t=e.childForFieldName("function")??e.namedChild(0);return t?t.text.split(".").pop()??t.text:null}function pu(e){return e.type.startsWith("jsx_")?!0:e.namedChildren.some(pu)}function tF(e){let t={tokens:new Set,componentNames:new Set,nativeTags:new Set,propNames:new Set,eventNames:new Set},n=r=>{r.type==="jsx_opening_element"||r.type==="jsx_self_closing_element"?nF(r,t):r.type==="jsx_element"&&r.text.trimStart().startsWith("<>")?t.tokens.add("jsx:fragment"):r.type==="jsx_expression"?rF(r,t):r.type==="jsx_fragment"&&t.tokens.add("jsx:fragment");for(let i of r.children)n(i)};return n(e),t}function nF(e,t){let n=iF(e),r=!1;if(n){let i=eh(n),o=i==="Fragment"||i==="React.Fragment";r=dF(i)&&!o,o?t.tokens.add("jsx:fragment"):r?(t.componentNames.add(i),t.tokens.add(`component:${i}`)):(t.nativeTags.add(i),t.tokens.add(`native:${i}`))}for(let i of e.namedChildren)if(i.type==="jsx_attribute"){let o=oF(i);if(!o)continue;let s=eh(o);if(s.startsWith("on")&&s.length>2){let a=s.slice(2).replace(/^[A-Z]/,c=>c.toLowerCase());t.eventNames.add(a),t.tokens.add(`event:${a}`)}else BP.has(s)||(t.propNames.add(s),t.tokens.add(`${r?"prop":"native-prop"}:${s}`))}else i.type==="jsx_spread_attribute"&&t.tokens.add(nh(i))}function rF(e,t){let n=e.text;/^\{\s*\.\.\./.test(n)&&t.tokens.add(nh(e)),rh(e)&&t.tokens.add("jsx:conditional"),(n.includes(".map(")||n.includes(".flatMap("))&&t.tokens.add("jsx:list");for(let r of mF(n))Bs(r)||t.tokens.add(`binding:${r}`)}function nh(e){let t=/^\{\s*\.\.\.\s*([^}]+)\s*\}$/.exec(e.text)?.[1],n=e.namedChildren.find(o=>o.type!=="comment"),r=t??n?.text??"",i=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.exec(r.trim())?.[0];return i?`prop:spread:${i}`:"prop:spread"}function rh(e){return e.type==="ternary_expression"||e.type==="conditional_expression"?!0:e.namedChildren.some(rh)}function iF(e){for(let t of e.namedChildren)if(t.type==="identifier"||t.type==="jsx_identifier"||t.type==="property_identifier"||t.type==="member_expression"||t.type==="jsx_member_expression")return t.text;return/^<\s*([A-Za-z][\w$.]*)/.exec(e.text)?.[1]??null}function oF(e){for(let t of e.namedChildren)if(t.type==="property_identifier"||t.type==="identifier"||t.type==="jsx_identifier")return t.text;return/^([A-Za-z_$][\w$:-]*)/.exec(e.text)?.[1]??null}function sF(e,t){let n={tokens:new Set,hookNames:new Set,requestNames:new Set,stateNames:new Set,effectNames:new Set,handlerNames:new Set},r=i=>{if(i.type==="call_expression"){let o=$r(i,t);o&&aF(o.calleeLeaf,n)}else if(i.type==="variable_declarator")lF(i,n);else if(i.type==="function_declaration"){let o=mu(i);o&&ih(o,n)}for(let o of i.namedChildren)r(o)};return r(e),n}function aF(e,t){/^use[A-Z0-9_]/.test(e)&&(t.hookNames.add(e),!Yg.has(e)&&!NP.has(e)&&t.tokens.add(`hook:${e}`)),Yg.has(e)&&t.tokens.add(`react-hook:${e}`),MP.has(e)&&(t.effectNames.add(e),t.tokens.add(`effect:${e}`)),AP.has(e)&&t.tokens.add(`state-hook:${e}`),cF(e)&&(t.requestNames.add(e),t.tokens.add(`request:${e}`))}function cF(e){if(OP.has(e))return!0;let t=/^use([A-Z0-9_].*)$/.exec(e)?.[1];return t?/(Query|Mutation|Fetch|Resource)$/.test(t):!1}function lF(e,t){let n=e.childForFieldName("name")??e.namedChild(0),r=e.childForFieldName("value")??e.namedChild(1);if(n?.type==="array_pattern"&&r?.text.includes("useState")){let o=n.namedChildren.find(a=>Ki(a)),s=Ki(o);s&&(t.stateNames.add(s),t.tokens.add(`state:${s}`))}let i=Ki(n);i&&ih(i,t)}function ih(e,t){let n=uF(e);!n||!jP.has(n)||(t.handlerNames.add(e),t.tokens.add(`handler:${e}`),t.tokens.add(`handler-verb:${n}`))}function uF(e){let t=e.startsWith("handle")&&e.length>6?e.slice(6).replace(/^[A-Z]/,n=>n.toLowerCase()):e;return/^[a-z]+/.exec(t)?.[0]??null}function dF(e){return/^[A-Z]/.test(e)||e.includes(".")}function eh(e){return e.replace(/^this\./,"").replace(/\$/g,".")}function Ki(e){return e&&(e.type==="identifier"||e.type==="property_identifier"||e.type==="shorthand_property_identifier"||/^[A-Za-z_$][\w$]*$/.test(e.text))?e.text:null}function mF(e){let t=[];for(let n of e.matchAll(/\b[A-Za-z_$][\w$]*\b/g)){let r=n[0];t.includes(r)||t.push(r)}return t}function tn(e){return[...e].sort()}function at(e){return{capability:(t,n)=>fF(t,n),reactProfiles:(t={})=>th(e,t),reactProfilesForFile:t=>fu(e,t),vueProfiles:(t={})=>Kg(e,t),vueProfileForFile:t=>du(e,t),vueTemplateFacts:t=>Hs(e,t),vueScriptFacts:t=>Zs(Br(e,t))}}function fF(e,t){let n=e.startsWith("react-")?"react":"vue";if(t===void 0)return{slot:e,available:!0,framework:n};let r=t.replace(/\\/g,"/").toLowerCase();return n==="react"&&!r.endsWith(".tsx")&&!r.endsWith(".jsx")?{slot:e,available:!1,framework:n,reason:"React behavior profiles are only available for .tsx and .jsx files"}:n==="vue"&&!r.endsWith(".vue")?{slot:e,available:!1,framework:n,reason:"Vue behavior facts are only available for .vue files"}:{slot:e,available:!0,framework:n}}function ar(e,t,n={}){let r=z(e,t);if(!r)return[];let i=[];if(n.includeCrossLanguageDispatchNames)for(let o of r.crossLanguageDispatchNames)i.push({name:o,kind:"cross-language-dispatch",occurrences:1});if(n.includeRustAttributeNames&&r.language==="rust")for(let o of r.rustAttrReferencedNames)i.push({name:o,kind:"rust-attribute",occurrences:1});return i}import{basename as ah}from"path";function H(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ct(e){return e.replace(/'''[\s\S]*?'''/g,kn).replace(/"""[\s\S]*?"""/g,kn).replace(/#.*$/gm,kn).replace(/\/\/.*$/gm,kn).replace(/\/\*[\s\S]*?\*\//g,kn).replace(/`(?:\\[\s\S]|[^`])*`/g,kn).replace(/'(?:\\.|[^'\\\r\n])*'/g,kn).replace(/"(?:\\.|[^"\\\r\n])*"/g,kn)}function Yi(e){return sh(e,{maskStrings:!1})}function oh(e){return sh(e,{maskStrings:!0})}function sh(e,t){let n="",r=0,i=e.length;for(;r<i;){if(e[r]==="/"&&e[r+1]==="/"){let s=e.indexOf(`
|
|
129
|
+
`,r),a=s===-1?i:s;n+=gu(e,r,a),r=a;continue}if(e[r]==="/"&&e[r+1]==="*"){let s=e.indexOf("*/",r+2),a=s===-1?i:s+2;n+=gu(e,r,a),r=a;continue}let o=e[r];if(o==="`"||o==="'"||o==='"'){let s=o,a=r+1;for(;a<i;){if(e[a]==="\\"){a+=2;continue}if(e[a]===s){a+=1;break}if(s!=="`"&&e[a]===`
|
|
130
|
+
`)break;a+=1}n+=t.maskStrings?gu(e,r,a):e.slice(r,a),r=a;continue}n+=o,r+=1}return n}function gu(e,t,n){let r="";for(let i=t;i<n;i+=1)r+=e[i]===`
|
|
131
|
+
`?`
|
|
132
|
+
`:" ";return r}function kn(e){return e.replace(/[^\r\n]/g," ")}var z6=Zn("stripped-lines",{clearGroups:["whole-project","source-file"]});Cn({name:"stripped-source-singleton",groups:["whole-project","source-file"],clearAll:()=>{ta=null,Ji=""},clearFile:()=>{ta=null,Ji=""}});var ta=null,Ji="";function pF(e){return ta===e||(ta=e,Ji=ct(e)),Ji}function Pn(e,t,n){let r=pF(e);return`${r.slice(0,t)}${" ".repeat(n-t)}${r.slice(n)}`}function Ke(e,t){return new RegExp(`\\b${H(t)}\\b`,"m").test(e)}function zr(e,t){let n=new Set,r=new RegExp(`\\b${H(t)}\\s*\\.\\s*([A-Za-z_$][\\w$]*)`,"g");for(let i of e.matchAll(r)){let o=i[1];o&&n.add(o)}return[...n]}function Xi(e){let t=0;for(let n of e)n==="("&&(t+=1),n===")"&&(t-=1);return t}var gF=new Set(["identifier","type_identifier","property_identifier","shorthand_property_identifier","field_identifier"]);function Je(e){let t=[],n=0,r=0;for(let i=0;i<e.length;i++){let o=e[i];(o==="{"||o==="["||o==="(")&&n++,(o==="}"||o==="]"||o===")")&&n--,o===","&&n===0&&(t.push(e.slice(r,i)),r=i+1)}return t.push(e.slice(r)),t}function nt(e,t){for(let n of e.namedChildren)if(n.type===t)return n;return null}function Ie(e,t){let n=new Set,r=(i,o)=>{let s=o||t.has(i.type);!s&&gF.has(i.type)&&n.add(i.text);for(let a of i.children)r(a,s)};return r(e.rootNode,!1),n}function Ct(e,t,n,r,i,o,s){return{importedName:i,localName:o,sourcePath:s??ve(e,r,su(t)),kind:"named",used:Ke(n,o),usedMembers:[]}}function be(e,t,n,r,i="named",o={}){return{importedName:e,localName:t,sourcePath:n,kind:i,used:r.has(t),usedMembers:[],isTypeOnly:o.isTypeOnly}}function nn(e,t,n,r,i="named",o=[],s={}){return{importedName:e,localName:t,sourcePath:n,kind:i,used:r,usedMembers:o,isTypeOnly:s.isTypeOnly}}function cr(e,t){return{importedName:e,localName:null,sourcePath:t,kind:"side-effect",used:!0,usedMembers:[]}}function lr(e,t,n={}){return{importedName:e,localName:n.localName??null,sourcePath:t,kind:"namespace",used:n.used??!0,usedMembers:n.usedMembers??[],isTypeOnly:n.isTypeOnly}}function lt(e,t,n){let r=[];for(let i of e.matchAll(t)){let o=i[0];if(!o||typeof i.index!="number")continue;let s=Pn(e,i.index,i.index+o.length);for(let a of n(i,s))r.push(a)}return r}function ut(e,t,n,r){let i=Y(e,t);if(i){let o=n(i);if(o)return o}return r()}function na(e,t,n,r){let i=Y(e,t),o=N(t),s=o?n[o]:void 0;return i&&s?s(i):r()}function ch(e,t,n){return ut(e,t,r=>yF(e,t,r),()=>hF(e,t,n))}function hF(e,t,n){return lt(n,/^[ \t]*#include\s+[<"]([^">]+)[">]\s*$/gm,(r,i)=>{let o=r[1]?.trim();if(!o)return[];let s=ah(o).replace(/\.[^.]+$/,"");return[nn(o,s,Ks(e,t,o),Ke(i,s))]})}function yF(e,t,n){let r=Ie(n,new Set(["preproc_include"])),i=[];for(let o of n.rootNode.descendantsOfType("preproc_include")){let s=null;for(let c of o.namedChildren){if(c.type==="system_lib_string"){s=c.text.replace(/^<|>$/g,"");break}if(c.type==="string_literal"){s=c.namedChildren.find(u=>u.type==="string_content")?.text??c.text.replace(/^"|"$/g,"");break}}if(!s)continue;let a=ah(s).replace(/\.[^.]+$/,"");i.push(be(s,a,Ks(e,t,s),r))}return i}var bF=new Set([":require",":require-macros",":use"]),bu=String.raw`A-Za-z0-9_$*+!?.<>=-`;function uh(e,t,n){let r=PF(n);if(!r)return[];let i=kF(n,r.start,r.end),o=[];for(let s of r.children.slice(2)){if(s.type!=="list"||s.children.length===0)continue;let a=dt(s.children[0]);if(a){if(bF.has(a)){for(let c of CF(s.children.slice(1)))o.push(...xF(e,c,i));continue}if(a===":import")for(let c of vF(s.children.slice(1)))o.push(c)}}return o}function SF(e){return e.type==="list"&&dt(e.children[0])==="ns"}function xF(e,t,n){let r=au(e,t.namespace),i=t.alias??t.namespace,o=wF(n,i),s=[{importedName:t.namespace,localName:i,sourcePath:r,kind:"namespace",used:t.refers.length>0||t.referAll||o.length>0||EF(n,t.namespace),usedMembers:o}];t.referAll&&s.push({importedName:"*",localName:null,sourcePath:r,kind:"side-effect",used:!0,usedMembers:[]});for(let a of t.refers)s.push({importedName:a,localName:a,sourcePath:r,kind:"named",used:DF(n,a),usedMembers:[]});return s}function CF(e){return e.flatMap(t=>ra(t,null))}function ra(e,t){if(e.type==="atom")return e.text.startsWith(":")?[]:[{namespace:yu(t,e.text),alias:null,refers:[],referAll:!1}];if(e.type==="vector")return e.children.length>0&&dt(e.children[0])===null?e.children.flatMap(n=>ra(n,t)):RF(e,t);if(e.type==="list"&&e.children.length>0){let n=dt(e.children[0]);return n?!n||n.startsWith(":")?[]:e.children.slice(1).flatMap(r=>ra(r,yu(t,n))):e.children.flatMap(r=>ra(r,t))}return[]}function RF(e,t){let n=dt(e.children[0]);if(!n||n.startsWith(":"))return[];let r={namespace:yu(t,n),alias:null,refers:[],referAll:!1};for(let i=1;i<e.children.length;i+=1){let o=dt(e.children[i]);if(!o?.startsWith(":"))continue;let s=e.children[i+1];if((o===":as"||o===":as-alias")&&s){r.alias=dt(s),i+=1;continue}o===":refer"&&s&&(dt(s)===":all"?r.referAll=!0:(s.type==="vector"||s.type==="list")&&r.refers.push(...s.children.map(dt).filter(IF)),i+=1)}return[r]}function vF(e){let t=[];for(let n of e){if(n.type==="atom"){let i=n.text.split(".").pop()??n.text;t.push(nn(i,i,null,!0));continue}if(n.type!=="vector")continue;let r=dt(n.children[0]);if(r)for(let i of n.children.slice(1)){let o=dt(i);o&&t.push(nn(`${r}.${o}`,o,null,!0))}}return t}function yu(e,t){return e?`${e}.${t}`:t}function dt(e){return e?.type==="atom"?e.text:null}function IF(e){return!!(e&&!e.startsWith(":"))}function wF(e,t){let n=new Set,r=new RegExp(`${Su()}${H(t)}\\s*/\\s*([${bu}]+)`,"g");for(let i of e.matchAll(r)){let o=i[1];o&&n.add(o)}return[...n]}function EF(e,t){return new RegExp(`${Su()}${H(t)}\\s*/`,"m").test(e)}function DF(e,t){return new RegExp(`${Su()}${H(t)}(?![${bu}])`,"m").test(e)}function Su(){return`(?<![${bu}])`}function kF(e,t,n){let r="",i=0;for(;i<e.length;){if(i>=t&&i<n){r+=e[i]===`
|
|
133
|
+
`?`
|
|
134
|
+
`:" ",i+=1;continue}let o=e[i];if(o===";"){let s=js(e,i);r+=lh(e.slice(i,s)),i=s;continue}if(o==='"'){let s=Vi(e,i,0).index;r+=lh(e.slice(i,s)),i=s;continue}r+=o,i+=1}return r}function PF(e){let t=0;for(;t<e.length&&(t=xu(e,t),!(t>=e.length));){let n=ia(e,t);if(!n){t+=1;continue}if(SF(n.form))return n.form;t=n.index}return null}function ia(e,t){let n=xu(e,t);if(e.startsWith("#?@",n)||e.startsWith("#?",n))return FF(e,n);if(e.startsWith("#_",n)){let i=ia(e,n+2);return i?{form:{type:"atom",text:"",start:n,end:i.index},index:i.index}:null}for(;ql(e[n]);)n+=1;let r=e[n];return r?r==="("?hu(e,n,"list",")"):r==="["?hu(e,n,"vector","]"):r==="{"?hu(e,n,"map","}"):r==='"'?{form:{type:"atom",text:"",start:n,end:Vi(e,n,0).index},index:Vi(e,n,0).index}:_F(e,n):null}function FF(e,t){let n=e.startsWith("#?@",t)?3:2,r=ia(e,t+n);return r?{form:{type:"list",children:r.form.type==="list"||r.form.type==="vector"||r.form.type==="map"?TF(r.form.children):[],start:t,end:r.index},index:r.index}:null}function TF(e){let t=[];for(let n=0;n<e.length;n+=2){let r=dt(e[n]),i=e[n+1];r?.startsWith(":")&&i&&t.push(i)}return t}function hu(e,t,n,r){let i=[],o=t+1;for(;o<e.length;){if(o=xu(e,o),e[o]===r)return{form:{type:n,children:i,start:t,end:o+1},index:o+1};let s=ia(e,o);if(!s){o+=1;continue}s.form.type==="atom"&&s.form.text===""||i.push(s.form),o=s.index}return{form:{type:n,children:i,start:t,end:e.length},index:e.length}}function _F(e,t){let n=t;for(;n<e.length&&!Gl(e[n]);)n+=1;return{form:{type:"atom",text:e.slice(t,n),start:t,end:n},index:n}}function xu(e,t){let n=t;for(;n<e.length;){let r=e[n];if(/\s|,/.test(r)){n+=1;continue}if(r===";"){n=js(e,n);continue}break}return n}function lh(e){return e.replace(/[^\r\n]/g," ")}function dh(e,t,n){let r=[];for(let i of n.matchAll(/^[ \t]*import\s+['"]([^'"]+)['"](?:\s+as\s+([A-Za-z_]\w*))?[\s\S]*?;$/gm)){let o=i[1]?.trim(),s=i[2]?.trim()??null,a=i[0];if(!o||!a||typeof i.index!="number")continue;let c=Pn(n,i.index,i.index+a.length);r.push({importedName:o,localName:s,sourcePath:Js(e,t,o),kind:s?"namespace":"side-effect",used:s?Ke(c,s):!0,usedMembers:s?zr(c,s):[]})}return r}function mh(e,t,n){let r=[];for(let i of n.matchAll(/^[ \t]*export\s+['"]([^'"]+)['"][\s\S]*?;$/gm)){let o=i[1]?.trim();o&&r.push({specifier:o,sourcePath:Js(e,t,o)})}return r}function fh(e,t,n){return na(e,t,{csharp:r=>MF(e,t,r),vb:r=>LF(e,t,r)},()=>{let r=$g(t)?/^[ \t]*Imports\s+(.+?)\s*$/gm:/^[ \t]*using\s+(.+?)\s*;$/gm;return lt(n,r,(i,o)=>{let s=i[1]?.trim();if(!s)return[];let[a,c]=s.split(/\s*=\s*/),l=!!c,u=(l?c:a)?.trim()??s,d=u.split(".").pop()??u,m=l?a?.trim()??d:d;return[Ct(e,t,o,u,d,m,ve(e,u,Dn))]})})}function LF(e,t,n){let r=Ie(n,new Set(["imports_statement"])),i=[];for(let o of n.rootNode.descendantsOfType("imports_statement")){let s=o.namedChildren.filter(m=>m.type==="namespace_name");if(s.length===0)continue;let a=s[s.length-1],c=s.length>1?s[0]:null,l=a.text,u=l.split(".").pop()??l,d=c?.text??u;i.push(be(u,d,ve(e,l,Dn),r,c?"namespace":"named"))}return i}function MF(e,t,n){let r=Ie(n,new Set(["using_directive"])),i=[];for(let o of n.rootNode.descendantsOfType("using_directive")){let s=o.namedChildren;if(s.length===0)continue;let a=null,c;s.length>=2&&s[0].type==="identifier"&&(s[1].type==="qualified_name"||s[1].type==="identifier")?(a=s[0],c=s[1]):c=s[s.length-1];let l=c.text,u=l.split(".").pop()??l,d=a?.text??u;i.push(be(u,d,ve(e,l,Dn),r,a?"namespace":"named"))}return i}var AF=B("vue-non-script-identifiers",{clearGroups:["whole-project","source-file"]});function ph(e,t){return AF.get(e,t,()=>{let n=new Set,r=P(e,t);if(!r)return n;let o=r.replace(/<script\b[^>]*>[\s\S]*?<\/script>/g,s=>s.replace(/[^\r\n]/g," ")).replace(/<!--[\s\S]*?-->/g,s=>s.replace(/[^\r\n]/g," ")).replace(/\/\*[\s\S]*?\*\//g,s=>s.replace(/[^\r\n]/g," "));for(let s of o.matchAll(/[A-Za-z_$][\w$]*/g))n.add(s[0]);return n})}function Cu(e,t,n){return ut(e,t,r=>OF(e,t,r),()=>NF(e,t,n))}function NF(e,t,n){return KF(n).flatMap(r=>JF(e,t,r.clause,r.specifier,r.start,r.end,n))}function OF(e,t,n){let r=jF(e,t,n),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))i.push(...BF(e,t,n,o,r));return i}function jF(e,t,n){let r=Ie(n,new Set(["import_statement"]));if(Yt(t))for(let i of ph(e,t))r.add(i);return r}function BF(e,t,n,r,i){let o=GF(r);if(!o)return[];let s=tt(e,t,o),a=nt(r,"import_clause");return a?$F(n,a,s,i,VF(r.text)):[cr("*",s)]}function $F(e,t,n,r,i){let o=[];for(let s of t.namedChildren)if(s.type==="identifier")o.push(HF(s.text,n,r,i));else if(s.type==="namespace_import"){let a=UF(e,s,n,r,i);a&&o.push(a)}else s.type==="named_imports"&&o.push(...qF(s,n,r,i));return o}function HF(e,t,n,r){return be("default",e,t,n,"default",{isTypeOnly:r})}function UF(e,t,n,r,i){let s=nt(t,"identifier")?.text??"";if(!s)return null;let a=zF(e,s);return lr("*",n,{localName:s,usedMembers:a,isTypeOnly:i,used:a.length>0||r.has(s)})}function qF(e,t,n,r){let i=[];for(let o of e.namedChildren){if(o.type!=="import_specifier")continue;let s=o.namedChild(0),a=o.namedChild(1);if(!s)continue;let c=s.text,l=a?.text??c;i.push(be(c,l,t,n,"named",{isTypeOnly:r||WF(o.text)}))}return i}function GF(e){let t=nt(e,"string");if(!t)return null;let n=nt(t,"string_fragment");return n?n.text:null}function VF(e){return/^\s*import\s+type\b/.test(e)}function WF(e){return/^\s*type\b/.test(e.trim())}function zF(e,t){let n=new Set;for(let r of e.rootNode.descendantsOfType("member_expression")){let i=r.namedChild(0),o=r.namedChild(1);!i||!o||i.type!=="identifier"||i.text!==t||(o.type==="property_identifier"||o.type==="identifier")&&n.add(o.text)}return[...n]}function KF(e){let t=[],n=/^[ \t]*import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let i of e.matchAll(n)){let o=i[0],s=i[1],a=i[2];!o||!a||typeof i.index!="number"||t.push({clause:s,specifier:a,start:i.index,end:i.index+o.length})}let r=/^[ \t]*import\s+['"]([^'"]+)['"]\s*;?/gm;for(let i of e.matchAll(r)){let o=i[0],s=i[1];!o||!s||typeof i.index!="number"||t.push({clause:null,specifier:s,start:i.index,end:i.index+o.length})}return t.sort((i,o)=>i.start-o.start)}function JF(e,t,n,r,i,o,s){let a=tt(e,t,r),c=Pn(s,i,o);return n?YF(n).map(u=>({...u,sourcePath:a})).map(u=>{if(u.kind==="namespace"){let d=zr(c,u.localName);return lr(u.importedName,u.sourcePath,{localName:u.localName,usedMembers:d,used:d.length>0||Ke(c,u.localName),isTypeOnly:u.isTypeOnly})}return u.kind==="side-effect"?cr(u.importedName,u.sourcePath):nn(u.importedName,u.localName??"",u.sourcePath,u.localName?Ke(c,u.localName):!1,u.kind,[],{isTypeOnly:u.isTypeOnly})}):[cr("*",a)]}function YF(e){let t=e.trim(),n=/^type\b/.test(t),r=t.replace(/^type\s+/,""),[i,o]=XF(r),s=[];return i&&s.push(...gh(i,n)),o&&s.push(...gh(o,n)),s}function gh(e,t){let n=e.trim();if(!n)return[];if(n.startsWith("{")){let r=n.slice(1,-1).trim();return r?Je(r).map(i=>{let o=i.trim(),s=t||/^type\b/.test(o),a=o.replace(/^type\s+/,""),[c,l]=a.split(/\s+as\s+/);return{importedName:c.trim(),localName:(l??c).trim(),kind:"named",isTypeOnly:s}}):[]}return n.startsWith("* as ")?[{importedName:"*",localName:n.slice(5).trim(),kind:"namespace",isTypeOnly:t}]:[{importedName:"default",localName:n,kind:"default",isTypeOnly:t}]}function XF(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r==="{"&&t++,r==="}"&&t--,r===","&&t===0)return[e.slice(0,n).trim(),e.slice(n+1).trim()]}return[e.trim(),null]}function Ru(e,t,n){let r=Y(e,t);return r?rT(e,t,r):QF(e,t,n)}function QF(e,t,n){return[...ZF(e,t,n),...eT(e,t,n),...tT(e,t,n)]}function ZF(e,t,n){let r=[],i=/^[ \t]*export\s+(?:type\s+)?\{([\s\S]*?)\}\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[1]??"",a=o[2]??"",c=Je(s).map(d=>nT(d.trim())).filter(d=>!!d),l=Kr(n,o.index),u=Kr(n,o.index+o[0].length-1);r.push({kind:"named",sourcePath:tt(e,t,a),names:c,startLine:l,endLine:u})}return r}function eT(e,t,n){let r=[],i=/^[ \t]*export\s+\*\s+as\s+(\w+)\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[2]??"",a=Kr(n,o.index),c=Kr(n,o.index+o[0].length-1);r.push({kind:"star-as",sourcePath:tt(e,t,s),names:[],startLine:a,endLine:c})}return r}function tT(e,t,n){let r=[],i=/^[ \t]*export\s+\*\s+from\s+['"]([^'"]+)['"]\s*;?/gm;for(let o of n.matchAll(i)){if(typeof o.index!="number")continue;let s=o[1]??"",a=Kr(n,o.index),c=Kr(n,o.index+o[0].length-1);r.push({kind:"star",sourcePath:tt(e,t,s),names:[],startLine:a,endLine:c})}return r}function nT(e){if(!e)return null;let t=e.replace(/^type\s+/,"").trim();if(!t)return null;let n=t.match(/^(\w+)\s+as\s+(\w+)$/);if(n)return n[2]??null;let r=t.match(/^(\w+)$/);return r?r[1]??null:null}function Kr(e,t){let n=0;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function rT(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("export_statement")){let o=iT(e,t,i);if(o===void 0)continue;let s=i.startPosition.row,a=i.endPosition.row,c=oT(i,o,s,a);r.push(c)}return r}function iT(e,t,n){let r=nt(n,"string");if(!r)return;let i=nt(r,"string_fragment");if(i)return tt(e,t,i.text)}function oT(e,t,n,r){let i=nt(e,"export_clause");if(i){let s=[];for(let a of i.namedChildren){if(a.type!=="export_specifier")continue;let c=a.namedChild(0),l=a.namedChild(1);c&&s.push((l??c).text)}return{kind:"named",sourcePath:t,names:s,startLine:n,endLine:r}}return nt(e,"namespace_export")?{kind:"star-as",sourcePath:t,names:[],startLine:n,endLine:r}:{kind:"star",sourcePath:t,names:[],startLine:n,endLine:r}}function hh(e,t,n){return na(e,t,{java:r=>sT(e,t,r),kotlin:r=>aT(e,t,r),scala:r=>cT(e,t,r)},()=>lt(n,/^[ \t]*import\s+(?:static\s+)?(.+?)\s*;?$/gm,(r,i)=>{let o=r[1]?.trim();return o?lT(e,t,o,i):[]}))}function sT(e,t,n){let r=Ie(n,new Set(["import_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.children.some(d=>d.type==="asterisk"),c=o.namedChildren.find(d=>d.type==="scoped_identifier")??o.namedChildren.find(d=>d.type==="identifier");if(!c)continue;let l=c.text;if(s){i.push(lr("*",ve(e,l,et)));continue}let u=l.split(".").pop()??l;i.push(be(u,u,ve(e,l,et),r))}return i}function aT(e,t,n){let r=Ie(n,new Set(["import_header","import_list"])),i=[];for(let o of n.rootNode.descendantsOfType("import_header")){let s=o.namedChildren.find(f=>f.type==="identifier");if(!s)continue;let a=o.namedChildren.some(f=>f.type==="wildcard_import"),c=o.namedChildren.find(f=>f.type==="import_alias");if(a){i.push(lr("*",ve(e,s.text,et)));continue}let l=s.text,u=l.split(".").pop()??l,m=c?.namedChild(0)?.text??u;i.push(be(u,m,ve(e,l,et),r))}return i}function cT(e,t,n){let r=Ie(n,new Set(["import_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("import_declaration")){let s=o.namedChildren.find(d=>d.type==="namespace_selectors"||d.type==="namespace_wildcard"),a=o.namedChildren.filter(d=>d!==s&&(d.type==="identifier"||d.type==="stable_identifier")),c=a.map(d=>d.text).join(".");if(!c)continue;if(s?.type==="namespace_wildcard"){i.push(lr("*",ve(e,c,et)));continue}if(s?.type==="namespace_selectors"){for(let d of s.namedChildren)if(d.type==="arrow_renamed_identifier"){let[m,f]=d.namedChildren;if(!m)continue;let p=m.text,g=f?.text??p;if(p==="_")continue;i.push(be(p,g,ve(e,`${c}.${p}`,et),r))}else if(d.type==="identifier"){let m=d.text;i.push(be(m,m,ve(e,`${c}.${m}`,et),r))}continue}let l=a[a.length-1]?.text??c,u=a.slice(0,-1).map(d=>d.text).join(".")||c;i.push(be(l,l,ve(e,u&&a.length>1?`${u}.${l}`:c,et),r))}return i}function lT(e,t,n,r){if(n.includes("{")&&n.includes("}")){let i=n.slice(0,n.indexOf("{")).replace(/\.$/,"").trim(),o=n.slice(n.indexOf("{")+1,n.lastIndexOf("}")).trim();return Je(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.includes("=>")?a.split(/\s*=>\s*/):a.split(/\s+as\s+/),u=c?.trim();if(!u||u==="_")return[];let d=(l??u.split(".").pop()??u).trim(),m=u==="_"?i:`${i}.${u}`.replace(/\.\./g,".");return[Ct(e,t,r,m,u,d)]})}return[Ct(e,t,r,n,n.split(".").pop()??n,n.split(".").pop()??n)]}function bh(e,t,n){return ut(e,t,r=>uT(e,t,r),()=>lt(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?Je(o).flatMap(s=>{let a=s.trim();if(!a)return[];let[c,l]=a.split(/\s+as\s+/i),u=c?.trim()??a,d=u.split("\\").pop()??u,m=(l??d).trim();return[Ct(e,t,i,u,d,m,ve(e,u.replace(/\\/g,"."),sr))]}):[]}))}function uT(e,t,n){let r=Ie(n,new Set(["namespace_use_declaration"])),i=[],o=(s,a,c)=>{i.push(be(a,c,ve(e,s.replace(/\\/g,"."),sr),r))};for(let s of n.rootNode.descendantsOfType("namespace_use_declaration")){let a=s.namedChildren.find(c=>c.type==="namespace_use_group");if(a){let c=s.namedChildren.find(l=>l.type==="namespace_name")?.text??"";for(let l of a.namedChildren){if(l.type!=="namespace_use_clause")continue;let{importedName:u,localName:d,qualified:m}=yh(l,c);u&&o(m,u,d)}continue}for(let c of s.namedChildren){if(c.type!=="namespace_use_clause")continue;let{importedName:l,localName:u,qualified:d}=yh(c,"");l&&o(d,l,u)}}return i}function yh(e,t){let n=e.namedChildren.find(l=>l.type==="qualified_name"),r=e.namedChildren.filter(l=>l.type==="name"),i="";n?i=n.text:r.length>=1&&(i=r[0].text);let o=n&&r.length>0?r[r.length-1]:null,s=i.split("\\").pop()??i,a=o?.text??s,c=t?`${t}\\${i}`:i;return{importedName:s,localName:a,qualified:c}}function xh(e,t,n){return ut(e,t,r=>dT(e,t,r),()=>fT(n).flatMap(r=>gT(e,t,r,n)))}function dT(e,t,n){let r=Ie(n,new Set(["import_statement","import_from_statement"])),i=[];for(let o of n.rootNode.descendantsOfType("import_statement"))for(let s of o.namedChildren){let a=Sh(s);if(!a)continue;let c=Vr(e,t,a.qualifiedName);i.push({importedName:a.qualifiedName,localName:a.localName,sourcePath:c,kind:"namespace",used:r.has(a.localName),usedMembers:[]})}for(let o of n.rootNode.descendantsOfType("import_from_statement")){let s=o.namedChild(0);if(!s)continue;let a=mT(s);if(a===null)continue;let c=Vr(e,t,a);for(let l=1;l<o.namedChildCount;l+=1){let u=o.namedChild(l);if(u.type==="wildcard_import"){i.push({importedName:"*",localName:null,sourcePath:c,kind:"side-effect",used:!0,usedMembers:[]});continue}let d=Sh(u);d&&i.push({importedName:d.qualifiedName,localName:d.localName,sourcePath:c,kind:"named",used:r.has(d.localName),usedMembers:[]})}}return i}function Sh(e){if(e.type==="aliased_import"){let t=e.namedChild(0),n=e.namedChild(1);return!t||!n?null:{qualifiedName:t.text,localName:n.text}}if(e.type==="dotted_name"){let t=e.text;return{qualifiedName:t,localName:t.split(".")[0]??t}}return e.type==="identifier"?{qualifiedName:e.text,localName:e.text}:null}function mT(e){if(e.type==="dotted_name")return e.text;if(e.type==="relative_import"){let t=nt(e,"import_prefix")?.text??"",n=nt(e,"dotted_name")?.text??"";return`${t}${n}`}return null}function fT(e){let t=e.split(`
|
|
135
|
+
`),n=[],r=0;for(let i=0;i<t.length;i++){let o=t[i],s=o.trimStart(),a=r;if(r+=o.length+1,!s.startsWith("import ")&&!s.startsWith("from "))continue;let c=o,l=a+o.length,u=Xi(o);for(;i+1<t.length&&(u>0||c.trimEnd().endsWith("\\"));){i++;let m=t[i];c+=`
|
|
136
|
+
${m}`,l+=1+m.length,u+=Xi(m),r+=m.length+1}let d=pT(c);d&&n.push({...d,start:a,end:l})}return n}function pT(e){let t=e.replace(/\\\s*\n/g," ").trim();if(t.startsWith("import "))return{kind:"import",module:null,clause:t.slice(7).trim()};let n=t.match(/^from\s+([.\w]+)\s+import\s+([\s\S]+)$/);if(!n)return null;let r=n[2].trim();return r.startsWith("(")&&r.endsWith(")")&&(r=r.slice(1,-1).trim()),{kind:"from",module:n[1],clause:r}}function gT(e,t,n,r){let i=Pn(r,n.start,n.end),o=n.clause.replace(/\n/g," ").trim();if(n.kind==="import")return Je(o).flatMap(c=>{let l=c.trim().replace(/,$/,"");if(!l)return[];let[u,d]=l.split(/\s+as\s+/),m=u.trim(),f=(d??m.split(".")[0]??m).trim(),p=Vr(e,t,m),g=zr(i,f);return[{importedName:m,localName:f,sourcePath:p,kind:"namespace",used:Ke(i,f)||g.length>0,usedMembers:g}]});let s=n.module?Vr(e,t,n.module):null,a=[];for(let c of Je(o)){let l=c.trim().replace(/,$/,"");if(!l)continue;if(l==="*"){a.push({importedName:"*",localName:null,sourcePath:s,kind:"side-effect",used:!0,usedMembers:[]});continue}let[u,d]=l.split(/\s+as\s+/),m=(d??u).trim();a.push({importedName:u.trim(),localName:m,sourcePath:s,kind:"named",used:Ke(i,m),usedMembers:[]})}return a}import{basename as hT}from"path";function Ch(e,t,n){return ut(e,t,r=>bT(e,t,r),()=>yT(e,t,n))}function yT(e,t,n){return lt(n,/^[ \t]*(require_relative|require)\s+["']([^"']+)["']\s*$/gm,(r,i)=>{let o=r[1],s=r[2];if(!o||!s)return[];let a=o==="require_relative"?zs(e,t,s):null;if(a){let c=Rh(s);return[nn(c,c,a,Ke(i,c))]}return[cr(s,a)]})}function bT(e,t,n){let r=Ie(n,new Set([])),i=[],o=new Set(["require","require_relative","load"]);for(let s of n.rootNode.descendantsOfType("call")){let a=s.namedChild(0);if(!a||a.type!=="identifier"||!o.has(a.text))continue;let l=s.namedChildren.find(f=>f.type==="argument_list")?.namedChild(0);if(!l||l.type!=="string")continue;let d=l.namedChildren.find(f=>f.type==="string_content")?.text;if(!d)continue;let m=a.text==="require_relative"?zs(e,t,d):null;if(m){let f=Rh(d);i.push(be(f,f,m,r))}else i.push(cr(d,m))}return i}function Rh(e){return $s(hT(e).replace(/\.[^.]+$/,""),/_/)}function vh(e,t,n){return ut(e,t,r=>ST(e,t,r),()=>lt(n,/^[ \t]*use\s+(.+?)\s*;$/gm,(r,i)=>{let o=r[1]?.trim();return o?xT(e,t,o,i):[]}))}function ST(e,t,n){let r=Ie(n,new Set(["use_declaration"])),i=[];for(let o of n.rootNode.descendantsOfType("use_declaration")){let s=o.namedChild(0);if(s)for(let a of Qi(s,"")){if(!a.importedName||a.importedName==="*")continue;let c=Zt(e,t,a.qualifiedName)??Zt(e,t,a.qualifiedName.split("::").slice(0,-1).join("::"));i.push(be(a.importedName,a.localName,c,r))}}return i}function Qi(e,t){switch(e.type){case"identifier":case"super":case"crate":{let n=e.text;return[{qualifiedName:Jr(t,n),importedName:n,localName:n}]}case"self":{let n=t.split("::").filter(Boolean).pop()??"self";return[{qualifiedName:t||"self",importedName:n,localName:n}]}case"scoped_identifier":{let n=e.text,r=n.split("::").pop()??n;return[{qualifiedName:Jr(t,n),importedName:r,localName:r}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=Jr(t,n.text),o=[];for(let s of r.namedChildren)o.push(...Qi(s,i));return o}case"use_list":{let n=[];for(let r of e.namedChildren)n.push(...Qi(r,t));return n}case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=Qi(n,t),o=r.text;return i.map(s=>({...s,localName:o}))}case"use_wildcard":{let n=e.namedChild(0),r=n?n.text:"";return[{qualifiedName:Jr(t,`${r}::*`),importedName:"*",localName:"*"}]}default:return[]}}function Jr(e,t){return e?t?`${e}::${t}`:e:t}function xT(e,t,n,r){let i=n.trim();if(i.includes("{")&&i.includes("}")){let u=i.slice(0,i.indexOf("{")).replace(/::$/,"").trim(),d=i.slice(i.indexOf("{")+1,i.lastIndexOf("}")).trim();return Je(d).flatMap(m=>{let f=m.trim();if(!f)return[];if(f==="self"){let b=u.split("::").filter(Boolean).pop();return b?[Ct(e,t,r,u,b,b)]:[]}let[p,g]=f.split(/\s+as\s+/),y=p?.trim();if(!y)return[];let h=(g??y.split("::").pop()??y).trim(),C=`${u}::${y}`.replace(/::::/g,"::");return[Ct(e,t,r,C,y.split("::").pop()??y,h,Zt(e,t,u))]})}let[o,s]=i.split(/\s+as\s+/),a=o?.trim()??i,c=(s??a.split("::").pop()??a).trim(),l=Zt(e,t,a)??Zt(e,t,a.split("::").slice(0,-1).join("::"));return[Ct(e,t,r,a,a.split("::").pop()??a,c,l)]}function Ih(e,t,n){let r=Y(e,t);if(r)return CT(e,t,r);let i=[];for(let o of n.matchAll(/^[ \t]*pub\s+use\s+(.+?)\s*;$/gm)){let s=o[1]?.trim();s&&i.push(...vT(e,t,s))}return i}function CT(e,t,n){let r=[];for(let i of n.rootNode.descendantsOfType("use_declaration")){if(!RT(i))continue;let o=i.namedChildren.find(s=>s.type!=="visibility_modifier");if(o)for(let s of Qi(o,""))s.importedName&&r.push(vu(e,t,s.qualifiedName))}return r}function RT(e){for(let t of e.children)if(t.type==="visibility_modifier"&&t.text.startsWith("pub"))return!0;return!1}function vT(e,t,n){let r=n.trim();if(r.includes("{")&&r.includes("}")){let i=r.slice(0,r.indexOf("{")).replace(/::$/,"").trim(),o=r.slice(r.indexOf("{")+1,r.lastIndexOf("}")).trim();return Je(o).flatMap(s=>{let a=s.trim();if(!a||a==="self")return[];let[c]=a.split(/\s+as\s+/),l=`${i}::${c?.trim()??a}`.replace(/::::/g,"::");return[vu(e,t,l)]})}return[vu(e,t,r)]}function vu(e,t,n){return{specifier:n,sourcePath:Zt(e,t,n)??Zt(e,t,n.split("::").slice(0,-1).join("::"))}}function Fn({language:e,extensions:t,imports:n,parseImports:r}){return{language:e,extensions:t,capabilities:{imports:n},parseImports:r}}function wh(e,t){let n=t.toLowerCase();for(let r of e)for(let i of r.extensions)if(n.endsWith(i))return r;return null}var IT={language:"javascript",extensions:ir,capabilities:{imports:"ast-with-regex-fallback",reExports:"ast-with-regex-fallback"},parseImports:Cu,parseReExports:Ru},wT=Fn({language:"python",extensions:Us,imports:"ast-with-regex-fallback",parseImports:xh}),ET=Fn({language:"jvm",extensions:et,imports:"ast-dispatch-with-regex-fallback",parseImports:hh}),DT={language:"rust",extensions:qs,capabilities:{imports:"ast-with-regex-fallback",exports:"ast-with-regex-fallback"},parseImports:vh,parseExports:Ih},kT=Fn({language:"ruby",extensions:Gs,imports:"ast-with-regex-fallback",parseImports:Ch}),PT=Fn({language:"c/cpp",extensions:Vs,imports:"ast-with-regex-fallback",parseImports:ch}),FT=Fn({language:"dotnet",extensions:Dn,imports:"ast-dispatch-with-regex-fallback",parseImports:fh}),TT={language:"dart",extensions:Ws,capabilities:{imports:"regex-only",exports:"regex-only"},parseImports:dh,parseExports:mh},_T=Fn({language:"php",extensions:sr,imports:"ast-with-regex-fallback",parseImports:bh}),LT=Fn({language:"clojure",extensions:Gr,imports:"regex-only",parseImports:uh}),Eh=[IT,wT,ET,DT,kT,PT,FT,TT,_T,LT];function oa(e){return wh(Eh,e)}function d9(e){return Eh.find(n=>n.language===e)?.capabilities??null}var Iu={clearGroups:["whole-project","source-file"]},MT=B("source-imports",Iu),AT=B("source-exports",Iu),NT=B("source-reexports",Iu),Dh=ce({kind:"source-imports",invalidation:X("source-imports"),serialize:OT,deserialize:jT}),kh=ce({kind:"source-reexports",invalidation:X("source-reexports"),serialize:BT,deserialize:$T});function rn(e,t){let n=se(t);return NT.get(e,n,()=>{let r=oa(n);if(!r?.parseReExports)return[];let i=P(e,n);if(!i)return[];let o=me(e,n,i),s=uu(e),a=kh.read(e,n,o);if(a?.resolutionFingerprint===s)return a.reExports;let c=r.parseReExports(e,n,i);return kh.write(e,n,o,{resolutionFingerprint:s,reExports:c}),c})}function te(e,t){let n=se(t);return MT.get(e,n,()=>{let r=oa(n);if(!r)return[];let i=P(e,n);if(!i)return[];let o=me(e,n,i),s=uu(e),a=Dh.read(e,n,o);if(a?.resolutionFingerprint===s)return a.imports;let c=r.parseImports(e,n,i);return Dh.write(e,n,o,{resolutionFingerprint:s,imports:c}),c})}function sa(e,t){let n=se(t);return AT.get(e,n,()=>{let r=oa(n);if(!r?.parseExports)return[];let i=P(e,n);return i?r.parseExports(e,n,i):[]})}function OT(e){return JSON.stringify(e)}function jT(e){try{let t=JSON.parse(e);return!Mt(t)||typeof t.resolutionFingerprint!="string"||!Array.isArray(t.imports)?null:{resolutionFingerprint:t.resolutionFingerprint,imports:t.imports}}catch{return null}}function BT(e){return JSON.stringify(e)}function $T(e){try{let t=JSON.parse(e);return!Mt(t)||typeof t.resolutionFingerprint!="string"||!Array.isArray(t.reExports)?null:{resolutionFingerprint:t.resolutionFingerprint,reExports:t.reExports}}catch{return null}}function mt(e){return{forFile(t,n){return Ph(e,t,n)},forFiles(t,n){let r=new Map;for(let i of t)r.set(i,Ph(e,i,n));return r}}}function Ph(e,t,n){let r={file:t},i=n.facts||n.identifiers;if(n.text&&(r.text=P(e,t)),n.lines&&(r.lines=Ee(e,t)),n.ast&&(r.ast=Y(e,t)),n.imports&&(r.imports=te(e,t)),n.reexports&&(r.reexports=rn(e,t)),i){let o=Wl(e,t),s=o.facts;n.facts&&(r.facts=s),o.unavailable&&(r.sourceFactsUnavailable=o.unavailable),n.identifiers&&s&&(r.identifiers=s.fileIdentifiers,r.identifierLineMap=s.identifierLineMap)}return r}function ur(e,t){return e.all(`SELECT gs.id, gs.symbol, der.document_id, der.start_line, der.start_char, der.end_line, der.end_char, d.relative_path, gs.display_name, gs.documentation
|
|
137
|
+
FROM global_symbols gs
|
|
138
|
+
JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
|
|
139
|
+
JOIN documents d ON der.document_id = d.id
|
|
140
|
+
WHERE ${t.where}
|
|
141
|
+
${e.pathExclusionsFor("d")}
|
|
142
|
+
${Th(t.orderBy)}
|
|
143
|
+
${_h(t.limit)}`,...t.params??[])}function Yr(e,t){return e.all(`SELECT
|
|
144
|
+
gs.id,
|
|
145
|
+
gs.symbol,
|
|
146
|
+
c.document_id,
|
|
147
|
+
MIN(c.start_line) AS start_line,
|
|
148
|
+
0 AS start_char,
|
|
149
|
+
MAX(c.end_line) AS end_line,
|
|
150
|
+
0 AS end_char,
|
|
151
|
+
d.relative_path,
|
|
152
|
+
gs.display_name,
|
|
153
|
+
gs.documentation
|
|
154
|
+
FROM global_symbols gs
|
|
155
|
+
JOIN mentions m ON m.symbol_id = gs.id
|
|
156
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
157
|
+
JOIN documents d ON c.document_id = d.id
|
|
158
|
+
WHERE m.role = 1
|
|
159
|
+
AND ${t.where}
|
|
160
|
+
${e.pathExclusionsFor("d")}
|
|
161
|
+
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path, gs.display_name, gs.documentation
|
|
162
|
+
${Th(t.orderBy)}
|
|
163
|
+
${_h(t.limit)}`,...t.params??[])}function Th(e){return e?`ORDER BY ${e}`:""}function _h(e){return typeof e=="number"?`LIMIT ${e}`:""}function on(e){return!e||!e.trim()?null:e.replace(/^```\w*\s*/,"").replace(/\s*```$/,"").replace(/^\(method\)\s*/,"").replace(/^\(property\)\s*/,"").replace(/^\(function\)\s*/,"").replace(/^\(class\)\s*/,"").replace(/^\(interface\)\s*/,"").replace(/^\(enum\)\s*/,"").replace(/^\(type alias\)\s*/,"").replace(/^\(const\)\s*/,"").replace(/^\(var\)\s*/,"").trim()||null}function sn(e){if(!e)return null;let t=Fh(e);if(t)return t.replace(/\n/g," ");let n=e.indexOf("|");if(n===-1)return e.replace(/\n/g," ");let r=e.slice(n+1);return(Fh(r)??r).replace(/\n/g," ")}function Fh(e){return/^```(?:\w+)?\s*\n?([\s\S]*?)\n?```/.exec(e.trimStart())?.[1]?.trim()||null}function HT(e,t={}){if(Lt(e.symbol)!==null)return t.includeClassMemberFallbacks===!0;let i=(e.documentation??"").replace(/^```\w*\s*/,"").replace(/\s*```$/,"").trim();return/^(?:var|let|const|function|class|interface|type|enum)\b/.test(i)}function Tn(e,t,n={}){let r=new Map;for(let o of t)e.length>0&&!HT(o,{includeClassMemberFallbacks:n.includeClassMemberFallbacks})||r.set(o.id,o);for(let o of e)r.set(o.id,o);let i=[...r.values()];return n.sort?i.sort((o,s)=>o.start_line-s.start_line||o.end_line-s.end_line||o.symbol.localeCompare(s.symbol)):i}var UT=B("file-definitions",{clearGroups:["definition-catalog"]}),qT=B("file-function-like-definitions",{clearGroups:["definition-catalog"]}),Lh=new WeakMap;function Q(e,t,n={}){return n.includeClassMemberFallbacks?wu(e,t,void 0,{includeClassMemberFallbacks:!0}):UT.get(e,t,()=>{let r=Oh(e,t);if(r)return r;let i=wu(e,t),o=Ne(e),s=mt(e).forFile(t,{text:!0}).text;return o&&s&&Nh.write(e,t,me(e,t,s),{projectFingerprint:o,definitions:i.map(a=>({...a}))}),i})}function GT(e,t){return qT.get(e,t,()=>{let n=Oh(e,t);return n?n.filter(r=>r.isFunctionLike):wu(e,t,r=>r.isFunctionLike)})}var Nh=ce({kind:"file-definitions",invalidation:X("file-definitions"),serialize:VT,deserialize:WT});function Oh(e,t){let n=Ne(e);if(!n)return null;let r=mt(e).forFile(t,{text:!0}).text;if(!r)return null;let i=Nh.read(e,t,me(e,t,r));return i?zT(i,n,t):null}function VT(e){return JSON.stringify(e)}function WT(e){try{let t=JSON.parse(e);return!Mt(t)||typeof t.projectFingerprint!="string"||!Array.isArray(t.definitions)?null:{projectFingerprint:t.projectFingerprint,definitions:t.definitions}}catch{return null}}function zT(e,t,n){if(e.projectFingerprint!==t)return null;let r=[];for(let i of e.definitions){let o=KT(i,n);if(!o)return null;r.push(o)}return r}function KT(e,t){return!Mt(e)||typeof e.symbolId!="number"||typeof e.symbol!="string"||typeof e.documentId!="number"||typeof e.startLine!="number"||typeof e.startChar!="number"&&e.startChar!==void 0||typeof e.endLine!="number"||typeof e.endChar!="number"&&e.endChar!==void 0||e.relativePath!==t||typeof e.leaf!="string"||typeof e.parentTypeName!="string"&&e.parentTypeName!==null||typeof e.isFunctionLike!="boolean"||typeof e.isTypeLike!="boolean"||typeof e.kind!="number"&&e.kind!==null||typeof e.documentation!="string"&&e.documentation!==null||typeof e.enclosingSymbol!="string"&&e.enclosingSymbol!==null?null:{symbolId:e.symbolId,symbol:e.symbol,documentId:e.documentId,startLine:e.startLine,startChar:e.startChar,endLine:e.endLine,endChar:e.endChar,relativePath:e.relativePath,leaf:e.leaf,parentTypeName:e.parentTypeName,isFunctionLike:e.isFunctionLike,isTypeLike:e.isTypeLike,kind:e.kind,documentation:e.documentation,enclosingSymbol:e.enclosingSymbol}}function wu(e,t,n,r={}){let i=Tn(JT(e,t),YT(e,t),{sort:!0,includeClassMemberFallbacks:r.includeClassMemberFallbacks}).map(jh);return n&&(i=i.filter(n)),Hh(e,t,i)}function JT(e,t){return e.all(`SELECT
|
|
164
|
+
gs.id,
|
|
165
|
+
gs.symbol,
|
|
166
|
+
der.document_id,
|
|
167
|
+
der.start_line,
|
|
168
|
+
der.start_char,
|
|
169
|
+
der.end_line,
|
|
170
|
+
der.end_char,
|
|
171
|
+
d.relative_path,
|
|
172
|
+
gs.display_name,
|
|
173
|
+
gs.kind,
|
|
174
|
+
gs.documentation,
|
|
175
|
+
gs.enclosing_symbol
|
|
176
|
+
FROM global_symbols gs
|
|
177
|
+
JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
|
|
178
|
+
JOIN documents d ON der.document_id = d.id
|
|
179
|
+
WHERE d.relative_path = ?
|
|
180
|
+
${e.symbolNoiseFor("gs")}
|
|
181
|
+
ORDER BY der.start_line, der.end_line`,t)}function YT(e,t){return e.all(`SELECT
|
|
182
|
+
gs.id,
|
|
183
|
+
gs.symbol,
|
|
184
|
+
c.document_id,
|
|
185
|
+
MIN(c.start_line) AS start_line,
|
|
186
|
+
0 AS start_char,
|
|
187
|
+
MAX(c.end_line) AS end_line,
|
|
188
|
+
0 AS end_char,
|
|
189
|
+
d.relative_path,
|
|
190
|
+
gs.display_name,
|
|
191
|
+
gs.kind,
|
|
192
|
+
gs.documentation,
|
|
193
|
+
gs.enclosing_symbol
|
|
194
|
+
FROM global_symbols gs
|
|
195
|
+
JOIN mentions m ON m.symbol_id = gs.id
|
|
196
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
197
|
+
JOIN documents d ON c.document_id = d.id
|
|
198
|
+
WHERE d.relative_path = ?
|
|
199
|
+
AND m.role = 1
|
|
200
|
+
${e.symbolNoiseFor("gs")}
|
|
201
|
+
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
|
|
202
|
+
ORDER BY start_line, end_line`,t)}function jh(e){return{symbolId:e.id,symbol:e.symbol,documentId:e.document_id,startLine:e.start_line,startChar:e.start_char??0,endLine:e.end_line,endChar:e.end_char??0,relativePath:e.relative_path,leaf:F(e.symbol),parentTypeName:Lt(e.symbol),isFunctionLike:oe(e.symbol),isTypeLike:pe(e.symbol)==="type",kind:e.kind??null,documentation:e.documentation??null,enclosingSymbol:e.enclosing_symbol??null}}function De(e,t={}){return Eu(e,t.scope)}function Eu(e,t){return M(e,{scope:t,includeIgnored:!1}).flatMap(n=>Q(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function Bh(e,t){return M(e,{scope:t,includeIgnored:!1}).flatMap(n=>GT(e,n)).filter(n=>!e.isIgnored(n.relativePath))}function Zi(e,t){let n=Mh(XT(e,t.scope,t.sqlPrefilter)),r=Mh(QT(e,t.scope,t.sqlPrefilter)),i=new Set([...n.keys(),...r.keys()]),o=[];for(let s of[...i].sort()){if(e.isIgnored(s))continue;let a=Tn(n.get(s)??[],r.get(s)??[],{sort:!0}).filter(c=>t.symbolMatches(c.symbol));a.length!==0&&o.push(...Hh(e,s,a.map(jh)))}return o}function XT(e,t,n){let r=t?"AND d.relative_path LIKE ?":"",i=n?`AND ${$h("gs",n)}`:"",o=t?[`%${t}%`]:[];return e.all(`SELECT
|
|
203
|
+
gs.id,
|
|
204
|
+
gs.symbol,
|
|
205
|
+
der.document_id,
|
|
206
|
+
der.start_line,
|
|
207
|
+
der.start_char,
|
|
208
|
+
der.end_line,
|
|
209
|
+
der.end_char,
|
|
210
|
+
d.relative_path,
|
|
211
|
+
gs.display_name,
|
|
212
|
+
gs.kind,
|
|
213
|
+
gs.documentation,
|
|
214
|
+
gs.enclosing_symbol
|
|
215
|
+
FROM global_symbols gs
|
|
216
|
+
JOIN defn_enclosing_ranges der ON gs.id = der.symbol_id
|
|
217
|
+
JOIN documents d ON der.document_id = d.id
|
|
218
|
+
WHERE 1 = 1
|
|
219
|
+
${e.pathExclusionsFor("d")}
|
|
220
|
+
${r}
|
|
221
|
+
${i}
|
|
222
|
+
${e.symbolNoiseFor("gs")}
|
|
223
|
+
ORDER BY d.relative_path, der.start_line, der.end_line`,...o)}function QT(e,t,n){let r=t?"AND d.relative_path LIKE ?":"",i=n?`AND ${$h("gs",n)}`:"",o=t?[`%${t}%`]:[];return e.all(`SELECT
|
|
224
|
+
gs.id,
|
|
225
|
+
gs.symbol,
|
|
226
|
+
c.document_id,
|
|
227
|
+
MIN(c.start_line) AS start_line,
|
|
228
|
+
0 AS start_char,
|
|
229
|
+
MAX(c.end_line) AS end_line,
|
|
230
|
+
0 AS end_char,
|
|
231
|
+
d.relative_path,
|
|
232
|
+
gs.display_name,
|
|
233
|
+
gs.kind,
|
|
234
|
+
gs.documentation,
|
|
235
|
+
gs.enclosing_symbol
|
|
236
|
+
FROM global_symbols gs
|
|
237
|
+
JOIN mentions m ON m.symbol_id = gs.id
|
|
238
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
239
|
+
JOIN documents d ON c.document_id = d.id
|
|
240
|
+
WHERE m.role = 1
|
|
241
|
+
${e.pathExclusionsFor("d")}
|
|
242
|
+
${r}
|
|
243
|
+
${i}
|
|
244
|
+
${e.symbolNoiseFor("gs")}
|
|
245
|
+
GROUP BY gs.id, gs.symbol, c.document_id, d.relative_path
|
|
246
|
+
ORDER BY d.relative_path, start_line, end_line`,...o)}function ZT(e){return`(${e}.symbol LIKE '%().' OR ${e}.symbol LIKE '%()')`}function $h(e,t){return t==="callable"?ZT(e):e_(e)}function e_(e){return`(${e}.symbol LIKE '%.' OR ${e}.symbol LIKE '%()')`}function Mh(e){let t=new Map;for(let n of e){let r=t.get(n.relative_path);r?r.push(n):t.set(n.relative_path,[n])}return t}function aa(e,t,n={}){if(t.length===0)return[];let r=t.flatMap(i=>Q(e,i)).filter(i=>!e.isIgnored(i.relativePath));return n.onlyDocumented&&(r=r.filter(i=>i.documentation!==null&&i.documentation!=="")),n.sort&&(r=r.sort((i,o)=>i.relativePath.localeCompare(o.relativePath)||i.startLine-o.startLine||i.endLine-o.endLine)),r.map(i=>({startLine:i.startLine,endLine:i.endLine,symbol:i.symbol,shortName:I(i.symbol),signature:on(sn(i.documentation)),relativePath:i.relativePath,enclosingSymbol:i.enclosingSymbol}))}function Du(e){let t=new Map,n=e.map((r,i)=>({definition:r,index:i,span:r.endLine-r.startLine})).sort((r,i)=>r.span-i.span||r.index-i.index);for(let{definition:r}of n)for(let i=r.startLine;i<=r.endLine;i+=1)t.has(i)||t.set(i,r);return t}function At(e,t){let n=Lh.get(e);return n||(n=Du(e),Lh.set(e,n)),n.get(t)??null}function ca(e,t){let n=Q(e,t.relative_path).find(r=>r.symbolId===t.id);return n?{symbolId:n.symbolId,symbol:n.symbol,documentId:n.documentId,startLine:n.startLine,startChar:n.startChar,endLine:n.endLine,endChar:n.endChar,relativePath:n.relativePath}:{symbolId:t.id,symbol:t.symbol,documentId:t.document_id,startLine:t.start_line,startChar:t.start_char??0,endLine:t.end_line,endChar:t.end_char??0,relativePath:t.relative_path}}function Hh(e,t,n){let r=mt(e).forFile(t,{text:!0}).text,i=Kl(e,t);return i?s_(n,i,r):r?t_(n,r):n}function t_(e,t){let n=t.split(/\r?\n/),r=n_(e,n),i=r_(e,r),o=i_(i,n);return o_(e,o)}function n_(e,t){let n=e.some(i=>la(i.symbol))?f_(t):null,r=new Map;for(let i of e)r.set(i.symbolId,m_(t,n,i));return r}function r_(e,t){return e.filter(n=>la(n.symbol)).map(n=>({definition:n,startLine:t.get(n.symbolId)??n.startLine})).sort((n,r)=>n.startLine-r.startLine||n.definition.startLine-r.definition.startLine||n.definition.symbol.localeCompare(r.definition.symbol))}function i_(e,t){let n=new Map;for(let r=0;r<e.length;r+=1){let i=e[r],o=e[r+1],s=o?Math.max(i.startLine,o.startLine-1):t.length-1;n.set(i.definition.symbolId,{startLine:i.startLine,endLine:p_(t,i.definition,i.startLine,s)})}return n}function o_(e,t){return e.map(n=>{let r=t.get(n.symbolId);return r?{...n,startLine:r.startLine,endLine:r.endLine}:n})}function s_(e,t,n=null){let r=new Map;for(let i of t){let o=r.get(i.name);o?o.push(i):r.set(i.name,[i])}return e.map(i=>{if(!d_(i)||!i.leaf)return Ah(i,n);let o=r.get(i.leaf);if(!o||o.length===0)return Ah(i,n);let s=n?a_(i,o,n):null;if(s)return{...i,startLine:s.startLine,endLine:s.endLine};let a=o[0],c=Math.abs(a.startLine-i.startLine);for(let l=1;l<o.length;l+=1){let u=o[l],d=Math.abs(u.startLine-i.startLine);d<c&&(a=u,c=d)}return{...i,startLine:a.startLine,endLine:a.endLine}})}function a_(e,t,n){let r=c_(e.symbol);if(!r)return null;let i=n.split(/\r?\n/),o=new RegExp(`\\b${H(r)}\\b`);for(let s of t){let a=l_(i,s.startLine);if(a&&o.test(a))return s}return null}function c_(e){return e.match(/\/impl#\[([^\]]+)\]/)?.[1]??null}function l_(e,t){for(let n=t;n>=0;n-=1){let r=e[n]?.trim()??"";if(r){if(/^impl\b/.test(r))return u_(e,n,t);if(/^(?:struct|enum|trait|mod)\b/.test(r))return null}}return null}function u_(e,t,n){let r=[];for(let i=t;i<=n;i+=1){let o=e[i]??"";if(r.push(o),o.includes("{"))break}return r.join(" ")}function d_(e){return la(e.symbol)?!0:pe(e.symbol)==="term"&&Lt(e.symbol)===null}function Ah(e,t){if(!t||!e.leaf||pe(e.symbol)!=="term"||Lt(e.symbol)!==null)return e;let n=H(e.leaf),r=new RegExp(`\\b(?:export\\s+)?(?:const|let|var)\\s+${n}\\b`),o=t.split(/\r?\n/).findIndex(s=>r.test(s));return o>=0?{...e,startLine:o,endLine:o}:e}function m_(e,t,n){if(!la(n.symbol))return n.startLine;let r=Math.max(0,Math.min(n.startLine,e.length-1));if(!t)return r;let i=t.get(n.leaf);if(!i||i.length===0)return r;let o=null;for(let s of i){let a=Math.abs(s-n.startLine);(!o||a<o.distance)&&(o={line:s,distance:a})}return o?.line??r}function f_(e){let t=/\b(?:function|def|fn)\s+([A-Za-z_$][\w$]*)/g,n=/\b([A-Za-z_$][\w$]*)\s*[:=]\s*(?:async\s*)?(?:function\b|\()/g,r=/^\s*(?:(?:export|public|private|protected|static|readonly|async|abstract|get|set)\s+)*([A-Za-z_$][\w$]*)\s*(?:<[^(]*>)?\s*\(/,i=/\b([A-Za-z_$][\w$]*)\s*\(/g,o=new Map,s=(a,c)=>{let l=o.get(a);if(!l){o.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)};for(let a=0;a<e.length;a+=1){let c=e[a]??"";for(let u of c.matchAll(t))u[1]&&s(u[1],a);for(let u of c.matchAll(n))u[1]&&s(u[1],a);let l=c.match(r);l?.[1]&&s(l[1],a);for(let u of c.matchAll(i))u[1]&&s(u[1],a)}return o}function p_(e,t,n,r){let i=Math.max(n,Math.min(e.length-1,r)),o=Math.max(n,Math.min(i,t.endLine)),s=0,a=0,c=!1;for(let l=n;l<=i;l+=1){let u=g_(e[l]??"");for(let d of u)d==="{"?(s+=1,c=!0):d==="}"?s=Math.max(0,s-1):d==="("?a+=1:d===")"&&(a=Math.max(0,a-1));if(c&&s===0||!c&&a===0&&l>=o)return l}return o}function g_(e){let t="",n=null,r=!1;for(let i=0;i<e.length;i+=1){let o=e[i],s=e[i+1];if(!n&&o==="/"&&s==="/"){t+=" ".repeat(e.length-i);break}if(n){if(r){r=!1,t+=" ";continue}if(o==="\\"){r=!0,t+=" ";continue}o===n&&(n=null),t+=" ";continue}if(o==='"'||o==="'"||o==="`"){n=o,t+=" ";continue}t+=o}return t}function la(e){return e.includes("().")}function ua(e){let t=Re(e);if("kind"in t)return[];let n=[];for(let r=t.descriptors.length-2;r>=0;r-=1){let i=t.descriptors[r];i?.suffix==="type"&&i.name&&n.push(i.name)}return n}var h_=B("symbol-resolution",{clearGroups:[]});function $(e,t){return to(e,t).match}function to(e,t){return h_.get(e,t,()=>{let n=qh(e,t.trim()).filter(o=>!e.isIgnored(o.relative_path));if(n.length>0)return eo(e,n);let r=v_(e,t);if(r&&!e.isIgnored(r.relative_path))return eo(e,[r]);let i=y_(e,t);return i.length>0?eo(e,i):C_(e,t)})}function y_(e,t){let n=ma(t),r=ku(n);if(!r)return[];let i=`%${r.path}%`,o=r.leaf;return b_(e,i,o,n)}function b_(e,t,n,r){let i=Tn([],[...S_(e,t,n),...x_(e,t,n)]).filter(o=>!e.isIgnored(o.relative_path)).filter(o=>Xr(o,r)>1);return i.sort((o,s)=>Xr(s,r)-Xr(o,r)||o.end_line-o.start_line-(s.end_line-s.start_line)||o.start_line-s.start_line||o.symbol.localeCompare(s.symbol)),i}function S_(e,t,n){return ur(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function x_(e,t,n){return Yr(e,{where:"d.relative_path LIKE ? AND (gs.display_name = ? OR gs.symbol LIKE ?)",params:[t,n,`%/${n}.%`]})}function C_(e,t){let n=ma(t),r=P_(t),i=D_(e,r),o=F_(i,t,n).filter(a=>!e.isIgnored(a.relative_path));if(o.length>0)return eo(e,o);let s=[];for(let a of i){if(e.isIgnored(a.relative_path))continue;let c=k_(a,t,n,r);c<=0||s.push({row:a,score:c})}return s.sort((a,c)=>c.score-a.score||a.row.end_line-a.row.start_line-(c.row.end_line-c.row.start_line)||a.row.relative_path.localeCompare(c.row.relative_path)||a.row.symbol.localeCompare(c.row.symbol)),eo(e,s.map(a=>a.row))}function eo(e,t){let n=t.map(i=>ca(e,i)),r=n[0]??null;return{match:r,candidates:r?R_(n,r):[],total:n.length}}function R_(e,t){let n=new Set([`${t.symbolId}:${t.relativePath}:${t.startLine}`]),r=[];for(let i of e){let o=`${i.symbolId}:${i.relativePath}:${i.startLine}`;if(!n.has(o)&&(n.add(o),r.push({symbol:i.symbol,shortName:I(i.symbol),relativePath:i.relativePath,startLine:i.startLine}),r.length>=5))break}return r}function v_(e,t){let n=t.match(/^(.+):(\d+)-(\d+)$/);if(!n)return;let[,r,i,o]=n,s=Math.max(0,parseInt(i,10)-1),a=Math.max(s,parseInt(o,10)-1);return I_(e,r,s,a)??w_(e,r,s,a)}function I_(e,t,n,r){return ur(e,{where:"d.relative_path LIKE ? AND der.start_line <= ? AND der.end_line >= ?",params:[`%${t}%`,n,r],orderBy:"(der.end_line - der.start_line) ASC",limit:1})[0]}function w_(e,t,n,r){return Yr(e,{where:"d.relative_path LIKE ? AND c.start_line <= ? AND c.end_line >= ?",params:[`%${t}%`,n,r],orderBy:"(MAX(c.end_line) - MIN(c.start_line)) ASC",limit:1})[0]}function no(e,t){let n=qh(e,t).find(r=>!e.isIgnored(r.relative_path));return n?ca(e,n):null}function qh(e,t){let n=ur(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, der.start_line"}),r=n.length>0?[]:Yr(e,{where:"gs.symbol = ?",params:[t],orderBy:"d.relative_path, start_line"});return Tn(n,r)}function da(e,t){if("symbol"in t&&"relativePath"in t)return t;let n=E_(e,t.symbolId)[0];return n?ca(e,n):null}function E_(e,t){let n=ur(e,{where:"gs.id = ?",params:[t],orderBy:"der.start_line, der.end_line"}),r=Yr(e,{where:"gs.id = ?",params:[t],orderBy:"start_line, end_line"});return Tn(n,r)}function D_(e,t){let n=t.map(()=>"(gs.symbol LIKE ? OR d.relative_path LIKE ? OR COALESCE(gs.display_name, '') LIKE ?)"),r=t.flatMap(a=>{let c=`%${a}%`;return[c,c,c]}),i=n.join(`
|
|
247
|
+
AND `),o=ur(e,{where:i,params:r,limit:200}),s=Yr(e,{where:i,params:r,limit:200});return Tn(o,s)}function k_(e,t,n,r){let i=t.trim(),o=n,s=o.replace(/\(\)$/,""),a=t.toLowerCase(),c=n.toLowerCase(),l=c.replace(/\(\)$/,""),u=e.symbol,d=I(e.symbol),m=F(e.symbol),f=e.display_name??"",p=e.symbol.toLowerCase(),g=d.toLowerCase(),y=m.toLowerCase(),h=f.toLowerCase(),C=e.relative_path.toLowerCase(),b=/[/:.]/.test(n),S=ku(n),x=S?.leaf.toLowerCase(),v=0;return(u===i||u===o)&&(v+=1150),(d===i||d===o)&&(v+=1100),f===s&&(v+=1180),m===s&&(v+=1160),(`${m}()`===i||`${m}()`===o)&&(v+=955),(p===a||p===c)&&(v+=1e3),(g===a||g===c)&&(v+=950),(C===a||C===c)&&(v+=925),(C.endsWith(`/${c}`)||C.endsWith(`/${a}`))&&(v+=875),h===l&&(v+=850),y===l&&(v+=825),(`${y}()`===a||`${y}()`===c)&&(v+=820),(g.endsWith(`:${c}`)||g.endsWith(`:${l}`)||g.endsWith(`:${l}()`))&&(v+=800),p.includes(c)&&(v+=120),g.includes(c)&&(v+=140),C.includes(c)&&(v+=140),h.includes(c)&&(v+=110),r.every(R=>{let D=R.toLowerCase();return p.includes(D)||g.includes(D)||C.includes(D)||h.includes(D)})&&(v+=100+r.length*15),S&&C.includes(S.path.toLowerCase())&&(v+=360,x&&(y===x||`${y}()`===x||`${y}()`==`${x}()`)&&(v+=700),fe(e.symbol)&&(v+=180)),oe(e.symbol)&&y===l&&(v+=60),!b&&In(e.symbol)&&(v-=160),v-=Math.min(50,Math.max(0,e.end_line-e.start_line)),v}function ku(e){let t=e.trim().replace(/\\/g,"/"),n=t.lastIndexOf("/");if(n<=0||n===t.length-1)return null;let r=t.slice(n+1).replace(/\(\)$/,"");return!r||r.includes(".")?null:{path:t.slice(0,n),leaf:r}}function ma(e){return e.trim().replace(/\(\)$/,"").replace(/\(.*$/,"")}function P_(e){let t=ma(e),n=t.split(/[^A-Za-z0-9_]+/).map(r=>r.trim()).filter(r=>r.length>0);return n.length>0?[...new Set(n)]:[t]}function F_(e,t,n){let r=t.trim(),i=e.filter(o=>{let s=I(o.symbol),a=(o.display_name??"").trim();return o.symbol===r||s===r||s===n||a===r||a===n||`${a}()`===r||Xr(o,n)>1||o.relative_path===r});return i.length===0?[]:(i.sort((o,s)=>Xr(s,n)-Xr(o,n)||o.end_line-o.start_line-(s.end_line-s.start_line)||o.relative_path.localeCompare(s.relative_path)||o.symbol.localeCompare(s.symbol)),i)}function Xr(e,t){let n=ku(t);if(!n)return 0;let r=e.relative_path.toLowerCase(),i=F(e.symbol).toLowerCase(),o=n.path.toLowerCase(),s=n.leaf.toLowerCase();return r.includes(o)?i!==s?1:fe(e.symbol)?Lt(e.symbol)===null?5:4:Lt(e.symbol)===null?3:2:0}function z9(e,t,n=5){let r=Uh(t);if(!r)return[];let i=ur(e,{where:"1 = 1",orderBy:"d.relative_path, der.start_line",limit:5e3}),o=new Map;for(let s of i){if(e.isIgnored(s.relative_path))continue;let a=I(s.symbol),c=F(s.symbol),l=s.display_name??c,u=[a,c,l].filter(f=>f.trim().length>0),d=Math.min(...u.map(f=>T_(Uh(f),r))),m=o.get(a);(!m||d<m.distance)&&o.set(a,{shortName:a,distance:d})}return[...o.values()].sort((s,a)=>s.distance-a.distance||s.shortName.localeCompare(a.shortName)).slice(0,n).map(s=>s.shortName)}function Uh(e){return ma(e).toLowerCase().replace(/[^a-z0-9_]+/g,"")}function T_(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let n=Array.from({length:t.length+1},(r,i)=>i);for(let r=0;r<e.length;r++){let i=[r+1];for(let o=0;o<t.length;o++){let s=e[r]===t[o]?0:1;i[o+1]=Math.min(i[o]+1,n[o+1]+1,n[o]+s)}n=i}return n[t.length]}function fa(e,t,n,r={}){if(!n)return[];let i=P(e,t);return i?i.indexOf(n)===-1?[]:(an(e,t).get(n)??[]).filter(s=>!__(s,r)):[]}function __(e,t){return typeof t.excludeStartLine=="number"&&typeof t.excludeEndLine=="number"&&e>=t.excludeStartLine&&e<=t.excludeEndLine}var L_=B("file-identifiers",{clearGroups:["whole-project","source-file"]});function Gh(e,t){let n=z(e,t);return n?n.fileIdentifiers:L_.get(e,t,()=>new Set(an(e,t).keys()))}var M_=B("file-ident-lines",{clearGroups:["whole-project","source-file"]});function an(e,t){let n=z(e,t);return n?n.identifierLineMap:M_.get(e,t,()=>N_(e,t))}var A_=B("file-idents-by-line",{clearGroups:["whole-project","source-file"]});function Vh(e,t){let n=z(e,t);return n?n.identifiersByLine:A_.get(e,t,()=>{let r=an(e,t),i=0;for(let s of r.values()){let a=s[s.length-1];a!==void 0&&a>i&&(i=a)}let o=new Array(i+1);for(let s=0;s<=i;s+=1)o[s]=new Set;for(let[s,a]of r)for(let c of a)o[c].add(s);return o})}function N_(e,t){let n=new Map,r=(a,c)=>{let l=n.get(a);if(!l){n.set(a,[c]);return}l[l.length-1]!==c&&l.push(c)},i=P(e,t);if(!i)return n;let o=ct(i).split(/\r?\n/),s=/\b([A-Za-z_$][\w$]*)\b/g;for(let a=0;a<o.length;a+=1){let c=o[a]??"";for(let l of c.matchAll(s))l[1]&&r(l[1],a)}return n}function Wh(e,t){return pa(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT
|
|
248
|
+
m.symbol_id,
|
|
249
|
+
d.relative_path,
|
|
250
|
+
COUNT(*) AS ref_count
|
|
251
|
+
FROM mentions m
|
|
252
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
253
|
+
JOIN documents d ON c.document_id = d.id
|
|
254
|
+
WHERE m.role != 1
|
|
255
|
+
${r}
|
|
256
|
+
${e.pathExclusionsFor("d")}
|
|
257
|
+
GROUP BY m.symbol_id, d.relative_path`,...n??[])})}function zh(e,t){return pa(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id, d.relative_path
|
|
258
|
+
FROM mentions m
|
|
259
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
260
|
+
JOIN documents d ON c.document_id = d.id
|
|
261
|
+
WHERE m.role != 1
|
|
262
|
+
${r}
|
|
263
|
+
${e.pathExclusionsFor("d")}`,...n??[])}).filter(n=>n.symbol_id!==null)}function Kh(e,t){return pa(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id
|
|
264
|
+
FROM mentions m
|
|
265
|
+
WHERE m.role != 1
|
|
266
|
+
${r}`,...n??[])}).filter(n=>n.symbol_id!==null)}function Qr(e,t){return pa(e,t,n=>{let r=n?`AND m.symbol_id IN (${n.map(()=>"?").join(",")})`:"";return e.all(`SELECT DISTINCT m.symbol_id, d.relative_path, c.document_id,
|
|
267
|
+
c.start_line AS chunk_start, c.end_line AS chunk_end
|
|
268
|
+
FROM mentions m
|
|
269
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
270
|
+
JOIN documents d ON c.document_id = d.id
|
|
271
|
+
WHERE m.role != 1
|
|
272
|
+
${r}
|
|
273
|
+
${e.pathExclusionsFor("d")}
|
|
274
|
+
ORDER BY d.relative_path, c.start_line`,...n??[])})}function pa(e,t,n){if(!t)return n();if(t.length===0)return[];let r=[];for(let i=0;i<t.length;i+=750)r.push(...n(t.slice(i,i+750)));return r}function ga(e,t){let n=Jh(e);return n?t.filter(r=>Jh(r.file)===n):t}function ha(e,t,n,r){let i=n.find(o=>o.file===t);if(i)return i;if(r){let o=new Set(te(e,t).map(s=>s.sourcePath).filter(s=>!!s));for(let s of n)for(let a of o)if(Qe(a,s.file))return s;return null}return n.length===1?n[0]:null}function Jh(e){let t=N(e);return t?t==="typescript"||t==="tsx"||t==="javascript"?"javascript-family":t:null}var O_=Z("global-leaf-index",{clearGroups:["whole-project"]});function cn(e){return O_.get(e,()=>{let t=e.all(`SELECT gs.id, gs.symbol,
|
|
275
|
+
COALESCE(der_doc.relative_path, mention_doc.relative_path) AS relative_path
|
|
276
|
+
FROM global_symbols gs
|
|
277
|
+
LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
278
|
+
LEFT JOIN documents der_doc ON der_doc.id = der.document_id
|
|
279
|
+
LEFT JOIN (
|
|
280
|
+
SELECT m.symbol_id, MIN(d.relative_path) AS relative_path
|
|
281
|
+
FROM mentions m
|
|
282
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
283
|
+
JOIN documents d ON c.document_id = d.id
|
|
284
|
+
WHERE m.role = 1
|
|
285
|
+
GROUP BY m.symbol_id
|
|
286
|
+
) mention_doc ON mention_doc.symbol_id = gs.id
|
|
287
|
+
WHERE 1 = 1
|
|
288
|
+
${e.symbolNoiseFor("gs")}`),n=new Map;for(let r of t){if(!r.relative_path||e.isIgnored(r.relative_path))continue;let i=F(r.symbol);if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.some(s=>s.symbolId===r.id)||o.push({symbol:r.symbol,symbolId:r.id,file:r.relative_path})}return n})}var Yh=/[A-Za-z_$][A-Za-z0-9_$]*/g,Xh=/^[A-Za-z_$][A-Za-z0-9_$]*$/,j_=512;function ro(e){let t=[],n=!1;for(let r of e)r&&(n=!0,Xh.test(r)||t.push(r));return{candidateNames:e,hasUsableCandidate:n,nonIdentifierNames:t}}function ya(e,t){let n=B_(t)?t:ro(t);if(n.candidateNames.size===0||!n.hasUsableCandidate)return!0;if(n.candidateNames.size<=j_){for(let i of n.candidateNames)if(i){if(Xh.test(i)){if($_(i).test(e))return!0;continue}if(e.includes(i))return!0}return!1}Yh.lastIndex=0;let r;for(;(r=Yh.exec(e))!==null;)if(n.candidateNames.has(r[0]))return!0;for(let i of n.nonIdentifierNames)if(e.includes(i))return!0;return!1}function B_(e){return"candidateNames"in e}function $_(e){return new RegExp(`(?<![A-Za-z_$0-9])${H(e)}(?![A-Za-z_$0-9])`)}var H_=B("source-import-paths-by-local-name",{clearGroups:["whole-project","source-file"]});function ba(e,t){let n=En(t);return H_.get(e,n,()=>U_(e,n))}function U_(e,t){let n=new Map;for(let r of te(e,t)){if(!r.sourcePath)continue;let i=r.localName??r.importedName;if(i&&Qh(n,i,r.sourcePath),r.kind==="namespace")for(let o of r.usedMembers)Qh(n,o,r.sourcePath)}return n}function Qh(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function Zr(e,t,n){let r=cn(e).get(n);if(!r||r.length===0)return[];if(r.length===1)return[io(r[0])];let i=r.filter(c=>c.file===t);if(i.length>0)return i.map(io);let o=ba(e,t),s=o.get(n);if(s)for(let c of s){let l=r.filter(u=>Qe(c,u.file));if(l.length>0)return l.map(io)}let a=new Set;for(let c of o.values())for(let l of c)a.add(l);for(let c of a){let l=r.filter(u=>Qe(c,u.file));if(l.length>0&&l.length===r.length)return l.map(io)}return[]}function Zh(e,t,n){let r=Zr(e,t,n);if(r.length>0)return r;let i=cn(e).get(n);return!i||i.length===0?[]:i.map(io)}function ey(e,t,n={}){let r=da(e,t);if(!r)return[];let i=F(r.symbol);if(!i)return[];if(n.semantic!==!1&&n.semanticEvidence){let s=n.semanticEvidence.references(e,{...r,leaf:i,parentTypeName:null,isFunctionLike:!1,isTypeLike:!1,kind:null,documentation:null,enclosingSymbol:null});if(s.length>0){let a=new Map;for(let c of s){let l=a.get(c.file)??[];l.push(c.line),a.set(c.file,l)}return Sa(e,a)}}let o=new Map;for(let s of ze(e)){let a=P(e,s);if(!a||a.indexOf(i)===-1||s!==r.relativePath&&!Zr(e,s,i).some(u=>u.symbolId===r.symbolId))continue;let c=fa(e,s,i,s===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{});c.length>0&&o.set(s,c)}return Sa(e,o)}function ty(e,t,n={}){let r=new Map;for(let c of t){if(!c.leaf)continue;let l=r.get(c.leaf)??[];l.push(c),r.set(c.leaf,l)}if(r.size===0)return new Map;let i=new Set(t.map(c=>c.symbolId)),o=new Set(r.keys()),s=ro(o),a=new Map;for(let c of ze(e)){if(n.skipPath?.(c)||!ya(P(e,c),s))continue;let l=Gh(e,c);if(l.size!==0){for(let u of l)if(r.has(u))for(let d of Zr(e,c,u)){if(!i.has(d.symbolId)||c===d.relativePath)continue;let m=a.get(d.symbolId);m||(m=new Set,a.set(d.symbolId,m)),m.add(c)}}}return a}function io(e){return{symbolId:e.symbolId,symbol:e.symbol,relativePath:e.file}}function Sa(e,t){let n=[],r=new Set;for(let[i,o]of t){let s=Q(e,i);for(let a of o){let c=At(s,a),l=`${i}|${a}|${c?.symbol??""}`;r.has(l)||(r.add(l),n.push({file:i,line:a,enclosingSymbol:c?.symbol??null}))}}return n}function oo(e,t){let n=K_(e,t);return n?Sa(e,G_(e,n.match,n.identifier)):[]}function Nt(e,t,n={}){return q_(e,t,n).map(r=>({file:r.file,line:r.line,enclosingSymbol:r.enclosingSymbol}))}function q_(e,t,n={}){let r=ey(e,t,{semantic:n.semantic,semanticEvidence:n.semanticEvidence}),i=r.length>0?ny(r,"source-attribution"):ny(oo(e,t),"scip-reference-chunk");return n.includeIgnored===!0?i:i.filter(o=>!e.isIgnored(o.file))}function ny(e,t){return e.map(n=>({...n,provenance:t}))}function G_(e,t,n){let r=new Map;for(let[i,o]of V_(e,t.symbolId))r.set(i,W_(e,i,o,t,n));return r}function V_(e,t){let n=new Map;for(let r of Qr(e,[t])){if(e.isIgnored(r.relative_path))continue;let i=n.get(r.relative_path);i||(i=[],n.set(r.relative_path,i)),i.push({start_line:r.chunk_start,end_line:r.chunk_end})}return n}function W_(e,t,n,r,i){let o=t===r.relativePath?{excludeStartLine:r.startLine,excludeEndLine:r.endLine}:{},s=i?fa(e,t,i,o):[];return n.flatMap(a=>z_(s,a))}function z_(e,t){let n=e.filter(r=>r>=t.start_line&&r<=t.end_line);return n.length>0?n:[t.start_line]}function K_(e,t){let n=da(e,t);return n?{match:n,identifier:F(n.symbol)||null}:null}var ry=nr({kind:"file-dependency-graph",invalidation:X("file-dependency-graph"),serialize:e=>JSON.stringify(e),deserialize:tL}),J_=B("file-dep-graph",{clearGroups:["whole-project"]});function ae(e,t,n={}){let r=n.scipEdges??"all-references",i=n.sourceEdges??"imports-only",o=Q_(t,r,i);return J_.get(e,o,()=>{let s=new Set(M(e,{includeIgnored:!1})),a=Ne(e),c=0,l=0,u=null,d=!1,m=0,f=0;return E("file-dep-graph.product",()=>{if(a){let h=ry.read(e,o,a);if(h){d=!0;let C=eL(h);return c=h.sourceFileCount,l=h.sourceEdgeCount,m=h.scipEdgeCount,f=C.size,u=h.sourceDependencyFingerprint,C}}let p=E("file-dep-graph.source-imports",()=>{let h=Y_(e,s,t,i);return c=h.files.length,l=h.edges.length,u=h.fingerprint,h},()=>({scope:t??null,sourceEdges:i,files:c,edges:l})),g=new Map,y=(h,C)=>oL(e,g,s,h,C);E("file-dep-graph.scip-edges",()=>{for(let h of iL(e,t,r))m+=1,y(h.from_file,h.to_file)},()=>({scope:t??null,edges:m}));for(let h of p.edges)y(h.fromFile,h.toFile);return f=g.size,a&&ry.write(e,o,a,{sourceDependencyFingerprint:p.fingerprint,sourceFileCount:p.files.length,sourceEdgeCount:p.edges.length,scipEdgeCount:m,graph:Z_(g)}),g},()=>({scope:t??null,available:a!==null,hit:d,files:c,sourceEdges:l,sourceEdgeMode:i,scipEdges:m,graphFiles:f,sourceDependencyFingerprint:u}))})}function Y_(e,t,n,r){let i=[],o=[];for(let s of t)if(!(n&&!s.includes(n))){i.push(s);for(let a of te(e,s))a.sourcePath&&o.push({fromFile:s,toFile:a.sourcePath});if(r==="imports-and-reexports")for(let a of rn(e,s))a.sourcePath&&o.push({fromFile:s,toFile:a.sourcePath})}return{files:i,edges:o,fingerprint:X_(i,o)}}function X_(e,t){let n=t.map(r=>`${r.fromFile}\0${r.toFile}`).sort();return Ce(JSON.stringify({files:e,edges:n}))}function Q_(e,t,n){return`edge-mode-v3:${t}:${n}:${e??"<all>"}`}function Z_(e){return[...e].map(([t,n])=>[t,[...n]])}function eL(e){return new Map(e.graph.map(([t,n])=>[t,new Set(n)]))}function tL(e){let t=JSON.parse(e);return nL(t)?t:null}function nL(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.sourceDependencyFingerprint=="string"&&typeof t.sourceFileCount=="number"&&typeof t.sourceEdgeCount=="number"&&typeof t.scipEdgeCount=="number"&&Array.isArray(t.graph)&&t.graph.every(rL)}function rL(e){return Array.isArray(e)&&e.length===2&&typeof e[0]=="string"&&Array.isArray(e[1])&&e[1].every(t=>typeof t=="string")}function iL(e,t,n){let r=t?"AND d1.relative_path LIKE ?":"",i=t?[`%${t}%`]:[],o=n==="imports-only"?"AND m.role = 2":"AND m.role != 1";return e.all(`SELECT DISTINCT
|
|
289
|
+
d1.relative_path AS from_file,
|
|
290
|
+
d2.relative_path AS to_file
|
|
291
|
+
FROM mentions m
|
|
292
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
293
|
+
JOIN documents d1 ON c.document_id = d1.id
|
|
294
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
295
|
+
JOIN (
|
|
296
|
+
SELECT m2.symbol_id, c2.document_id
|
|
297
|
+
FROM mentions m2
|
|
298
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
299
|
+
WHERE m2.role = 1
|
|
300
|
+
GROUP BY m2.symbol_id
|
|
301
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
302
|
+
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
303
|
+
WHERE d1.id != d2.id
|
|
304
|
+
${o}
|
|
305
|
+
${e.pathExclusionsFor("d1","d2")}
|
|
306
|
+
${r}`,...i)}function oL(e,t,n,r,i){if(r===i||e.isIgnored(r)||e.isIgnored(i)||!n.has(i))return;let o=t.get(r);o||(o=new Set,t.set(r,o)),o.add(i)}function xa(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 iy(e){let t=new Map,n=aL(e),r=new Map;return i=>{let o=sL(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=cL(Q(e,i.file)),t.set(i.file,a));let c=lL(a,i);return r.set(o,c),c}}function sL(e){return`${e.file}\0${e.symbol}\0${e.line}`}function aL(e){return new Set(e.all("SELECT relative_path FROM documents").map(t=>t.relative_path))}function cL(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 lL(e,t){if(e.definitions.length===0)return t.symbol;let n=mL(t.symbol),r=uL(e.byLeaf,n),i=dL(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 uL(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 dL(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 mL(e){let t=new Set([e]),r=e.split(/::|\.|#/).filter(Boolean).at(-1);return r&&t.add(r),t}function oy(e,t){let r=te(e,t).map(i=>pL(t,i));return{usage:r,positions:gL(e,t,r)}}function sy(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?fL(r.usage,i.sourcePaths):r.usage}}}function fL(e,t){return e.map((n,r)=>{let i=t.get(String(r));return i?{...n,sourcePath:i}:n})}function pL(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 gL(e,t,n){let r=Y(e,t);if(!r)return[];let i=hL(r.rootNode),o=new Map;for(let a of i){let c=o.get(Fu(a.importedName,a.localName));c?c.push(a.position):o.set(Fu(a.importedName,a.localName),[a.position])}let s=[];return n.forEach((a,c)=>{let l=o.get(Fu(a.importedName,a.localName??a.importedName))?.shift();l&&s.push({...l,id:String(c),file:t})}),s}function hL(e){let t=[];for(let n of e.descendantsOfType("use_declaration")){let r=n.namedChildren.find(i=>i.type!=="visibility_modifier");r&&t.push(...Ca(r,""))}return t.filter(n=>n.importedName!=="*")}function Ca(e,t){switch(e.type){case"identifier":case"super":case"self":case"crate":return[{importedName:e.text,localName:e.text,position:Pu(e,e.text)}];case"scoped_identifier":{let n=e.text.split("::").pop()??e.text;return[{importedName:n,localName:n,position:Pu(e,n)}]}case"scoped_use_list":{let n=e.namedChild(0),r=e.namedChild(1);if(!n||!r)return[];let i=Jr(t,n.text);return r.namedChildren.flatMap(o=>Ca(o,i))}case"use_list":return e.namedChildren.flatMap(n=>Ca(n,t));case"use_as_clause":{let n=e.namedChild(0),r=e.namedChild(1);return!n||!r?[]:Ca(n,t).map(i=>({...i,localName:r.text}))}case"use_wildcard":{let n=e.namedChild(0),r="*";return[{importedName:r,localName:r,position:Pu(n??e,r)}]}default:return[]}}function Pu(e,t){let n=Math.max(0,e.text.lastIndexOf(t));return{id:"",file:"",line:e.startPosition.row,column:e.startPosition.column+n+yL(t)}}function yL(e){return Math.max(0,Math.min(e.length-1,1))}function Fu(e,t){return`${e}\0${t}`}import{spawnSync as Zu}from"child_process";import{existsSync as ed}from"fs";import{fileURLToPath as RA}from"url";function _n(e){if(!e)return;let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}import{execFileSync as dy}from"child_process";import{existsSync as _u,readFileSync as vL}from"fs";import{createRequire as IL}from"module";import{platform as my}from"os";import{dirname as uy,join as Ra}from"path";import{execFileSync as ay,spawnSync as bL}from"child_process";import{platform as SL}from"os";var cy=SL()==="win32";function K7(e,t=bL){try{return t(e,["--version"],{stdio:"ignore",timeout:1e4}).status===0}catch{return!1}}function Tu(e){let t=cy?"where":"which";try{return ay(t,[e],{stdio:"pipe",timeout:1e4,killSignal:"SIGKILL"}),!0}catch{return!1}}var xL=/\.(?:c|m)?js$/i,CL=/\.(?:exe|com)$/i;function J7(e,t){return xL.test(e)?{binary:process.execPath,args:[e,...t]}:{binary:e,args:[...t]}}function RL(e,t){return ay(e,t,{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4,killSignal:"SIGKILL"})}function ly(e,t={}){let n=t.isWindows??cy,r=t.lookup??RL,i;try{i=r(n?"where":"which",[e])}catch{return null}let o=i.split(/\r?\n/).map(s=>s.trim()).filter(Boolean);return n?o.find(s=>CL.test(s))??null:o[0]??null}var wL=IL(import.meta.url),fy={language:"rust",indexerBinary:"rust-analyzer",installUrl:"https://github.com/rust-lang/rust-analyzer"};function Lu(e){return[e.indexerBinary,...e.binaryAliases??[]]}function EL(e){let t=Lu(e);return t.length===1?t[0]:t.join(" or ")}function Mu(e){for(let t of Lu(e))if(my()==="win32"){let n=ly(t);if(n)return n}else if(Tu(t))return t;return kL(e)}function ree(e){return Mu(e)!==null||DL(e)}function DL(e){return py(e)!==null}function kL(e){let t=py(e);if(!t)return null;let r=JSON.parse(vL(t,"utf8")).bin;if(!r)return null;if(typeof r=="string")return Ra(uy(t),r);for(let i of Lu(e)){let o=r[i];if(o)return Ra(uy(t),o)}return null}function py(e){if(!e.bundledNpmPackage)return null;try{return wL.resolve(`${e.bundledNpmPackage}/package.json`)}catch{return null}}function PL(e,t){for(let n of e.projectLocalBinaries??[]){let r=Ra(t,n);if(_u(r))return r}return null}function FL(e,t){return PL(e,t)??Mu(e)}function iee(e,t=process.env,n=e.indexerBinary){if(e.indexerBinary!=="scip-dotnet"||Au(n,t))return t;let r=hy(n,t);return r?{...t,DOTNET_ROOT:r}:t}function gy(e,t){let n=EL(e),r=t?FL(e,t):Mu(e);if(!r)return{language:e.language,binaryLabel:n,installed:!1,runnable:!1,resolvedBinary:null,installUrl:e.installUrl};if(e.indexerBinary!=="scip-dotnet")return{language:e.language,binaryLabel:n,installed:!0,runnable:!0,resolvedBinary:r};let i=TL(r);return{language:e.language,binaryLabel:n,installed:!0,runnable:i.runnable,resolvedBinary:r,installUrl:e.installUrl,note:i.note}}function TL(e){if(Au(e,process.env))return{runnable:!0};let t=hy(e,process.env);if(t)return{runnable:!0,note:`using .NET 9 runtime from ${t}`};let n=yy(process.env);return{runnable:!1,note:n.length>0?`.NET 9 runtime still unavailable after checking ${n.join(", ")}`:"binary is present, but scip-dotnet still needs a .NET 9 runtime"}}function hy(e,t){for(let n of yy(t))if(Au(e,{...t,DOTNET_ROOT:n}))return n;return null}function yy(e){let t=[],n=e.DOTNET_ROOT;if(n&&_u(n)&&t.push(n),my()==="darwin"&&Tu("brew"))try{let r=dy("brew",["--prefix","dotnet@9"],{stdio:"pipe",env:e,timeout:1e4,killSignal:"SIGKILL"}).toString().trim(),i=Ra(r,"libexec");_u(i)&&!t.includes(i)&&t.push(i)}catch{}return t}function Au(e,t){try{return dy(e,["--version"],{stdio:"pipe",env:t,timeout:1e4,killSignal:"SIGKILL"}),!0}catch{return!1}}function va(e){let t=gy(fy,e),n=t.runnable;return{available:n,dependencyAvailable:n,resolvedBinary:t.resolvedBinary??void 0,reason:n?"rust-analyzer semantic reference queries are enabled.":"rust-analyzer is not runnable; Rust semantic checks will use SCIP/source evidence only."}}import{existsSync as aA,mkdtempSync as tb,readFileSync as nb,rmSync as zu}from"fs";import{tmpdir as Yu}from"os";import{join as Ku}from"path";import{fileURLToPath as bo,pathToFileURL as cA}from"url";import{SHARE_ENV as lA,Worker as uA}from"worker_threads";function Ln(e){try{return process.kill(e,0),!0}catch(t){return typeof t=="object"&&t!==null&&"code"in t&&t.code==="EPERM"}}import{execFileSync as LL}from"child_process";import{readFileSync as ML}from"fs";import{platform as AL}from"os";var _L=new Set(["aix","android","darwin","freebsd","haiku","linux","openbsd","sunos","win32","cygwin","netbsd"]);function ln(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return t.version!==1||typeof t.pid!="number"||!Number.isSafeInteger(t.pid)||t.pid<=0||typeof t.platform!="string"||!_L.has(t.platform)||typeof t.startToken!="string"||t.startToken.trim()===""?null:{version:1,pid:t.pid,platform:t.platform,startToken:t.startToken}}function ft(e,t){return e.version===t.version&&e.pid===t.pid&&e.platform===t.platform&&e.startToken===t.startToken}var NL=1e3,OL=16*1024;function Rt(e,t=$L){if(!Number.isSafeInteger(e)||e<=0)return null;try{let n=jL(e,t);return n?{version:1,pid:e,platform:t.platform,startToken:n}:null}catch{return null}}function jL(e,t){if(t.platform==="linux"||t.platform==="android")return BL(t.readFile(`/proc/${e}/stat`));if(t.platform==="win32"){let n=`([DateTimeOffset](Get-Process -Id ${e} -ErrorAction Stop).StartTime).ToUnixTimeMilliseconds()`;return by(t.run("powershell.exe",["-NoProfile","-NonInteractive","-Command",n]))}return t.platform==="darwin"||t.platform==="freebsd"||t.platform==="openbsd"||t.platform==="netbsd"?by(t.run("ps",["-p",String(e),"-o","lstart="])):null}function BL(e){let t=e.lastIndexOf(")");if(t<0)return null;let r=e.slice(t+1).trim().split(/\s+/)[19];return r&&/^\d+$/.test(r)?r:null}function by(e){let t=e.trim();return t===""?null:t}var $L={platform:AL(),readFile(e){return ML(e,"utf8")},run(e,t){return LL(e,[...t],{encoding:"utf8",timeout:NL,maxBuffer:OL,env:{...process.env,LC_ALL:"C",LANG:"C"},stdio:["ignore","pipe","ignore"]})}};function Mn(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 dr(e,t,n){let r=_n(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 zM}from"child_process";import{createHash as KM,randomUUID as JM}from"crypto";import{existsSync as Jy,readFileSync as Fa,realpathSync as YM,rmSync as XM}from"fs";import{tmpdir as QM}from"os";import{resolve as si}from"path";function we(){return performance.now()}function un(e){return Array.isArray(e)?`[${e.map(un).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${un(n)}`).join(",")}}`:JSON.stringify(e)}import{createHash as YL,randomUUID as wy}from"crypto";import{existsSync as ri,lstatSync as mo,mkdirSync as XL,readFileSync as uo,readdirSync as ni,renameSync as Ey,rmSync as An}from"fs";import{basename as Ou,dirname as QL,join as Se}from"path";import{randomUUID as HL}from"crypto";import{closeSync as UL,fsyncSync as qL,linkSync as GL,mkdirSync as VL,openSync as WL,renameSync as zL,unlinkSync as KL,writeSync as JL}from"fs";import{dirname as Sy}from"path";function so(e,t,n,r){let i=0;for(;i<t.length;){let o=n.writeFile(e,t,i,t.length-i);if(!Number.isSafeInteger(o)||o<=0||o>t.length-i)throw new Error(`${r} write did not make valid forward progress`);i+=o}}function ei(e,t){if(t!=="win32")return!1;let n=e.code;return n==="EACCES"||n==="EBADF"||n==="EINVAL"||n==="EISDIR"||n==="EPERM"}var Nu=Object.freeze({platform:process.platform,randomToken:()=>HL(),makeDirectory:e=>VL(e,{recursive:!0}),openFile:(e,t,n)=>WL(e,t,n),writeFile:(e,t,n,r)=>JL(e,t,n,r),syncFile:e=>qL(e),closeFile:e=>UL(e),renameFile:(e,t)=>zL(e,t),linkFile:(e,t)=>GL(e,t),removeFile:e=>KL(e)});function ao(e,t,n={}){let r=n.durability??"visibility",i=n.runtime??Nu,o=Sy(e);i.makeDirectory(o);let s=`${e}.tmp-${i.randomToken()}`,a=typeof t=="string"?Buffer.from(t):t,c,l=!1;try{return c=i.openFile(s,"wx",n.mode??384),l=!0,so(c,a,i,"atomic file"),r==="durable"&&i.syncFile(c),i.closeFile(c),c=void 0,i.renameFile(s,e),l=!1,{durability:r,directorySync:r==="durable"?vt(o,i):"not-requested"}}finally{if(c!==void 0)try{i.closeFile(c)}catch{}if(l)try{i.removeFile(s)}catch{}}}function co(e,t,n={}){let r=n.durability??"visibility",i=n.runtime??Nu;if(!i.linkFile)throw new Error("Exclusive atomic file publication requires hard-link support.");let o=Sy(e);i.makeDirectory(o);let s=`${e}.tmp-${i.randomToken()}`,a=typeof t=="string"?Buffer.from(t):t,c,l=!1;try{return c=i.openFile(s,"wx",n.mode??384),l=!0,so(c,a,i,"exclusive atomic file"),r==="durable"&&i.syncFile(c),i.closeFile(c),c=void 0,i.linkFile(s,e),i.removeFile(s),l=!1,{durability:r,directorySync:r==="durable"?vt(o,i):"not-requested"}}finally{if(c!==void 0)try{i.closeFile(c)}catch{}if(l)try{i.removeFile(s)}catch{}}}function vt(e,t=Nu){let n;try{n=t.openFile(e,"r")}catch(r){if(ei(r,t.platform))return"unsupported";throw r}try{return t.syncFile(n),"synced"}catch(r){if(ei(r,t.platform))return"unsupported";throw r}finally{t.closeFile(n)}}function Ia(e,t,n={}){ao(e,xy(t,n),{durability:"visibility",runtime:n.runtime})}function rt(e,t,n={}){return ao(e,xy(t,n),{durability:"durable",runtime:n.runtime})}function xy(e,t){let n=JSON.stringify(e,null,t.spacing);return t.trailingNewline?`${n}
|
|
307
|
+
`:n}var Nn=1,ZL=Object.freeze({maxItems:1024,maxBytes:512*1024*1024,maxItemBytes:64*1024*1024,maxBatch:16,claimLeaseMs:5*6e4,responseRetentionMs:10*6e4,deadLetterRetentionMs:1440*6e4,temporaryRetentionMs:6e4,cleanupBatch:64}),ti=class extends Error{constructor(n,r,i,o){let s=n==="item-too-large"?`request is ${o} bytes; per-item limit is ${i.maxItemBytes}`:n==="item-capacity"?`mailbox has ${r.totalItems} retained items; limit is ${i.maxItems}`:n==="byte-capacity"?`mailbox retains ${r.totalBytes} bytes and the request adds ${o}; limit is ${i.maxBytes}`:"another writer held the admission coordinator through the bounded wait";super(`Mailbox backpressure: ${s}. Retry after the service drains or expires retained work.`);this.code=n;this.status=r;this.limits=i;this.attemptedBytes=o;this.name="MailboxBackpressureError"}code;status;limits;attemptedBytes},eM=".owner.json",tM={isProcessAlive:()=>!0,readProcessIdentity:()=>null};function wa(e){return{rootDir:e,pendingDir:Se(e,"pending"),inflightDir:Se(e,"inflight"),responseDir:Se(e,"responses"),deadLetterDir:Se(e,"dead-letter"),legacyRequestDir:Se(e,"requests")}}function nM(e={}){let t={...ZL,...e};for(let[n,r]of Object.entries(t))if(!Number.isFinite(r)||r<=0||!Number.isInteger(r))throw new Error(`Mailbox limit ${n} must be a positive integer.`);return t}function Dy(e){for(let t of[e.pendingDir,e.inflightDir,e.responseDir,e.deadLetterDir,e.legacyRequestDir])XL(t,{recursive:!0})}function ii(e,t){return YL("sha256").update(un({namespace:e,payload:t})).digest("hex")}function mr(e){if(!/^[a-f0-9]{64}$/.test(e))throw new Error("Mailbox operation keys must be lowercase SHA-256 identities.");return`op-${e}`}function Ea(e,t,n={}){let r=nM(n.limits),i=n.nowMs??Date.now();return Dy(e),uM(t),iM(e,r,n.admissionLockTimeoutMs??2e3,n.monotonicNow??we,()=>{rM(e,i,r);let o=Se(e.pendingDir,`${t.id}.json`),s=Se(e.responseDir,`${t.id}.json`),a=Cy(e,t.id);if(a){let d=Ry(a,t.operationKey,t.id);return{disposition:"duplicate",requestId:t.id,responsePath:s,authoritativeDeadlineAtMs:d.deadlineAtMs??t.deadlineAtMs}}let c=`${JSON.stringify(t)}
|
|
308
|
+
`,l=Buffer.byteLength(c),u=ky(e);if(l>r.maxItemBytes)throw new ti("item-too-large",u,r,l);if(u.totalItems+1>r.maxItems)throw new ti("item-capacity",u,r,l);if(u.totalBytes+l>r.maxBytes)throw new ti("byte-capacity",u,r,l);n.onBeforePublish?.();try{return co(o,c,{durability:"durable"}),{disposition:"accepted",requestId:t.id,responsePath:s,authoritativeDeadlineAtMs:t.deadlineAtMs}}catch(d){if(d.code!=="EEXIST")throw d;let m=Cy(e,t.id);if(!m)throw d;let f=Ry(m,t.operationKey,t.id);return{disposition:"duplicate",requestId:t.id,responsePath:s,authoritativeDeadlineAtMs:f.deadlineAtMs??t.deadlineAtMs}}})}function rM(e,t,n,r=tM){let i={reclaimed:0,completedClaimsRemoved:0,responsesRemoved:0,deadLettersRemoved:0,temporaryFilesRemoved:0},o=n.cleanupBatch;for(let s of Bu(e.inflightDir)){if(o<=0)break;let a=Se(e.responseDir,`${s.requestId}.json`);if(ri(a)){An(s.path,{force:!0}),i.completedClaimsRemoved++,o--;continue}if(s.claimExpiresAtMs>t||cM(e,s.ownerId,r)!=="dead")continue;let c=Se(e.pendingDir,s.originalFile);try{Ey(s.path,c),i.reclaimed++}catch(l){if(l.code!=="EEXIST")throw l;An(s.path,{force:!0})}vt(QL(s.path)),vt(e.pendingDir),o--}o=vy(e.responseDir,o,(s,a)=>dM(s)??a+n.responseRetentionMs,t,()=>{i.responsesRemoved++}),o=vy(e.deadLetterDir,o,(s,a)=>a+n.deadLetterRetentionMs,t,()=>{i.deadLettersRemoved++});for(let s of[e.pendingDir,e.inflightDir,e.responseDir,e.deadLetterDir,e.legacyRequestDir]){if(o<=0)break;for(let a of Py(s)){if(o<=0)break;Ou(a).includes(".tmp-")&&(mo(a).mtimeMs+n.temporaryRetentionMs>t||(An(a,{force:!0}),i.temporaryFilesRemoved++,o--))}}return mM(e.inflightDir),i}function ky(e){Dy(e);let t=[...lo(e.pendingDir).map(c=>({path:c,pending:!0})),...lo(e.legacyRequestDir).map(c=>({path:c,pending:!0}))],n=Bu(e.inflightDir).map(c=>({path:c.path,pending:!1})),r=lo(e.responseDir).map(c=>({path:c,pending:!1})),i=lo(e.deadLetterDir).map(c=>({path:c,pending:!1})),o=[...t,...n,...r,...i],s=0,a;for(let c of t){let l=$u(c.path);if(!l){s++;continue}let u=l.enqueuedAtMs??mo(c.path).mtimeMs;a=a===void 0?u:Math.min(a,u)}return{pending:t.length,inflight:n.length,responses:r.length,deadLetters:i.length,invalid:s,totalItems:o.length,totalBytes:o.reduce((c,l)=>c+fM(l.path),0),...a===void 0?{}:{oldestPendingAt:new Date(a).toISOString()}}}function iM(e,t,n,r,i){let o=Se(e.rootDir,".admission.lock"),s=`${process.pid}-${wy()}`,a=r()+Math.max(0,n);for(;!oM(e.rootDir,o,s);){if(sM(o),r()>=a)throw new ti("admission-busy",ky(e),t,0);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,5)}try{return i()}finally{try{ju(o).ownerToken===s&&(An(o,{recursive:!0,force:!0}),vt(e.rootDir))}catch{}}}function oM(e,t,n){let r=`${JSON.stringify({ownerToken:n,pid:process.pid,acquiredAtMs:Date.now()})}
|
|
309
|
+
`;try{return co(t,r,{durability:"durable"}),!0}catch(i){if(i.code==="EEXIST")return!1;try{ju(t).ownerToken===n&&(An(t,{force:!0}),vt(e))}catch{}throw i}}function sM(e){let t=null;try{let r=ju(e);typeof r.ownerToken=="string"&&Number.isSafeInteger(r.pid)&&Number(r.pid)>0&&(t=Number(r.pid))}catch{}if(t===null||aM(t))return;let n=`${e}.stale-${wy()}`;try{Ey(e,n)}catch(r){let i=r.code;if(i==="ENOENT"||i==="EEXIST")return;throw r}An(n,{recursive:!0,force:!0})}function ju(e){try{return JSON.parse(uo(e,"utf8"))}catch(t){if(t.code!=="EISDIR")throw t;return JSON.parse(uo(Se(e,"owner.json"),"utf8"))}}function aM(e){try{return process.kill(e,0),!0}catch(t){let n=t.code;return n==="EPERM"||n!=="ESRCH"}}function cM(e,t,n){let r=lM(Se(e.inflightDir,Fy(t),eM));if(!r)return"unknown";if(!n.isProcessAlive(r.pid))return"dead";if(!r.processIdentity)return"live";let i=n.readProcessIdentity(r.pid);return i?ft(r.processIdentity,i)?"live":"dead":"unknown"}function lM(e){try{let t=JSON.parse(uo(e,"utf8"));if(t.version!==1||typeof t.ownerId!="string"||!t.ownerId||typeof t.pid!="number"||!Number.isSafeInteger(t.pid)||t.pid<=0)return null;let n=t.processIdentity===void 0?null:ln(t.processIdentity);return t.processIdentity!==void 0&&(!n||n.pid!==t.pid)?null:{version:1,ownerId:t.ownerId,pid:t.pid,...n?{processIdentity:n}:{}}}catch{return null}}function Cy(e,t){for(let n of[Se(e.pendingDir,`${t}.json`),Se(e.legacyRequestDir,`${t}.json`),Se(e.responseDir,`${t}.json`)])if(ri(n))return n;for(let n of Bu(e.inflightDir))if(n.requestId===t)return n.path;return null}function Ry(e,t,n){let r=$u(e);if(!r||r.operationKey!==t)throw new Error(`Mailbox operation ${n} conflicts with an existing retained record.`);return r}function uM(e){if(e.mailboxVersion!==Nn||e.id!==mr(e.operationKey)||!e.clientId.trim()||!Number.isFinite(e.enqueuedAtMs)||!Number.isFinite(e.deadlineAtMs)||e.deadlineAtMs<e.enqueuedAtMs)throw new Error("Mailbox request has an invalid lifecycle identity.")}function Bu(e){if(!ri(e))return[];let t=[];for(let n of ni(e,{withFileTypes:!0})){if(!n.isDirectory())continue;let r=Iy(n.name);if(r===null)continue;let i=Se(e,n.name);for(let o of ni(i,{withFileTypes:!0})){if(!o.isFile()||!o.name.endsWith(".claim"))continue;let s=/^(.*)\.(\d+)\.claim$/.exec(o.name);if(!s)continue;let a=Iy(s[1]),c=Number(s[2]);if(a===null||Ou(a)!==a||!a.endsWith(".json")||!Number.isSafeInteger(c))continue;let l=Se(i,o.name),u=$u(l)??{id:Ou(a,".json")},d=mo(l);t.push({requestId:u.id,ownerId:r,path:l,originalFile:a,claimedAtMs:d.mtimeMs,claimExpiresAtMs:c,byteLength:d.size,...u.operationKey?{operationKey:u.operationKey}:{},...u.clientId?{clientId:u.clientId}:{},...u.enqueuedAtMs===void 0?{}:{enqueuedAtMs:u.enqueuedAtMs},...u.deadlineAtMs===void 0?{}:{deadlineAtMs:u.deadlineAtMs},legacy:u.operationKey===void 0})}}return t.sort((n,r)=>n.claimedAtMs-r.claimedAtMs||n.path.localeCompare(r.path))}function $u(e){try{let t=JSON.parse(uo(e,"utf8"));return typeof t.id!="string"||!t.id?null:{id:t.id,...typeof t.operationKey=="string"?{operationKey:t.operationKey}:{},...typeof t.clientId=="string"?{clientId:t.clientId}:{},...typeof t.enqueuedAtMs=="number"?{enqueuedAtMs:t.enqueuedAtMs}:{},...typeof t.deadlineAtMs=="number"?{deadlineAtMs:t.deadlineAtMs}:{}}}catch{return null}}function dM(e){try{let t=JSON.parse(uo(e,"utf8"));return typeof t.expiresAtMs=="number"&&Number.isFinite(t.expiresAtMs)?t.expiresAtMs:null}catch{return null}}function vy(e,t,n,r,i){for(let o of lo(e)){if(t<=0)break;let s=mo(o);n(o,s.mtimeMs)>r||(An(o,{force:!0}),i(),t--)}return t}function lo(e){return ri(e)?ni(e,{withFileTypes:!0}).filter(t=>t.isFile()).map(t=>Se(e,t.name)).sort():[]}function Py(e){if(!ri(e))return[];let t=[];for(let n of ni(e,{withFileTypes:!0})){let r=Se(e,n.name);n.isFile()?t.push(r):n.isDirectory()&&t.push(...Py(r))}return t.sort()}function mM(e){if(ri(e))for(let t of ni(e,{withFileTypes:!0})){if(!t.isDirectory())continue;let n=Se(e,t.name);ni(n).some(r=>r.endsWith(".claim"))||An(n,{recursive:!0,force:!0})}}function fM(e){try{return mo(e).size}catch{return 0}}function Fy(e){return Buffer.from(e,"utf8").toString("base64url")}function Iy(e){try{let t=Buffer.from(e,"base64url").toString("utf8");return Fy(t)===e?t:null}catch{return null}}import{execFileSync as RM}from"child_process";import{existsSync as pM,readFileSync as gM}from"fs";import{deserializeSCIP as hM,SymbolRole as yM}from"@c4312/scip";import{existsSync as Nee,readFileSync as Oee}from"fs";import{relative as Bee,resolve as $ee,sep as Hee}from"path";import{fileURLToPath as qee,pathToFileURL as Gee}from"url";function Da(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 Hu=new WeakMap,bM="SCIP_RUST_SCIP_OCCURRENCE_REFERENCE_MODE";function Ty(e,t){let n=new Map,r=ka(),i=t.filter(s=>My(s,r));if(i.length===0)return n;let o=Ay(e);if(!o)return n;for(let s of i){let a=Ly(o,s);a!==null&&n.set(s.symbolId,a)}return n}function _y(e,t){if(!My(t,ka()))return null;let n=Ay(e);return n?Ly(n,t):null}function Ly(e,t){return e.referencesBySymbol.get(t.symbol)??[]}function My(e,t="safe"){if(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||Fe(e.symbol)||/impl#\[[^\]]+\]\[Default\]default\(\)\.$/.test(e.symbol))return!1;if(t==="all")return!0;let n=pe(e.symbol);if(n==="method")return!0;if(n!=="term")return!1;let r=Re(e.symbol);return"kind"in r?!1:!SM(r)}function SM(e){for(let t=0;t<e.descriptors.length-1;t+=1)if(e.descriptors[t]?.suffix==="type")return!0;return!1}function Ay(e){if(Hu.has(e))return Hu.get(e)??null;let t=xM(e);return Hu.set(e,t),t}function xM(e){if(!e.generation.indexPath||!pM(e.generation.indexPath))return null;try{let t=hM(gM(e.generation.indexPath)),n=new Map;for(let r of t.documents??[]){let i=r.relativePath;if(!(!i||e.isIgnored(i)))for(let o of r.occurrences??[]){if(!o.symbol||(o.symbolRoles&yM.Definition)!==0)continue;let s=CM(i,o.range);if(!s)continue;let a=n.get(o.symbol)??[];a.push(s),n.set(o.symbol,a)}}for(let[r,i]of n)n.set(r,Da(i));return{referencesBySymbol:n}}catch{return null}}function CM(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 ka(){return process.env[bM]==="all"?"all":"safe"}var Ny=new Map;function Uu(e){let n=va(e).resolvedBinary??null;return{engine:"rust-analyzer",resolvedBinary:n,version:n?vM(e,n):"unavailable"}}function fr(e){return{...Uu(e),scipOccurrenceReferenceMode:ka()}}function vM(e,t){let n=`${e}\0${t}`,r=Ny.get(n);if(r)return r;let i;try{i=RM(t,["--version"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim()}catch{i="unknown"}return Ny.set(n,i),i}import{createHash as jM}from"crypto";import{execFileSync as IM}from"child_process";import{createHash as Oy}from"crypto";import{lstatSync as wM,readdirSync as EM,readFileSync as DM,readlinkSync as kM,realpathSync as jy}from"fs";import{isAbsolute as PM,join as By,relative as FM,sep as TM}from"path";function _M(e){return[...new Set((e??[]).map(t=>t.trim()).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function LM(e){return(AM(e)??NM(e)).filter(t=>t&&!$y(t)).sort()}function qu(e,t={}){let n=LM(e).filter(i=>!t.language||wp(i,t.language,t.markerFiles)).filter(i=>!t.includePath||t.includePath(i)),r=jy(e);return n.map(i=>{let o=By(e,i);try{if(wM(o).isSymbolicLink()){let a=jy(o),c=FM(r,a);if(c===".."||c.startsWith(`..${TM}`)||PM(c))throw new Error("external symlink");let l=kM(o);return{path:i,size:Buffer.byteLength(l),hash:Oy("sha256").update("symlink\0").update(l).digest("hex")}}let s=DM(o);return{path:i,size:s.byteLength,hash:Oy("sha256").update(s).digest("hex")}}catch{return{path:i,size:-1,hash:"unreadable"}}})}function fo(e,t,n){return{version:2,languages:[...t].sort(),pnpmWorkspaces:n.typescriptProjectMode!=="workspace"&&n.pnpmWorkspaces===!0,typescriptProjectMode:n.typescriptProjectMode??"single",typescriptProjects:_M(n.typescriptProjects),clojureConfigPath:MM(n.clojureConfigPath),files:qu(e)}}function MM(e){return e?.trim()||void 0}function AM(e){try{return IM("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:50*1024*1024,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"}).split(`
|
|
310
|
+
`).filter(Boolean)}catch{return null}}function NM(e){let t=[],n=[""];for(;n.length>0;){let r=n.pop(),i=r?By(e,r):e,o;try{o=EM(i,{withFileTypes:!0})}catch{continue}for(let s of o){let a=r?`${r}/${s.name}`:s.name;if(s.isDirectory()){$y(a)||n.push(a);continue}t.push(a)}}return t}function $y(e){let t=e.split("/");return e==="meta.json"||t.some(n=>OM.has(n))||e.endsWith(".db")||e.endsWith(".db-wal")||e.endsWith(".db-shm")||e.endsWith(".scip")}var OM=new Set([".git","node_modules",".scipquery-cache",".scipquery-generations",".stryker-tmp","dist","build","coverage",".next",".nuxt","target"]);var BM=new Set(["Cargo.lock","Cargo.toml","rust-project.json","rust-toolchain","rust-toolchain.toml"]);function Hy(e){let t=qu(e,{includePath:$M});return jM("sha256").update(JSON.stringify(t)).digest("hex")}function $M(e){let t=e.replaceAll("\\","/"),n=t.split("/").at(-1)??t;return t.endsWith(".rs")||BM.has(n)?!0:t===".cargo/config"||t===".cargo/config.toml"||t.endsWith("/.cargo/config")||t.endsWith("/.cargo/config.toml")}import{createHash as HM}from"crypto";import{resolve as UM}from"path";var oi=3;function Vu(e){return HM("sha256").update(un({kind:"scip-query-durable-rust-mailbox",protocolVersion:oi,sessionDir:UM(e)})).digest("hex")}function Gy(e,t){return q(e)?e.protocolVersion!==oi?qy(e.protocolVersion===void 0?"helper wrote a prior uncorrelated response protocol":`helper wrote unsupported response protocol ${String(e.protocolVersion)}`):e.mailboxVersion!==Nn||e.id!==t.requestId||e.operationKey!==t.operationKey||e.sessionIdentity!==t.sessionIdentity||e.deadlineAtMs!==t.deadlineAtMs?qy("helper wrote an incompatible response identity"):typeof e.completedAtMs!="number"||!Number.isFinite(e.completedAtMs)||e.completedAtMs>t.deadlineAtMs||t.nowMs>t.deadlineAtMs?{ok:!1,code:"expired-request",error:"helper response arrived after the durable request deadline"}:e.ok===!1?typeof e.error!="string"||!WM(e.errorCode)?Gu("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"||!qM(e.response,t.requestKind)?Gu("helper wrote an invalid success response"):{ok:!0,session:e.session,response:e.response}:Gu("helper wrote an invalid response object")}function qM(e,t){return!q(e)||typeof e.available!="boolean"||e.reason!==void 0&&typeof e.reason!="string"?!1:t==="import-definitions"?Array.isArray(e.sourcePaths)&&e.sourcePaths.every(n=>Array.isArray(n)&&n.length===2&&typeof n[0]=="string"&&(n[1]===null||typeof n[1]=="string")):Uy(e.references,GM)&&(e.incompleteReferenceSymbolIds===void 0||Array.isArray(e.incompleteReferenceSymbolIds)&&e.incompleteReferenceSymbolIds.every(n=>Number.isSafeInteger(n)))&&(e.callees===void 0||Uy(e.callees,VM))&&(e.signatures===void 0||Array.isArray(e.signatures)&&e.signatures.every(n=>Array.isArray(n)&&n.length===2&&Number.isSafeInteger(n[0])&&(n[1]===null||typeof n[1]=="string")))}function Uy(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 GM(e){return q(e)&&typeof e.file=="string"&&j(e.line)&&j(e.column)}function VM(e){return q(e)&&typeof e.symbol=="string"&&typeof e.file=="string"&&j(e.line)}function WM(e){return e==="unsupported-protocol"||e==="malformed-request"||e==="expired-request"||e==="handler-error"}function Gu(e){return{ok:!1,code:"malformed-response",error:e}}function qy(e){return{ok:!1,code:"incompatible-response",error:e}}var ZM=5e3,Yy=10,eA=3e4;function Vy(e,t,n,r=eb){let i=r.engineIdentity(e),o={protocolVersion:oi,projectRoot:r.canonicalProjectRoot(e),projectFingerprint:r.projectFingerprint(e),engine:{engine:i.engine,resolvedBinary:i.resolvedBinary,version:i.version},workerFingerprint:r.fileFingerprint(t),environment:Xy(r.environment())};return{key:Pa(un(o)),...o}}function po(e,t,n,r){if(e.protocolVersion!==oi||!n(e.pid))return!1;if(!e.processIdentity)return!0;let i=r?.(e.pid);return i!=null&&ft(e.processIdentity,i)}function Wu(e,t,n){let r;try{r=Pa(Fa(t))}catch{r="missing"}let i=Pa(un({projectRoot:si(e),serverPath:si(t),serverFingerprint:r})).slice(0,20);return si(n,`scip-query-rust-session-${i}`)}function Wy(e){let t=e===void 0?Number.NaN:Number(e);return Number.isInteger(t)&&t>=0?t:0}function Xy(e){return Object.fromEntries(Object.entries(e).filter(([t])=>Zy(t)).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>[t,n??null]))}function Qy(e,t){let n=t.runtime??sA,r=t.identityRuntime??eb,i=Wu(e,t.serverPath,t.tempRoot??QM()),o=!1,s=(a,c)=>{if(o)throw new Error("Durable Rust semantic session was already disposed.");return nA(i,t.serverPath,t.semanticWorkerPath,a,c,n,t.mailboxLimits)};return{requestSemantic(a,c){let l=Vy(e,t.semanticWorkerPath,a,r),{readinessDeadlineMs:u,...d}=a;return s({kind:"semantic",identityKey:l.key,workerEnvironment:Ky(),request:{...d,referenceRetryTimeoutMs:tA(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,a.referenceRetryTimeoutMs),settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:Wy(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},requestImportDefinitions(a,c){let l=Vy(e,t.semanticWorkerPath,a,r),{readinessDeadlineMs:u,...d}=a;return s({kind:"import-definitions",identityKey:l.key,workerEnvironment:Ky(),request:{...d,settleDelayMs:process.env.SCIP_RUST_SEMANTIC_SETTLE_MS===void 0?a.settleDelayMs:Wy(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS)},timeoutMs:c},c)},shutdown(){o=!0}}}function tA(e,t){return t!==void 0?t:e===void 0?eA:void 0}function nA(e,t,n,r,i,o,s={}){let a=o.now(),c=a+i,l=(o.monotonicNow??we)(),u=l+i,d=ii("rust-semantic-v3",r),m=mr(d),f=wa(e),p=Vu(e),g=Ea(f,{mailboxVersion:Nn,protocolVersion:oi,id:m,operationKey:d,clientId:o.randomId(),enqueuedAtMs:a,deadlineAtMs:c,sessionIdentity:p,request:r},{nowMs:a,limits:s});for(zy(e,t,n,u,o);(o.monotonicNow??we)()<=u;){if(Jy(g.responsePath)){let h=rA(Fa(g.responsePath,"utf8"),{requestId:m,operationKey:d,sessionIdentity:p,deadlineAtMs:g.authoritativeDeadlineAtMs,requestKind:r.kind,nowMs:o.now()});if(!h.ok)throw new Error(h.error);return G()&&vn({type:"span",name:"rust.semantic.durable-session.request",durationMs:(o.monotonicNow??we)()-l,ok:!0,session:h.session,kind:r.kind}),h.response}let y=go(e);(!y||!po(y,o.now(),o.isProcessAlive,o.readProcessIdentity))&&zy(e,t,n,u,o),o.sleep(Yy)}throw new Error(`Durable Rust semantic session timed out after ${(i/1e3).toFixed(0)}s.`)}function zy(e,t,n,r,i){let o=go(e);if(o&&po(o,i.now(),i.isProcessAlive,i.readProcessIdentity))return;XM(si(e,"server.json"),{force:!0}),i.spawnServer(t,e,n);let s=i.monotonicNow??we,a=Math.min(r,s()+ZM);for(;s()<=a;){let c=go(e);if(c&&po(c,i.now(),i.isProcessAlive,i.readProcessIdentity))return;i.sleep(Yy)}throw new Error("Durable Rust semantic session helper did not become ready within 5s.")}function go(e){try{let t=JSON.parse(Fa(si(e,"server.json"),"utf8"));if(typeof t.protocolVersion!="number"||t.sessionIdentity!==void 0&&(typeof t.sessionIdentity!="string"||t.sessionIdentity!==Vu(e))||typeof t.pid!="number"||typeof t.heartbeatAtMs!="number"||t.busyUntilMs!==void 0&&typeof t.busyUntilMs!="number"||t.mailbox!==void 0&&!iA(t.mailbox))return null;let n=t.processIdentity===void 0?null:ln(t.processIdentity);return t.processIdentity!==void 0&&(!n||n.pid!==t.pid)?null:{protocolVersion:t.protocolVersion,...t.sessionIdentity===void 0?{}:{sessionIdentity:t.sessionIdentity},pid:t.pid,...n?{processIdentity:n}:{},heartbeatAtMs:t.heartbeatAtMs,...t.busyUntilMs===void 0?{}:{busyUntilMs:t.busyUntilMs},...t.mailbox===void 0?{}:{mailbox:t.mailbox}}}catch{return null}}function rA(e,t){try{return Gy(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 iA(e){if(!e||typeof e!="object")return!1;let t=e;return j(t.pending)&&j(t.inflight)&&j(t.responses)&&j(t.deadLetters)&&j(t.invalid)&&j(t.totalItems)&&typeof t.totalBytes=="number"&&Number.isFinite(t.totalBytes)&&t.totalBytes>=0&&(t.oldestPendingAt===void 0||Number.isFinite(Date.parse(t.oldestPendingAt)))}function Ky(){return Object.fromEntries(Object.entries(process.env).filter(([e])=>oA(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t??null]))}function Zy(e){return e==="HOME"||e==="PATH"||e.startsWith("CARGO_")||e.startsWith("RA_")||e.startsWith("RUST")}function oA(e){return Zy(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 eb={canonicalProjectRoot(e){try{return YM(e)}catch{return si(e)}},projectFingerprint(e){return Hy(e)},engineIdentity:Uu,fileFingerprint(e){return Pa(Fa(e))},environment(){return Xy(process.env)}},sA={now:Date.now,monotonicNow:we,randomId:JM,isProcessAlive:Ln,readProcessIdentity:Rt,spawnServer(e,t,n){if(!Jy(e))throw new Error(`Durable Rust semantic session helper was not found at ${e}. Run npm run build first.`);zM(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 Pa(e){return KM("sha256").update(e).digest("hex")}var rb=15e3,ib=8,sb=5e3,dA=64,mA=96,Xu=class{constructor(t,n,r={}){this.projectRoot=t;this.status=n;this.opts=r;this.requester=r.requester??gA(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:n.reason,references:ho(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!0});return{available:r.available,resolvedBinary:n.resolvedBinary,reason:r.reason,references:Mn(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:ho(t)}}}calleesForDefinitions(t){let n=this.status(this.projectRoot);if(!n.available||!n.resolvedBinary)return{available:!1,resolvedBinary:n.resolvedBinary,reason:n.reason,callees:yo(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!0});return{available:r.available,resolvedBinary:n.resolvedBinary,reason:r.reason,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:yo(t)}}}referencesAndCalleesForDefinitions(t,n){let r=this.status(this.projectRoot);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,references:ho(t),callees:yo(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{available:o.available,resolvedBinary:r.resolvedBinary,reason:o.reason,references:Mn(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:n.reason,signatures:ob(t)};try{let r=this.requestSession(n.resolvedBinary,t,{includeReferences:!1,includeCallees:!1,includeSignatures:!0});return{available:r.available,resolvedBinary:n.resolvedBinary,reason:r.reason,signatures:xA(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:ob(t)}}}importDefinitionsForFile(t,n){let r=this.status(this.projectRoot);if(n.length===0)return{available:r.available,resolvedBinary:r.resolvedBinary,reason:r.reason,sourcePaths:new Map};if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,sourcePaths:new Map(n.map(i=>[i.id,null]))};try{let i=this.requestImportDefinitions(r.resolvedBinary,t,n);return{available:i.available,resolvedBinary:r.resolvedBinary,reason:i.reason,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=Ta(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,rb),o=_a(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),s=Ta(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,ib),a=_a(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=So(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,{definitionCount:n.length,...r}),m={projectRoot:this.projectRoot,rustAnalyzerBinary:t,definitions:[...n],...c?{referenceDefinitions:c}:{},...l?{calleeDefinitions:l}:{},...u?{signatureDefinitions:u}:{},requestTimeoutMs:i,...r.includeReferences!==!1&&o>0?{referenceRetryTimeoutMs:o}:{},diagnosticsTimeoutMs:a,settleDelayMs:d,concurrency:s,includeReferences:r.includeReferences,includeCallees:r.includeCallees,includeSignatures:r.includeSignatures},f=CA(m);return E("rust.semantic.session.request",()=>this.requester.requestSemantic(m,dr(f,Qu(i,m.referenceRetryTimeoutMs),s)),()=>({definitions:n.length,operationDefinitions:f,referenceDefinitions:m.referenceDefinitions?.length,calleeDefinitions:m.calleeDefinitions?.length,signatureDefinitions:m.signatureDefinitions?.length,references:m.includeReferences!==!1,callees:m.includeCallees===!0,signatures:m.includeSignatures===!0,referenceRetryTimeoutMs:m.referenceRetryTimeoutMs}))}fallbackReferencesAndCallees(t,n,r,i){let o=n.length===0?{available:!0,references:ho(n)}:this.opts.fallbackReferenceResolver?.referencesForDefinitions(n),s=r.length===0?{available:!0,callees:yo(r)}:this.opts.fallbackCalleeResolver?.calleesForDefinitions(r);return o&&s?{available:o.available&&s.available,resolvedBinary:o.resolvedBinary??s.resolvedBinary??t.resolvedBinary,reason:o.reason??s.reason,references:Mn(n,o.references),callees:Ju(r,s.callees)}:{available:!1,resolvedBinary:t.resolvedBinary,reason:i instanceof Error?i.message:String(i),references:ho(n),callees:yo(r)}}requestImportDefinitions(t,n,r){let i=Ta(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,rb),o=Ta(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,ib),s=_a(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(i,1e4)),a=_a(process.env.SCIP_RUST_SEMANTIC_SETTLE_MS,sb),c={projectRoot:this.projectRoot,rustAnalyzerBinary:t,file:n,positions:[...r],requestTimeoutMs:i,diagnosticsTimeoutMs:s,settleDelayMs:a,concurrency:o};return E("rust.semantic.import-definitions.session.request",()=>this.requester.requestImportDefinitions(c,dr(r.length,i,o)),()=>({file:n,positions:r.length}))}};function ab(e,t,n={}){return new Xu(e,t,n)}function So(e,t){let n=db(e);if(n!==null)return n;let r=t.includeReferences!==!1;return r&&t.includeCallees!==!0&&t.includeSignatures!==!0&&t.definitionCount<=dA||r&&t.includeCallees===!0&&t.includeSignatures!==!0&&t.definitionCount<=mA?0:sb}function cb(e){let t=e?.trim().toLowerCase(),n=t==="0"||t==="false"||t==="off"||t==="worker",r=t==="1"||t==="true"||t==="on"||t==="durable",i=t===void 0||t==="";return{transport:n||!i&&!r?"worker":"durable",source:i?"default":"environment",fallback:"worker",valid:i||n||r,optOut:"SCIP_RUST_SEMANTIC_DURABLE_SESSION=0"}}function fA(e){return cb(e).transport}function Wte(e,t){let n=cb(t);if(n.transport==="worker")return{...n,state:"per-command"};let r=bo(ub()),i=Wu(e,r,Yu()),o=go(i);return o?{...n,state:po(o,Date.now(),Ln,Rt)?"live":"stale",pid:o.pid,heartbeatAtMs:o.heartbeatAtMs,...o.busyUntilMs===void 0?{}:{busyUntilMs:o.busyUntilMs}}:{...n,state:"stopped"}}function pA(e,t){let n=null,r=!1,i=!1,o=!1,s=()=>n??=t(),a=()=>{i||(e.shutdown(),i=!0)},c=(u,d,m)=>{let f=SA(u);r=!0;try{a()}catch{}G()&&vn({type:"span",name:"rust.semantic.durable-session.request",durationMs:m,ok:!1,kind:d,session:"worker-fallback",reason:f})},l=(u,d,m)=>{if(o)throw new Error("Rust semantic failover session was already disposed.");if(r)return m(s());let f=performance.now();try{return d(e)}catch(p){c(p,u,performance.now()-f)}return m(s())};return{requestSemantic(u,d){return l("semantic",m=>m.requestSemantic(u,d),m=>m.requestSemantic(u,d))},requestImportDefinitions(u,d){return l("import-definitions",m=>m.requestImportDefinitions(u,d),m=>m.requestImportDefinitions(u,d))},shutdown(){if(o)return;o=!0;let u=[];try{a()}catch(d){u.push(d)}try{n?.shutdown()}catch(d){u.push(d)}if(u.length>0)throw u[0]}}}function gA(e,t,n={worker:()=>hA(),durable:()=>Qy(e,{serverPath:bo(ub()),semanticWorkerPath:bo(lb())})}){return fA(t)==="durable"?pA(n.durable(),n.worker):n.worker()}function hA(e={}){let t=null,n=null,r=1,i=!1,o=()=>{n&&(zu(n,{recursive:!0,force:!0}),n=null)},s=()=>{let l=t;t=null,l&&l.terminate(),o()},a=()=>{if(t)return t;let l=e.semanticWorkerPath?cA(e.semanticWorkerPath):lb();if(!aA(bo(l)))throw new Error(`Rust semantic session worker was not found at ${bo(l)}. Run npm run build before using built semantic Rust queries.`);return n=tb(Ku(Yu(),"scip-query-rust-session-")),t=new uA(l,e.shareEnvironment?{env:lA}:void 0),t.unref(),t},c=()=>{let l=n??tb(Ku(Yu(),"scip-query-rust-session-"));return n=l,Ku(l,`${r++}.json`)};return{requestSemantic(l,u){if(i)throw new Error("Rust semantic session was already disposed.");let d=a(),m=c(),f=new SharedArrayBuffer(4),p=new Int32Array(f);if(d.postMessage({kind:"semantic",request:l,responsePath:m,sharedBuffer:f}),Atomics.wait(p,0,0,u)==="timed-out")throw s(),new Error(`Rust semantic session worker timed out after ${(u/1e3).toFixed(0)}s`);try{let y=yA(nb(m,"utf8"));if(!y.ok)throw new Error(y.error);return y.response}finally{zu(m,{force:!0})}},requestImportDefinitions(l,u){if(i)throw new Error("Rust semantic session was already disposed.");let d=a(),m=c(),f=new SharedArrayBuffer(4),p=new Int32Array(f);if(d.postMessage({kind:"import-definitions",request:l,responsePath:m,sharedBuffer:f}),Atomics.wait(p,0,0,u)==="timed-out")throw s(),new Error(`Rust semantic import-definition session worker timed out after ${(u/1e3).toFixed(0)}s`);try{let y=bA(nb(m,"utf8"));if(!y.ok)throw new Error(y.error);return y.response}finally{zu(m,{force:!0})}},shutdown(){if(i)return;if(i=!0,!t){o();return}let l=c(),u=new SharedArrayBuffer(4),d=new Int32Array(u);t.postMessage({kind:"shutdown",responsePath:l,sharedBuffer:u}),Atomics.wait(d,0,0,5e3),s()}}}function yA(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 bA(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 SA(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 ho(e){return new Map(e.map(t=>[t.symbolId,[]]))}function yo(e){return new Map(e.map(t=>[t.symbolId,[]]))}function ob(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 xA(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function CA(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 Qu(e,t){return t&&t>0?Math.max(e,t):e}function lb(){return new URL("./rust-semantic-session-worker.js",import.meta.url)}function ub(){return new URL("./rust-semantic-session-server.js",import.meta.url)}function Ta(e,t){return _n(e)??t}function _a(e,t){return db(e)??t}function db(e){if(!e)return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null}var td=15e3,nd=8;function gb(e,t={}){let n=t.status??va,r=wA(e,n),i=EA(e,n),o=DA(e,n),s=t.referenceResolver||t.calleeResolver||t.signatureResolver||!vA(t)?null:ab(e,n,{fallbackReferenceResolver:r,fallbackCalleeResolver:i,fallbackSignatureResolver:o}),a=t.referenceResolver??s??r,c=t.calleeResolver??s??i,l=t.signatureResolver??s??o,u=t.importUsageResolver??sy(t.sourceImportUsageResolver??IA(),t.importDefinitionResolver??s),d=t.calleeSymbolResolver,m=t.sourceZeroCalleeOracle,f=t.scipOccurrenceCalleeOracle,p=new Map,g=new Map,y=null,h=null,C=()=>(y??=n(e),y),b=()=>{let D=C();return D.dependencyAvailable?h??D:D},S=D=>{if(D.length===0)return new Map;let w=xo(D);try{let k=a.referencesForDefinitions(w),L=C();return h={...L,available:k.available,resolvedBinary:k.resolvedBinary??L.resolvedBinary,reason:k.reason??L.reason},k.available?new Map(k.references):Mn(w,k.references)}catch(k){return h={...C(),available:!1,reason:k instanceof Error?k.message:String(k)},pr(w)}},x=D=>{if(D.length===0)return new Map;let w=xo(D),k=w.filter(mb);if(k.length===0)return gr(w);let L=new Map,ne=pb(k,f),ee=[];for(let _ of k)g.has(_.symbolId)?L.set(_.symbolId,g.get(_.symbolId)??[]):ne.has(_.symbolId)?L.set(_.symbolId,ne.get(_.symbolId)??[]):fb(_,m)?L.set(_.symbolId,[]):ee.push(_);if(ee.length===0)return ai(w,L,void 0);try{let _=c.calleesForDefinitions(ee),ue=C();h={...ue,available:_.available,resolvedBinary:_.resolvedBinary??ue.resolvedBinary,reason:_.reason??ue.reason};let re=ai(ee,_.callees,d);for(let[xn,bl]of re)L.set(xn,bl);return ai(w,L,void 0)}catch(_){return h={...C(),available:!1,reason:_ instanceof Error?_.message:String(_)},gr(w)}},v=(D,w)=>{let k=xo(D),L=xo(w),ne=L.filter(mb),ee=new Map,_=pb(ne,f),ue=[];for(let re of ne)_.has(re.symbolId)?ee.set(re.symbolId,_.get(re.symbolId)??[]):fb(re,m)?ee.set(re.symbolId,[]):ue.push(re);if(k.length===0&&ue.length===0)return{references:pr(k),callees:ai(L,ee,void 0)};try{let re=s?s.referencesAndCalleesForDefinitions(k,ue):TA(a,c,{referenceDefinitions:k,calleeDefinitions:ue}),xn=C();h={...xn,available:re.available,resolvedBinary:re.resolvedBinary??xn.resolvedBinary,reason:re.reason??xn.reason};let bl=re.available?new Map(re.references):Mn(k,re.references);for(let[Sl,xl]of re.callees)ee.set(Sl,xl);let Cp=ai(L,ee,d);for(let[Sl,xl]of Cp)g.set(Sl,xl);return{references:bl,callees:Cp}}catch(re){return h={...C(),available:!1,reason:re instanceof Error?re.message:String(re)},{references:pr(k),callees:gr(L)}}},R=D=>{if(D.length===0)return new Map;let w=xo(D);try{let k=l.signaturesForDefinitions(w),L=C();return h={...L,available:k.available,resolvedBinary:k.resolvedBinary??L.resolvedBinary,reason:k.reason??L.reason},hb(w,k.signatures)}catch(k){return h={...C(),available:!1,reason:k instanceof Error?k.message:String(k)},La(w)}};return{language:"rust",availability:b,dispose:()=>{s?.dispose()},importUsage:D=>{let w=p.get(D);if(w)return w;try{let k=u.importUsage(D);return p.set(D,k),k}catch(k){return h={...C(),available:!1,reason:k instanceof Error?k.message:String(k)},[]}},referencesFor:D=>S([D]).get(D.symbolId)??[],referencesForDefinitions:S,referencesAndCalleesForDefinitions:v,calleesFor:D=>x([D]).get(D.symbolId)??[],calleesForDefinitions:x,signatureFor:D=>R([D]).get(D.symbolId)??null}}function vA(e){if(e.usePersistentSession!==void 0)return e.usePersistentSession;let t=process.env.SCIP_RUST_SEMANTIC_SESSION;return t!=="0"&&t!=="false"}function IA(){return{importUsageFacts:()=>({usage:[],positions:[]})}}function xo(e){return e.map(t=>{let n=t;return{...t,leaf:typeof n.leaf=="string"?n.leaf:F(t.symbol),parentTypeName:n.parentTypeName??null,isFunctionLike:typeof n.isFunctionLike=="boolean"?n.isFunctionLike:oe(t.symbol),isTypeLike:n.isTypeLike??!1,kind:n.kind??null,documentation:n.documentation??null,enclosingSymbol:n.enclosingSymbol??null}})}function mb(e){return e.isFunctionLike}function fb(e,t){if(!t)return!1;try{return t(e)}catch{return!1}}function pb(e,t){if(!t||e.length===0)return new Map;try{return t(e)}catch{return new Map}}function wA(e,t){return{referencesForDefinitions:n=>kA(e,t,n)}}function EA(e,t){return{calleesForDefinitions:n=>PA(e,t,n)}}function DA(e,t){return{signaturesForDefinitions:n=>FA(e,t,n)}}function kA(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,references:pr(n)};let i=rd();if(!ed(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:pr(n)};let o=ci(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,td),s=Ma(process.env.SCIP_RUST_SEMANTIC_REFERENCE_RETRY_TIMEOUT_MS,0),a=ci(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,nd),c=Ma(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),l=So(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=Zu(process.execPath,[i],{cwd:e,input:JSON.stringify(u),encoding:"utf8",maxBuffer:50*1024*1024,timeout:dr(n.length,Qu(o,u.referenceRetryTimeoutMs),a)}),m=id(d.stdout);if(m)return{available:m.available,resolvedBinary:r.resolvedBinary,reason:m.reason,references:Mn(n,new Map(m.references),new Set(m.incompleteReferenceSymbolIds??[]))};let f=d.error instanceof Error?d.error.message:d.stderr.trim()||`Rust semantic worker exited with status ${d.status??"unknown"}.`;return{available:!1,resolvedBinary:r.resolvedBinary,reason:f,references:pr(n)}}function PA(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,callees:gr(n)};let i=rd();if(!ed(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:gr(n)};let o=ci(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,td),s=ci(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,nd),a=Ma(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=So(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=Zu(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:dr(n.length,o,s)}),d=id(u.stdout);if(d)return{available:d.available,resolvedBinary:r.resolvedBinary,reason:d.reason,callees:ai(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:gr(n)}}function FA(e,t,n){let r=t(e);if(!r.available||!r.resolvedBinary)return{available:!1,resolvedBinary:r.resolvedBinary,reason:r.reason,signatures:La(n)};let i=rd();if(!ed(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:La(n)};let o=ci(process.env.SCIP_RUST_SEMANTIC_REQUEST_TIMEOUT_MS,td),s=ci(process.env.SCIP_RUST_SEMANTIC_CONCURRENCY,nd),a=Ma(process.env.SCIP_RUST_SEMANTIC_DIAGNOSTICS_TIMEOUT_MS,Math.min(o,1e4)),c=So(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=Zu(process.execPath,[i],{cwd:e,input:JSON.stringify(l),encoding:"utf8",maxBuffer:50*1024*1024,timeout:dr(n.length,o,s)}),d=id(u.stdout);if(d)return{available:d.available,resolvedBinary:r.resolvedBinary,reason:d.reason,signatures:hb(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:La(n)}}function TA(e,t,n){let r=n.referenceDefinitions.length>0?e.referencesForDefinitions(n.referenceDefinitions):{available:!0,references:pr(n.referenceDefinitions)},i=n.calleeDefinitions.length>0?t.calleesForDefinitions(n.calleeDefinitions):{available:!0,callees:gr(n.calleeDefinitions)};return{available:r.available&&i.available,resolvedBinary:r.resolvedBinary??i.resolvedBinary,reason:r.reason??i.reason,references:r.references,callees:i.callees}}function pr(e){return new Map(e.map(t=>[t.symbolId,[]]))}function gr(e){return new Map(e.map(t=>[t.symbolId,[]]))}function La(e){return new Map(e.map(t=>[t.symbolId,null]))}function ai(e,t,n){let r=0,i=0;return E("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 hb(e,t){return new Map(e.map(n=>[n.symbolId,t.get(n.symbolId)??null]))}function rd(){return RA(new URL("./rust-semantic-worker.js",import.meta.url))}function id(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return typeof n.available!="boolean"||!Array.isArray(n.references)?null:{available:n.available,reason:typeof n.reason=="string"?n.reason:void 0,references:n.references,incompleteReferenceSymbolIds:Array.isArray(n.incompleteReferenceSymbolIds)?n.incompleteReferenceSymbolIds.filter(r=>typeof r=="number"):void 0,callees:Array.isArray(n.callees)?n.callees:void 0,signatures:Array.isArray(n.signatures)?n.signatures:void 0}}catch{return null}}function ci(e,t){return _n(e)??t}function Ma(e,t){if(!e)return t;let n=Number(e);return Number.isInteger(n)&&n>=0?n:t}import{existsSync as _A,readFileSync as LA}from"fs";import{deserializeSCIP as MA,SymbolRole as AA}from"@c4312/scip";var od=new WeakMap;function bb(e,t){let n=t.filter(NA);if(n.length===0)return new Map;let r=!1,i=0,o=0;return E("rust.scip-occurrence.callees",()=>{let s=BA(e);if(r=!!s,!s)return new Map;let a=new Map;for(let c of n){let l=OA(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 NA(e){return!(!e.symbol.startsWith("rust-analyzer ")||!e.relativePath.endsWith(".rs")||!e.isFunctionLike||e.leaf==="main"||Fe(e.symbol))}function OA(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)||!jA(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 jA(e,t){let n=yb(e),r=yb(t);if(n.size!==r.size)return!1;for(let[i,o]of n)if(r.get(i)!==o)return!1;return!0}function yb(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 BA(e){if(od.has(e))return od.get(e)??null;let t=$A(e);return od.set(e,t),t}function $A(e){if(!e.generation.indexPath||!_A(e.generation.indexPath))return null;try{let t=De(e).filter(o=>o.symbol.startsWith("rust-analyzer ")&&o.relativePath.endsWith(".rs")&&o.isFunctionLike),n=new Map(t.map(o=>[o.symbol,o])),r=MA(LA(e.generation.indexPath)),i=new Map;for(let o of r.documents??[]){let s=o.relativePath;if(!s||!s.endsWith(".rs")||e.isIgnored(s))continue;let a=[];for(let c of o.occurrences??[]){if(!c.symbol||(c.symbolRoles&AA.Definition)!==0)continue;let l=n.get(c.symbol);if(!l)continue;let u=c.range?.[0];Number.isInteger(u)&&a.push({line:u,leaf:l.leaf,traitImplMember:Fe(l.symbol),callee:{symbol:l.symbol,file:l.relativePath,line:l.startLine}})}i.set(s,a)}return{occurrencesByFile:i}}catch{return null}}var Aa=class{sessions=new WeakMap;getOrCreate(t,n,r){let i=HA(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 HA(e,t){return`${e.config.projectRoot}:${t}-workspace`}import{randomUUID as ON}from"crypto";import{existsSync as jN,readFileSync as BN}from"fs";import{dirname as $N}from"path";import{readFileSync as UA}from"fs";import{join as Na}from"path";var yne=5,bne=5e3,qA="watch.lock",GA="watch-state.json",VA="watch-activity.json",WA="watch-refresh-requests";function Sb(e){return{lockPath:Na(e,qA),statePath:Na(e,GA),activityPath:Na(e,VA),refreshRequestsPath:Na(e,WA)}}function sd(e){try{return zA(JSON.parse(UA(e,"utf8")))}catch{return null}}function zA(e){if(!e||typeof e!="object")return null;let t=e;if(t.version!==1||typeof t.protocolVersion!="number"||typeof t.pid!="number"||!Number.isInteger(t.pid)||t.pid<=0||typeof t.projectRoot!="string"||t.worktreeId!==void 0&&(typeof t.worktreeId!="string"||t.worktreeId.length===0)||typeof t.cliVersion!="string"||!qe(t.startedAt)||!qe(t.heartbeatAt)||!qe(t.lastActivityAt)||!KA(t.watcher)||t.idleDeadlineAt!==void 0&&!qe(t.idleDeadlineAt))return null;if(t.processIdentity!==void 0){let n=ln(t.processIdentity);if(!n||n.pid!==t.pid)return null;t.processIdentity=n}return t.indexGeneration!==void 0&&!/^[a-f0-9]{64}$/.test(t.indexGeneration)||t.lastError!==void 0&&!JA(t.lastError)||t.lastRefresh!==void 0&&!YA(t.lastRefresh)||t.reindexActivity!==void 0&&!XA(t.reindexActivity)||t.refreshRequests!==void 0&&!QA(t.refreshRequests)||t.typescriptSemantic!==void 0&&!ZA(t.typescriptSemantic)||t.typescriptIndex!==void 0&&!eN(t.typescriptIndex)?null:t}function qe(e){return Is(e)}function KA(e){if(!e||typeof e!="object"||!("state"in e))return!1;let t=e;switch(t.state){case"idle":return!0;case"waiting":return Ue(t.changedFiles)&&Ue(t.reindexAt);case"indexing":return Ue(t.startedAt);case"cooldown":return Ue(t.until)&&typeof t.dirty=="boolean";case"draining":return Ue(t.startedAt)&&typeof t.reason=="string";default:return!1}}function JA(e){if(!e||typeof e!="object")return!1;let t=e;return qe(t.at)&&typeof t.message=="string"}function YA(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.trigger?.kind=="string"&&typeof t.result=="string"&&qe(t.startedAt)&&qe(t.completedAt)&&Ue(t.durationMs)}function XA(e){if(!e||typeof e!="object")return!1;let t=e;return!qe(t.windowStartedAt)||!qe(t.windowEndedAt)||!j(t.runs)||!j(t.rebuilt)||!j(t.reused)||!j(t.failed)||!j(t.suppressed)||!Ue(t.estimatedLogicalOutputBytes)||t.estimatedLogicalOutputBytes<0||!t.byTrigger||typeof t.byTrigger!="object"?!1:Object.values(t.byTrigger).every(n=>n===void 0||j(n))}function QA(e){if(!e||typeof e!="object")return!1;let t=e;return j(t.pending)&&j(t.claimed)&&j(t.completed)&&j(t.expired)&&j(t.invalid)&&(t.oldestPendingAt===void 0||qe(t.oldestPendingAt))}function ZA(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.protocolVersion=="number"&&(t.state==="idle"||t.state==="ready"||t.state==="unavailable"||t.state==="error")&&Ue(t.requests)&&Ue(t.sessionsCreated)&&Ue(t.sessionsReused)&&Ue(t.sessionsRefreshed)&&Ue(t.sessionsReplaced)&&Ue(t.projectsCreated)&&(t.lastRequestAt===void 0||qe(t.lastRequestAt))&&(t.lastError===void 0||typeof t.lastError=="string")&&(t.busyUntil===void 0||qe(t.busyUntil))&&(t.mailbox===void 0||xb(t.mailbox))}function eN(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.protocolVersion=="number"&&(t.state==="idle"||t.state==="ready"||t.state==="unavailable"||t.state==="error")&&j(t.requests)&&j(t.sessionsCreated)&&j(t.sessionsReplaced)&&j(t.initializations)&&j(t.programUpdates)&&j(t.documentsEmitted)&&j(t.documentsRemoved)&&(t.lastRequestAt===void 0||qe(t.lastRequestAt))&&(t.lastDurationMs===void 0||Ue(t.lastDurationMs)&&t.lastDurationMs>=0)&&(t.lastError===void 0||typeof t.lastError=="string")&&(t.busyUntil===void 0||qe(t.busyUntil))&&(t.mailbox===void 0||xb(t.mailbox))}function xb(e){if(!e||typeof e!="object")return!1;let t=e;return j(t.pending)&&j(t.inflight)&&j(t.responses)&&j(t.deadLetters)&&j(t.invalid)&&j(t.totalItems)&&Ue(t.totalBytes)&&t.totalBytes>=0&&t.totalItems===t.pending+t.inflight+t.responses+t.deadLetters&&(t.oldestPendingAt===void 0||qe(t.oldestPendingAt))}function Ue(e){return typeof e=="number"&&Number.isFinite(e)}import{performance as V}from"perf_hooks";function pt(e,t,n){if(e.has(t))return e.get(t);let r=n();return e.set(t,r),r}import Cb from"path";function tN(e,t){return e.getReferences().map(n=>{let r=n.getNode();return Oa(r,t)})}function nN(e){let t=e;return typeof t.findReferences=="function"?t.findReferences():[]}function Rb(e,t,n,r){let i=[];for(let o of nN(e))for(let s of tN(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 li(i)}function vb(e,t,n,r){let i=[],o=n?.getStart();for(let s of e.getReferences()){let a=s.getNode();ui(r,a.getSourceFile().getFilePath())===t&&(o!==void 0&&a.getStart()===o||i.push({location:Oa(a,r),node:a}))}return i}function Oa(e,t){let n=e.getSourceFile(),r=n.getLineAndColumnAtPos(e.getStart());return{file:ui(t,n.getFilePath())??n.getBaseName(),line:r.line-1,column:r.column-1}}function Ib(e,t,n){let r=e.getSourceFile(),i=cd(r,e),o=e.getText(),s=new RegExp(`\\b${H(o)}\\b`,"g"),a=r.getFullText().split(`
|
|
311
|
+
`),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 li(c.filter(l=>ui(n,Cb.join(n,l.file))===t))}function ad(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 cd(e,t){return e.getLineAndColumnAtPos(t.getStart()).line-1}function li(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 ui(e,t){let n=Cb.relative(e||process.cwd(),t).replace(/\\/g,"/");return!n||n.startsWith("..")?null:n}function wb(e,t,n,r){let i=rN(t,r);return i.size===0?new Map:iN(e,n,i)}function rN(e,t){let n=new Map;for(let r of Q(e,t)){let i=F(r.symbol)??r.leaf;if(!i)continue;let o=n.get(i);o||(o=[],n.set(i,o)),o.push(r)}return n}function iN(e,t,n){let r=new Map,i=new Map;return t.forEachDescendant(o=>{for(let s of oN(e,o)){let a=n.get(s);if(!a)continue;let c=cd(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 oN(e,t){let n=[],r=i=>{i&&!n.includes(i)&&n.push(i)};if("getNameNode"in t&&typeof t.getNameNode=="function"){let i=t.getNameNode();r(i?.getText())}if("getName"in t&&typeof t.getName=="function"){let i=t.getName();r(i)}return e.Node.isIdentifier(t)&&r(t.getText()),n}var sN=B("ts-definition-leaf-candidates",{clearGroups:["definition-catalog"]});function Eb(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||F(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 Db(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 sN.get(e,t,()=>{let n=new Map;for(let r of Q(e,t)){let i=r.leaf||F(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 md from"path";var Co=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];function Ot(e){let t=e.toLowerCase();return Co.some(n=>t.endsWith(n))}function kb(e,t){let n=new Map,r=null,i=null,o=()=>(i??=M(e,{extensions:Co}),i),s=()=>(r??=E("typescript.source-file-index",()=>aN(e.config.projectRoot,t,o()),()=>({projects:t.length,indexedDocuments:o().length})),r),a=c=>Ot(c)?pt(n,c,()=>{let l=Ro(md.resolve(e.config.projectRoot,c));for(let{project:u,sourceFiles:d}of s()){let m=d.get(l)??null;if(m||(m=u.addSourceFileAtPathIfExists(l)??null,m&&d.set(Ro(m.getFilePath()),m)),m)return{project:u,sourceFile:m}}return null}):null;return{sourceFile:c=>a(c)?.sourceFile??null,sourceFileMatch:a,indexedTypeScriptLikeDocuments:o}}function aN(e,t,n){let r=t.map(({project:i})=>({project:i,sourceFiles:new Map(i.getSourceFiles().map(o=>[Ro(o.getFilePath()),o]))}));for(let i of n){let o=Ro(md.resolve(e,i));for(let s of r){if(s.sourceFiles.has(o))break;let a=s.project.addSourceFileAtPathIfExists(o)??null;if(a){s.sourceFiles.set(Ro(a.getFilePath()),a);break}}}return r}function Ro(e){return md.resolve(e)}function fd(e,t){for(let n of e)if(t===n.name||t.startsWith(`${n.name}/`))return n.name;return null}function Pb(e){let t=`${e.relativeDir}/src`;return[`${t}/index.ts`,`${t}/index.tsx`,`${t}/index.mts`,`${t}/index.cts`]}import{existsSync as vo,readFileSync as cN}from"fs";import Oe from"path";var pd=["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 pd){let a=Oe.join(r,s);if(vo(a))return a}let o=Oe.dirname(r);if(o===r)break;r=o}for(let o of pd){let s=Oe.join(e,o);if(vo(s))return s}return null}function Fb(e){let t=e.config.projectRoot,n=new Set(lN(t,e.config.semantic?.typescript?.tsconfigs)),r=M(e,{includeIgnored:!1,extensions:Co});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=>!Tb(t,i)).sort((i,o)=>i.localeCompare(o))}function lN(e,t=[]){let n=new Set;for(let r of t){let i=Oe.isAbsolute(r)?r:Oe.join(e,r);vo(i)&&n.add(Oe.resolve(i))}for(let r of uN(e))for(let i of pd){let o=Oe.join(r,i);vo(o)&&n.add(Oe.resolve(o))}if(n.size===0){let r=gd(e);r&&n.add(Oe.resolve(r))}return[...n].filter(r=>!Tb(e,r)).sort((r,i)=>r.localeCompare(i))}function uN(e){let t=Oe.join(e,"package.json");if(!vo(t))return[];let n;try{n=JSON.parse(cN(t,"utf8"))}catch{return[]}return(Array.isArray(n.workspaces)?n.workspaces:n.workspaces?.packages??[]).flatMap(i=>tu(e,i))}function Tb(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/")}import{createRequire as dN}from"module";var _b=dN(import.meta.url),Io,ja;function hd(){if(Io!==void 0)return Io;try{Io=_b("ts-morph")}catch{Io=null}return Io}function Ba(){if(ja)return ja;let e=hd();if(!e)return"ts-morph:unavailable";let t="unknown";try{t=_b("ts-morph/package.json").version??"unknown"}catch{}return ja=`ts-morph:${t}:typescript:${e.ts.version}`,ja}function Lb(e,t){return t.map(n=>({tsconfigPath:n,project:new e.Project({tsConfigFilePath:n,skipFileDependencyResolution:!0})}))}function $a(e,t,n){return{language:"typescript",availability:()=>({available:!1,reason:e,tsconfigPath:t,tsconfigPaths:n}),importUsage:()=>[],referencesFor:()=>[],calleesFor:()=>[],signatureFor:()=>null}}function Ha(e,t){let n=new Map(e.map(i=>[i.symbol,i])),r=new Map(e.map(i=>[i.symbolId,[]]));for(let i of t.values())for(let o of i){let s=n.get(o.targetSymbol);s&&r.get(s.symbolId).push(o.location)}for(let[i,o]of r)r.set(i,mN(o));return r}function Nb(e,t,n){let r=Ab(e,t),i=Ab(e,n),o=[...r].filter(d=>!i.has(d)).sort(),s=[...i].filter(d=>!r.has(d)).sort(),a=Mb(e,t),c=Mb(e,n),l=[...a].filter(d=>!c.has(d)).sort(),u=[...c].filter(d=>!a.has(d)).sort();return{passed:o.length===0&&s.length===0,expectedCount:r.size,actualCount:i.size,missing:o,extra:s,callerFiles:{passed:l.length===0&&u.length===0,expectedCount:a.size,actualCount:c.size,missing:l,extra:u}}}function Mb(e,t){let n=new Set;for(let r of e)for(let i of t.get(r.symbolId)??[])i.file!==r.relativePath&&n.add(`${r.symbol}\0${i.file}`);return n}function Ob(e,t,n){let r=new Set(n),i=new Map(n.map(o=>[o,[]]));for(let o of e)for(let s of t.get(o.symbolId)??[])r.has(s.file)&&i.get(s.file).push({targetSymbol:o.symbol,location:s});for(let[o,s]of i)i.set(o,fN(s));return i}function Ab(e,t){let n=new Set;for(let r of e)for(let i of t.get(r.symbolId)??[])n.add(`${r.symbol}\0${i.file}\0${i.line}\0${i.column}`);return n}function mN(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(jb)}function fN(e){let t=new Map;for(let n of e){let{location:r}=n;t.set(`${n.targetSymbol}\0${r.file}\0${r.line}\0${r.column}`,n)}return[...t.values()].sort((n,r)=>n.targetSymbol.localeCompare(r.targetSymbol)||jb(n.location,r.location))}function jb(e,t){return e.file.localeCompare(t.file)||e.line-t.line||e.column-t.column}var pN=32;function Gb(e,t){let n=E("typescript.provider.load",()=>hd());if(!n)return $a("ts-morph is not installed");let r=E("typescript.provider.tsconfig-discovery",()=>Fb(e));if(r.length===0)return $a("no tsconfig found");try{let i=E("typescript.provider.project-bundles",()=>Lb(n,r),()=>({tsconfigs:r.length}));return gN(e,n,i)}catch(i){return $a(i instanceof Error?i.message:String(i),r[0],r)}}function gN(e,t,n,r={}){return E("typescript.provider.construct",()=>new bd(e,t,n),()=>({tsconfigs:n.length,reusedProjects:r.reusedProjects===!0}))}var bd=class{constructor(t,n,r){this.db=t;this.tsMorph=n;this.projects=r;this.workspacePackages=qr(t.config.projectRoot),this.sourceFiles=kb(t,r)}db;tsMorph;projects;language="typescript";importUsageCache=new Map;referencesCache=new Map;calleesCache=new Map;fileCalleesCache=new Map;signatureCache=new Map;definitionNodeCache=new Map;fileDefinitionNodeCache=new Map;indexedDefinitionLeafCache=new Map;compilerCheckerCache=new WeakMap;packageImportReferenceIndex=null;packageExportIndex=null;workspacePackages;sourceFiles;availability(){return{available:!0,tsconfigPath:this.projects[0]?.tsconfigPath,tsconfigPaths:this.projects.map(t=>t.tsconfigPath)}}importUsage(t){return pt(this.importUsageCache,t,()=>{let n=this.sourceFiles.sourceFile(t);if(!n)return[];let r=yN();return E("typescript.import-usage.file",()=>this.importUsageForSourceFile(t,n,r),()=>({file:t,...r}))})}referencesFor(t){return pt(this.referencesCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);return this.referencesForDefinitionNode(t,n)})}referencesForDefinitions(t,n={}){let r=new Map,i=G(),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=>!$b(u));if(a.length>=pN){let u=this.referencesForDefinitionsBySymbolScan(a);for(let d of a){let m=u.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),r.set(d.symbolId,m)}if(s=o.filter(d=>$b(d)),s.length===0)return r}let c=new Map;for(let u of s){let d=c.get(u.relativePath);d?d.push(u):c.set(u.relativePath,[u])}let l=[];for(let[u,d]of c){let m=Hb();E("typescript.references-map.file",()=>{let f=this.definitionNodesForFile(u);for(let p of d){i&&(m.cacheMisses+=1);let g=f.get(p.symbolId)??null;i&&(g?m.nodeHits+=1:m.nodeMisses+=1);try{let y=this.referencesForDefinitionNode(p,g,i?m:void 0);this.referencesCache.set(p.symbolId,y),r.set(p.symbolId,y)}catch{m.preciseSearchFailures+=1,l.push(p)}}},()=>({relativePath:u,definitions:d.length,...Ub(m)}))}if(l.length>0){let u=this.referencesForDefinitionsBySymbolScan(l);for(let d of l){let m=u.get(d.symbolId)??[];this.referencesCache.set(d.symbolId,m),r.set(d.symbolId,m)}}return r}referenceFragmentsForFiles(t){let n=De(this.db).filter(o=>Ot(o.relativePath)),r=t.filter(o=>this.sourceFiles.sourceFile(o)!==null),i=this.referencesForDefinitionsBySymbolScan(n,r);return Ob(n,i,r)}referencesForDefinitionsBySymbolScan(t,n){let r=G(),i=Hb(),o=new Map,s=new Set(t.map(c=>c.symbolId)),a=new Map(t.map(c=>[c.symbolId,c]));for(let c of t)o.set(c.symbolId,[]);return E("typescript.references-map.inverted-scan",()=>{let c=r?V.now():0,l=n?this.packageImportReferencesForFiles(n):this.packageImportReferences();for(let y of t){let h=l.get(y.symbolId)??[];if(h.length>0){let C=o.get(y.symbolId)??[];C.push(...h),o.set(y.symbolId,C)}r&&(i.packageReferenceCount+=h.length)}r&&(i.packageRefsMs+=V.now()-c);let u=new Map,d=new Map,m=this.hierarchyTargetsForDefinitions(t),f=new Set(t.map(y=>y.leaf).filter(Boolean)),p=r?V.now():0;for(let y of n??this.sourceFiles.indexedTypeScriptLikeDocuments()){if(this.db.isIgnored(y))continue;let h=this.sourceFiles.sourceFile(y);h&&(r&&(i.scanFiles+=1),this.addReferencesFromSourceFileScan(h,y,s,a,m,f,u,d,o,r?i:void 0))}r&&(i.scanMs+=V.now()-p);let g=r?V.now():0;this.addHierarchyMemberReferences(t,o,r?i:void 0),r&&(i.hierarchyMs+=V.now()-g);for(let[y,h]of o){let C=li(h);o.set(y,C),r&&(i.referenceCount+=C.length)}},()=>({definitions:t.length,...Ub(i)})),o}addReferencesFromSourceFileScan(t,n,r,i,o,s,a,c,l,u){let d=this.compilerCheckerForSourceFile(t),m=t.compilerNode,f=xN(t),p=g=>{if(this.tsMorph.ts.isIdentifier(g)){if(u&&(u.identifiers+=1),!s.has(g.text)&&!f.has(g.text)){this.tsMorph.ts.forEachChild(g,p);return}let y=this.compilerReferenceSymbol(d,g,u);if(y){let h;a.has(y)?h=a.get(y)??null:(h=this.referenceDefinitionFromCompilerSymbol(y),a.set(y,h)),u&&(h?u.targetHits+=1:u.targetMisses+=1);let C=pt(c,y,()=>this.compilerSymbolKeys(y)),b=null,S=null,x=h&&r.has(h.symbolId)?i.get(h.symbolId):void 0;if(x&&(b=yd(m,g),!Bb(x,n,b))){let v=m.getLineAndCharacterOfPosition(g.getStart(m));S={file:n,line:v.line,column:v.character};let R=l.get(x.symbolId)??[];R.push(S),l.set(x.symbolId,R),u&&(u.requestedHits+=1)}for(let v of C)for(let R of o.get(v)?.values()??[]){if(b??=yd(m,g),Bb(R,n,b))continue;if(!S){let w=m.getLineAndCharacterOfPosition(g.getStart(m));S={file:n,line:w.line,column:w.character}}let D=l.get(R.symbolId)??[];D.push(S),l.set(R.symbolId,D),u&&(u.requestedHits+=1)}}}this.tsMorph.ts.forEachChild(g,p)};p(m)}hierarchyTargetsForDefinitions(t){let n=new Map;for(let r of t){let i=this.nodeForDefinition(r),o=i?.compilerNode;if(!o||!this.isHierarchyMethod(o))continue;let s=o.parent;if(!this.isHierarchyContainer(s))continue;let a=this.compilerCheckerForSourceFile(i.getSourceFile()),c=a.getSymbolAtLocation(o.name);if(c)for(let l of this.hierarchyMemberSymbols(a,s,c))for(let u of this.compilerSymbolKeys(l)){let d=n.get(u)??new Map;d.set(r.symbolId,r),n.set(u,d)}}return n}hierarchyMemberSymbols(t,n,r){let i=new Set,o=new Set,s=(a,c,l)=>{if(!o.has(a)){o.add(a),i.add(c);for(let u of l){let d=u.getProperty(r.name);d&&s(u,d,this.hierarchyAncestorTypesForType(t,u))}}};return s(t.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(t,n)),i}addHierarchyMemberReferences(t,n,r){let i=new Map;for(let o of t){let s=this.nodeForDefinition(o),a=s?.compilerNode;if(!a||!this.isHierarchyMethod(a))continue;let c=a.parent;if(!this.isHierarchyContainer(c))continue;let l=this.compilerCheckerForSourceFile(s.getSourceFile()),u=l.getSymbolAtLocation(a.name);if(!u)continue;let d=a.getSourceFile(),m=d.getLineAndCharacterOfPosition(a.name.getStart(d)),f={definition:o,location:{file:o.relativePath,line:m.line,column:m.character}},p=n.get(o.symbolId)??[];for(let y of this.hierarchyMemberSymbols(l,c,u))if(y!==u)for(let h of this.compilerSymbolLocations(y))p.push(h),r&&(r.hierarchyReferences+=1);n.set(o.symbolId,p);let g=this.hierarchyRootMemberSymbols(l,c,u);for(let y of g){let h=i.get(y)??new Map;h.set(o.symbolId,f),i.set(y,h)}r&&(r.hierarchyDefinitions+=1)}for(let o of i.values())if(!(o.size<2)){r&&(r.hierarchyFamilies+=1);for(let{definition:s}of o.values()){let a=n.get(s.symbolId)??[];for(let c of o.values())c.definition.symbolId!==s.symbolId&&(a.push(c.location),r&&(r.hierarchyReferences+=1));n.set(s.symbolId,a)}}}hierarchyRootMemberSymbols(t,n,r){let i=new Set,o=new Set,s=(a,c,l)=>{if(o.has(a))return;o.add(a);let u=!1;for(let d of l){let m=d.getProperty(r.name);m&&(u=!0,s(d,m,this.hierarchyAncestorTypesForType(t,d)))}if(!u)for(let d of this.compilerSymbolKeys(c))i.add(d)};return s(t.getTypeAtLocation(n),r,this.hierarchyAncestorTypes(t,n)),i}compilerSymbolKeys(t){return(t.declarations??[]).map(n=>{let r=n.getSourceFile();return`${r.fileName}\0${n.getStart(r)}\0${t.name}`})}compilerSymbolLocations(t){let n=[];for(let r of t.declarations??[]){let i=r.getSourceFile(),o=ui(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 pt(this.calleesCache,t.symbolId,()=>pt(this.fileCalleesCache,t.relativePath,()=>this.calleeMapForFile(t.relativePath)).get(t.symbolId)??[])}calleesForDefinitions(t){let n=new Map,r=new Map;for(let i of t){let o=r.get(i.relativePath);o?o.push(i):r.set(i.relativePath,[i])}for(let[i,o]of r){let s=this.fileCalleesCache.get(i),a=new Set(o.map(l=>l.symbolId)),c=s??this.calleeMapForFile(i,a);for(let l of o){let u=c.get(l.symbolId)??[];this.calleesCache.set(l.symbolId,u),n.set(l.symbolId,u)}}return n}referencesForDefinitionNode(t,n,r){let i=r?V.now():0,o=this.packageImportReferencesForDefinition(t);if(r&&(r.packageRefsMs+=V.now()-i,r.packageReferenceCount+=o.length),!n)return o;let s=r?V.now():0,a=Rb(n,t,o,this.db.config.projectRoot);return r&&(r.semanticRefsMs+=V.now()-s,r.referenceCount+=a.length),a}signatureFor(t){return pt(this.signatureCache,t.symbolId,()=>{let n=this.nodeForDefinition(t);if(!n||!this.tsMorph.Node.isFunctionDeclaration(n)&&!this.tsMorph.Node.isMethodDeclaration(n)&&!this.tsMorph.Node.isArrowFunction(n)&&!this.tsMorph.Node.isFunctionExpression(n)&&!this.tsMorph.Node.isConstructorDeclaration(n))return null;let r=n.getType().getCallSignatures()[0];if(!r)return null;let i=r.getParameters().map(s=>{let a=s.getDeclarations()[0],c=a?s.getTypeAtLocation(a).getText(a):s.getValueDeclaration()?.getType().getText()??"unknown";return qb(c)}),o=r.getReturnType().getText(n);return`(${i.join(",")})=>${qb(o)}`})}importUsageForSourceFile(t,n,r){let i=[],o=new Map;for(let s of n.getImportDeclarations()){r.declarations+=1;let a=tt(this.db,t,s.getModuleSpecifierValue()),c=s.getImportClause()?.isTypeOnly()??!1;for(let l of Sd(s)){r.entries+=1;let u=c?null:l.identifier?.getSymbol()?.compilerSymbol??null;!c&&l.identifier&&(u?r.bindingSymbols+=1:r.missingBindingSymbols+=1);let d={sourcePath:a,entry:l,typeOnlyDeclaration:c,bindingSymbol:u,references:[]};if(i.push(d),c||!l.localName||!u)continue;let m=o.get(l.localName);m?m.push(d):o.set(l.localName,[d])}}return o.size>0&&n.forEachDescendant(s=>{if(s.getKindName()!=="Identifier")return;let a=o.get(s.getText());if(!a||bN(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:Oa(s,this.db.config.projectRoot),node:s}),r.matchedReferences+=1;break}}}),i.map(s=>s.typeOnlyDeclaration?hN(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 vb(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=>!ad(c.node)),s=i.some(c=>ad(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=fd(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,li(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,li(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=fd(this.workspacePackages,i.getModuleSpecifierValue());if(!o)return;let s=n.get(o);if(s)for(let a of Sd(i)){if(a.kind!=="named"||!a.identifier)continue;let c=s.get(a.importedName);if(!c||c.size===0)continue;let l=Ib(a.identifier,r,this.db.config.projectRoot);l.length>0&&IN(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 Pb(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?tt(this.db,n,a):n;if(!c||!c.startsWith(`${t.relativeDir}/src/`))continue;let l=s.getNamedExports();if(l.length===0){if(s.isNamespaceExport())continue;this.collectPackageExports(t,c,r,i);continue}for(let u of l){let d=u.getNameNode().getText(),m=u.getAliasNode()?.getText()??d,f=this.indexedDefinitionByLeaf(c,d);if(!f)continue;let p=r.get(m);p||(p=new Set,r.set(m,p)),p.add(f.symbolId)}}}indexedDefinitionByLeaf(t,n){return pt(this.indexedDefinitionLeafCache,t,()=>Db(this.db,t)).get(n)??null}nodeForDefinition(t){return pt(this.definitionNodeCache,t.symbolId,()=>this.definitionNodesForFile(t.relativePath).get(t.symbolId)??null)}definitionNodesForFile(t){return pt(this.fileDefinitionNodeCache,t,()=>{let n=this.sourceFiles.sourceFile(t);return n?wb(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?V.now():0,s=t.declarations??[];n&&(n.declarationsMs+=V.now()-o,n.declarationChecks+=s.length);for(let a of s){let c=n?V.now():0,l=a.getSourceFile(),u=ui(this.db.config.projectRoot,l.fileName),d=l.getLineAndCharacterOfPosition(a.getStart(l)).line;if(n&&(n.declarationLocationMs+=V.now()-c),!u||this.db.isIgnored(u))continue;let m=n?V.now():0,f=this.compilerDeclarationName(a),p=r?ud(this.db,u,d,i)??(f&&f!==i?ud(this.db,u,d,f):null):Eb(this.db,u,d,i);if(n&&(n.indexedLookupMs+=V.now()-m),p)return{symbolId:p.symbolId,symbol:p.symbol,file:p.relativePath,line:p.startLine}}return null}compilerDeclarationName(t){let n=t.name;return n&&this.tsMorph.ts.isIdentifier(n)?n.text:null}calleeMapForFile(t,n){let r=G(),i=0,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=r?RN():void 0;return E("typescript.callee-map.file",()=>{let f=r?V.now():0,p=this.sourceFiles.sourceFile(t);if(r&&(c=Math.round(V.now()-f)),!p)return new Map;let g=r?V.now():0,y=Q(this.db,t).sort((D,w)=>D.startLine-w.startLine||w.endLine-D.endLine);if(r&&(l=Math.round(V.now()-g)),i=y.length,y.length===0)return new Map;let h=new Map,C=r?V.now():0,b=this.compilerCheckerForSourceFile(p),S=p.compilerNode;r&&(u=Math.round(V.now()-C));let x=new Map,v=D=>{if(this.tsMorph.ts.isCallExpression(D)||this.tsMorph.ts.isNewExpression(D)){r&&(o+=1);let w=this.semanticCalleeForCallNode(b,S,y,D,x,n,m);w&&(r&&(s+=1),SN(h,w.callerId,w.target))}this.tsMorph.ts.forEachChild(D,v)},R=r?V.now():0;v(S),r&&(d=Math.round(V.now()-R));for(let[D,w]of h)h.set(D,wN(w));return a=h.size,h},()=>({relativePath:t,definitions:i,callNodes:o,resolvedCallees:s,outputRows:a,requestedDefinitions:n?.size??i,sourceFileLookupMs:c,definitionsLoadMs:l,checkerLookupMs:u,traversalMs:d,...m?vN(m):{}}))}semanticCalleeForCallNode(t,n,r,i,o,s,a){let c=a?V.now():0,l=CN(r,yd(n,i));if(a&&(a.callerLookupMs+=V.now()-c),!l)return null;if(s&&!s.has(l.symbolId))return a&&(a.skippedUnrequestedCallers+=1),null;let u=i.expression,d=this.compilerSymbolForExpression(t,u,a),m=null;if(d)if(a&&(a.targetSymbolHits+=1),o.has(d))a&&(a.compilerSymbolCacheHits+=1),m=o.get(d)??null;else{a&&(a.compilerSymbolCacheMisses+=1);let f=a?V.now():0;m=this.definitionFromCompilerSymbol(d,a),a&&(a.targetLookupMs+=V.now()-f),o.set(d,m)}else a&&(a.targetMisses+=1);return m?{callerId:l.symbolId,target:{symbol:m.symbol,file:m.file,line:m.line}}:null}compilerSymbolForExpression(t,n,r){let i=r?V.now():0,o=t.getSymbolAtLocation(n);if(r&&(r.expressionSymbolMs+=V.now()-i),o)return o;r&&(r.typeFallbacks+=1);let s=r?V.now():0,a=t.getTypeAtLocation(n).getSymbol();return r&&(r.typeSymbolMs+=V.now()-s),a}compilerCheckerForSourceFile(t){let n=t.getProject(),r=this.compilerCheckerCache.get(n);return r||(r=n.getTypeChecker().compilerObject,this.compilerCheckerCache.set(n,r)),r}};function Sd(e){let t=[],n=e.getDefaultImport();n&&t.push({identifier:n,importedName:"default",localName:n.getText(),kind:"default",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});let r=e.getNamespaceImport();r&&t.push({identifier:r,importedName:"*",localName:r.getText(),kind:"namespace",isTypeOnly:e.getImportClause()?.isTypeOnly()??!1});for(let i of e.getNamedImports()){let o=i.getNameNode(),a=i.getAliasNode()??(o.getKindName()==="Identifier"?o:null);t.push({identifier:a,importedName:o.getText(),localName:a?.getText()??o.getText(),kind:"named",isTypeOnly:i.isTypeOnly()||(e.getImportClause()?.isTypeOnly()??!1)})}return t.length===0&&t.push({identifier:null,importedName:"*",localName:null,kind:"side-effect",isTypeOnly:!1}),t}function hN(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 yN(){return{declarations:0,entries:0,bindingSymbols:0,missingBindingSymbols:0,scannedIdentifiers:0,symbolLookups:0,matchedReferences:0,fallbackEntries:0}}function bN(e){for(let t=e;t;t=t.getParent())if(t.getKindName()==="ImportDeclaration")return!0;return!1}function SN(e,t,n){let r=e.get(t);r||(r=[],e.set(t,r)),r.push(n)}function xN(e){let t=new Set;for(let n of e.getImportDeclarations())for(let r of Sd(n))r.localName&&t.add(r.localName);return t}function CN(e,t){let n=null;for(let r of e)t<r.startLine||t>r.endLine||(!n||r.startLine>=n.startLine)&&(n=r);return n}function yd(e,t){return e.getLineAndCharacterOfPosition(t.getStart(e)).line}function Bb(e,t,n){return t===e.relativePath&&n>=e.startLine&&n<=e.endLine}function $b(e){return e.symbol.includes("#")?pe(e.symbol)==="type"&&e.relativePath.endsWith(".d.ts"):!1}function RN(){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 vN(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 Hb(){return{cacheHits:0,cacheMisses:0,nodeHits:0,nodeMisses:0,scanFiles:0,identifiers:0,symbolLookups:0,aliasResolutions:0,targetHits:0,targetMisses:0,requestedHits:0,scanMs:0,packageRefsMs:0,semanticRefsMs:0,packageReferenceCount:0,referenceCount:0,preciseSearchFailures:0,hierarchyDefinitions:0,hierarchyFamilies:0,hierarchyReferences:0,hierarchyMs:0}}function Ub(e){return{...e,scanMs:Math.round(e.scanMs),packageRefsMs:Math.round(e.packageRefsMs),semanticRefsMs:Math.round(e.semanticRefsMs),hierarchyMs:Math.round(e.hierarchyMs)}}function IN(e,t,n){for(let r of t){let i=e.get(r)??[];i.push(...n),e.set(r,i)}}function wN(e){let t=new Set,n=[];for(let r of e){let i=`${r.symbol}|${r.file}|${r.line}`;t.has(i)||(t.add(i),n.push(r))}return n}function qb(e){return e.replace(/\s+/g," ").replace(/\bimport\("[^"]+"\)\./g,"").trim()}import{join as AN}from"path";import{createHash as EN}from"crypto";import{existsSync as wo,readFileSync as Eo,statSync as vd}from"fs";import{basename as DN,dirname as Ua,join as On}from"path";var hr=1,Id=1,Do=".scipquery-generations",qa="manifest.json";function gt(e){return On(Ua(e),Do)}function di(e){try{let t=JSON.parse(Eo(On(gt(e),"state.json"),"utf8"));return TN(t)?t:null}catch{return null}}function Ga(e,t){return Va(gt(e),t)}function Va(e,t){try{let n=JSON.parse(Eo(On(e,t,qa),"utf8"));return FN(n,t)?n:null}catch{return null}}function wd(e){let t=di(e.dbPath);if(t){let n=kN(e,t.currentGeneration);if(n)return n;if(t.artifactSet==="immutable-v1")throw new Error(`Published SQLite generation ${t.currentGeneration} is missing or invalid.`)}if(wo(On(Ua(e.dbPath),"index.lock")))throw new Error("Legacy SQLite publication is in progress; retry after the reindex lock is released.");return PN(e,t?.currentGeneration)}function Vb(e){let t=di(e);if(t)return t.currentGeneration;try{let n=On(Ua(e),"meta.json"),r=wo(n)?Eo(n,"utf8"):void 0;return Wb(e,r)}catch{return null}}function jn(e){return Pp(Tt(e))??e}function kN(e,t){try{let n=On(gt(e.dbPath),t),r=Ga(e.dbPath,t);if(!r)return null;let i=xd(n,r.database),o=r.index?xd(n,r.index):void 0,s=r.metadata?xd(n,r.metadata):void 0;return!Cd(i,r.database)||r.index&&(!o||!Cd(o,r.index))||r.metadata&&(!s||!Cd(s,r.metadata))?null:{identity:t,databasePath:i,...o?{indexPath:o}:{},...s?{metadataPath:s,metadataRaw:Eo(s,"utf8")}:{},source:"immutable"}}catch{return null}}function PN(e,t){let n=dn(e.dbPath),r=On(Ua(e.dbPath),"meta.json"),i=wo(r)?Eo(r,"utf8"):void 0,o=wo(e.indexPath)?e.indexPath:void 0;return{identity:t??Wb(e.dbPath,i),databasePath:e.dbPath,...o?{indexPath:o}:{},...i===void 0?{}:{metadataPath:r,metadataRaw:i},source:"legacy",databaseFileIdentity:n}}function Wb(e,t){let n=EN("sha256").update("sqlite-generation-legacy-v1\0");return t!==void 0&&n.update(jn(t)),n.update(`\0${dn(e)}`),n.digest("hex")}function dn(e){let t=vd(e);return`${t.dev}:${t.ino}:${t.size}:${t.mtimeMs}`}function xd(e,t){if(DN(t.file)!==t.file||t.file==="."||t.file==="..")throw new Error("SQLite generation manifest contains an unsafe artifact path");return On(e,t.file)}function Cd(e,t){return wo(e)&&vd(e).isFile()&&vd(e).size===t.size}function FN(e,t){return e.version===Id&&e.identity===t&&Rd(e.database)&&(e.index===void 0||Rd(e.index))&&(e.metadata===void 0||Rd(e.metadata))}function Rd(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.file=="string"&&!!t.file&&Number.isSafeInteger(t.size)&&(t.size??-1)>=0&&typeof t.sha256=="string"&&/^[a-f0-9]{64}$/.test(t.sha256)}function TN(e){return e.version===hr&&typeof e.currentGeneration=="string"&&!!e.currentGeneration&&typeof e.publishedAt=="string"&&Number.isFinite(Date.parse(e.publishedAt))&&(e.artifactSet===void 0||e.artifactSet==="immutable-v1")&&_N(e.stableMirrors)&&LN(e.previousGeneration)&&MN(e.publication)}function _N(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e;return typeof t.databaseFileIdentity=="string"&&!!t.databaseFileIdentity&&(t.indexFileIdentity===void 0||typeof t.indexFileIdentity=="string"&&!!t.indexFileIdentity)}function LN(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e;return typeof t.generationIdentity=="string"&&!!t.generationIdentity&&typeof t.databasePath=="string"&&!!t.databasePath&&(t.metadataPath===void 0||typeof t.metadataPath=="string"&&!!t.metadataPath)}function MN(e){if(e===void 0)return!0;if(!e||typeof e!="object")return!1;let t=e,n=[t.converterDurationMs,t.affectedDocumentCount,t.changedDocumentCount,t.producerDurationMs,t.materializationDurationMs,t.patchDurationMs].filter(r=>r!==void 0);return(t.mode==="incremental"||t.mode==="full")&&t.validation==="passed"&&t.converterDurationMs!==void 0&&n.every(r=>typeof r=="number"&&Number.isFinite(r)&&r>=0)&&(t.scipCompanion===void 0||t.scipCompanion==="current"||t.scipCompanion==="deferred")&&(t.typescriptOverlayGeneration===void 0||typeof t.typescriptOverlayGeneration=="string"&&!!t.typescriptOverlayGeneration)&&(t.scipCompanion!=="deferred"||!!t.typescriptOverlayGeneration)&&(t.fallbackReason===void 0||typeof t.fallbackReason=="string")}var Wa=3;var NN="typescript-semantic";function zb(e){let t=AN(e,NN),n=wa(t);return{...n,requestDir:n.legacyRequestDir}}function Kb(e){return Vb(e)}var HN=12e4,UN=5;function Xb(e,t,n={}){let r=new Ed(e,n),i=null,o=null,s=process.env.SCIP_QUERY_SKIP_WATCH_SERVICE==="1",a=()=>(i??=Gb(e,t),i),c=(d,m,f)=>{if(s)return f();try{return m(r.request(d))}catch{return s=!0,f()}},l=(d,m)=>c({kind:"references",definitions:[...d],...m?.exact?{exact:!0}:{}},f=>Yb(f),()=>a().referencesForDefinitions?.(d,m)??new Map(d.map(f=>[f.symbolId,a().referencesFor(f)]))),u=d=>c({kind:"callees",definitions:[...d]},m=>Yb(m),()=>a().calleesForDefinitions?.(d)??new Map(d.map(m=>[m.symbolId,a().calleesFor(m)])));return{language:"typescript",availability:()=>(o??=c({kind:"availability"},VN,()=>a().availability()),o),importUsage:d=>c({kind:"import-usage",file:d},m=>m,()=>a().importUsage(d)),referencesFor:d=>l([d]).get(d.symbolId)??[],referencesForDefinitions:l,referenceFragmentsForFiles:d=>c({kind:"reference-fragments",files:[...d]},m=>GN(m),()=>a().referenceFragmentsForFiles?.(d)??new Map),calleesFor:d=>u([d]).get(d.symbolId)??[],calleesForDefinitions:u,signatureFor:d=>c({kind:"signature",definition:d},WN,()=>a().signatureFor(d)),dispose:()=>i?.dispose?.()}}var Ed=class{constructor(t,n={}){this.db=t;this.runtime=n.runtime??KN,this.timeoutMs=n.timeoutMs??zN(),this.mailboxLimits=n.mailboxLimits??{},this.cacheDir=$N(t.config.dbPath),this.projectRoot=_t(t.config.projectRoot)}db;runtime;timeoutMs;cacheDir;projectRoot;mailboxLimits;request(t){let n=Sb(this.cacheDir),r=zb(this.cacheDir),i=sd(n.statePath);if(!Jb(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??we)()+this.timeoutMs,l=tg(),u=ii("typescript-semantic-v3",{generation:o,profileEnvironment:l,request:t}),d=mr(u),m=Ea(r,{mailboxVersion:Nn,operationKey:u,clientId:this.runtime.randomId(),enqueuedAtMs:s,deadlineAtMs:a,protocolVersion:Wa,id:d,generation:o,profileEnvironment:l,request:t},{nowMs:s,limits:this.mailboxLimits});for(;(this.runtime.monotonicNow??we)()<=c;){if(jN(m.responsePath))return qN(BN(m.responsePath,"utf8"),d,o,u);let f=sd(n.statePath);if(!Jb(f,this.projectRoot,this.runtime))throw new Error("TypeScript semantic service stopped while processing a request.");this.runtime.sleep(UN)}throw new Error(`TypeScript semantic service timed out after ${this.timeoutMs}ms.`)}};function Jb(e,t,n){let r=e?.processIdentity?n.readProcessIdentity?.(e.pid):null;return e!==null&&e.projectRoot===t&&e.typescriptSemantic?.protocolVersion===Wa&&n.isProcessAlive(e.pid)&&(!e.processIdentity||r!=null&&ft(e.processIdentity,r))}function qN(e,t,n,r){let i=JSON.parse(e);if(i.protocolVersion!==Wa||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 Yb(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid numeric map.");return new Map(e)}function GN(e){if(!Array.isArray(e))throw new Error("TypeScript semantic service wrote an invalid string map.");return new Map(e)}function VN(e){if(!e||typeof e!="object"||typeof e.available!="boolean")throw new Error("TypeScript semantic service wrote invalid availability.");return e}function WN(e){if(e!==null&&typeof e!="string")throw new Error("TypeScript semantic service wrote an invalid signature.");return e}function zN(){let e=Number(process.env.SCIP_TYPESCRIPT_SEMANTIC_TIMEOUT_MS);return Number.isInteger(e)&&e>0?e:HN}var KN={now:Date.now,monotonicNow:we,randomId:ON,sleep(e){let t=new Int32Array(new SharedArrayBuffer(4));Atomics.wait(t,0,0,e)},isProcessAlive:Ln,readProcessIdentity:Rt};var Qb=new Aa;Cn({name:"semantic-provider",groups:["semantic-provider"],clearAll:e=>Qb.clear(e)});function yr(e,t){let n=_e(t)??"typescript";return Qb.getOrCreate(e,n,()=>n==="rust"?gb(e.config.projectRoot,{sourceImportUsageResolver:{importUsageFacts:r=>oy(e,r)},calleeSymbolResolver:iy(e),sourceZeroCalleeOracle:r=>JN(e,r),scipOccurrenceCalleeOracle:r=>bb(e,r)}):Xb(e,t))}function _e(e){return e?N(e)==="rust"?"rust":Ot(e)?"typescript":null:"typescript"}function JN(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}import{existsSync as YN,readFileSync as XN}from"fs";import{resolve as QN}from"path";var ZN=/^[A-Za-z_][A-Za-z0-9_]*$/,Zb=/\bDefault::default\b/g,e0=/^\.\.\s*Default::default\b/;function eS(e,t){let n=new Map,r=new Map;for(let i of t){let o=Dd(e,i,r);o!==null&&n.set(i.symbolId,o)}return n}function Dd(e,t,n=new Map){let r=n0(t.symbol);if(!r)return null;let i=Qr(e,[t.symbolId]);if(i.length===0)return null;let o=new RegExp(`(^|[^A-Za-z0-9_])${H(r)}::default\\b`,"g"),s=new RegExp(`(^|[^A-Za-z0-9_])${H(r)}\\s*$`),a=t0(e,t.symbolId),c=[];for(let l of i){let u=r0(e,l.relative_path,n);if(u===null)return null;let d=u.split(/\r?\n/),m=0,f=[],p=0;for(let g=l.chunk_start;g<=l.chunk_end&&g<d.length;g+=1){let h=d[g]??"",C=new Set;o.lastIndex=0;let b;for(;b=o.exec(h);)c.push({file:l.relative_path,line:g,column:b.index+b[1].length+r.length+2}),p+=1;for(let S=0;S<h.length;S+=1){let x=e0.exec(h.slice(S));if(x){if(a&&f.includes(m)){let R=S+x[0].lastIndexOf("default");c.push({file:l.relative_path,line:g,column:R}),C.add(R),p+=1}S+=x[0].length-1;continue}let v=h[S];if(v==="{"){let R=s.test(h.slice(0,S));m+=1,R&&f.push(m);continue}if(v==="}")for(m=Math.max(0,m-1);f.length>0&&f[f.length-1]>m;)f.pop()}for(Zb.lastIndex=0;b=Zb.exec(h);){let S=b.index+9;if(!C.has(S))return null}}if(p===0)return null}return Da(c)}function t0(e,t){return e.get("SELECT 1 AS present FROM mentions WHERE symbol_id = ? AND role = 1 LIMIT 1",t)?.present===1}function n0(e){let t=/impl#\[([^\]]+)\]\[Default\]default\(\)\./.exec(e)?.[1]??null;return!t||!ZN.test(t)?null:t}function r0(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:i0(e,t);return n.set(t,i),i}function i0(e,t){let n=QN(e.config.projectRoot,t);if(!YN(n))return null;try{return XN(n,"utf8")}catch{return null}}function Ka(e){let t=za(e.projectFiles),n=new Set(t),r=new Map(e.snapshot.files.map(d=>[d.path,d])),i=e.snapshot.files.filter(d=>{let m=Cl(d.path,["typescript"]);return m==="config"||m==="ambient"}).map(d=>d.path),o=za([...t,...i]),s=o.find(d=>!r.has(d)),a=new Set(e.snapshot.files.map(d=>d.path)).size!==e.snapshot.files.length,c=!s&&o.some(d=>tS(r.get(d))),l=Ce(JSON.stringify({pnpmWorkspaces:e.snapshot.pnpmWorkspaces,typescriptProjectMode:e.snapshot.typescriptProjectMode,typescriptProjects:za(e.snapshot.typescriptProjects),membership:t})),u=new Map;return{identityFor(d,m){if(!n.has(d))return mi("target-outside-project");if(a)return mi("duplicate-input-path");if(s)return mi("missing-input-fingerprint");if(c)return mi("unreadable-input");let f=[],p,g;if(e.graph===null)f.push("dependency-graph-unavailable"),g="whole-project",p=o;else{let C=s0(d,e.graph,u);if(C.find(S=>!r.has(S)))return mi("missing-input-fingerprint");if(p=za([...C,...i]),p.some(S=>tS(r.get(S))))return mi("unreadable-input");g="dependency-closure"}let y=p.map(C=>a0(r.get(C)));return{version:1,key:Ce(JSON.stringify({version:1,engineIdentity:e.engineIdentity,schemaVersion:m,projectIdentity:l,inputs:y})),mode:g,inputFiles:p,reasons:f}}}}function o0(e,t){let n=new Set,r=[e];for(let i=0;i<r.length;i+=1){let o=r[i];if(!(o===void 0||n.has(o))){n.add(o);for(let s of[...t.get(o)??[]].sort())n.has(s)||r.push(s)}}return[...n].sort()}function s0(e,t,n){let r=n.get(e);if(r)return r;let i=o0(e,t);return n.set(e,i),i}function a0(e){return{path:e.path,size:e.size,hash:e.hash}}function tS(e){return e.size<0||e.hash==="unreadable"}function mi(e){return{version:1,key:null,mode:"unkeyed",inputFiles:[],reasons:[e]}}function za(e){return[...new Set(e)].sort()}var c0=Z("typescript-semantic-identity-context",{clearGroups:["whole-project"]});function Bn(e,t,n){let r=c0.get(e,()=>l0(e));if(!r)return null;let i=`${n}\0${t}`,o=r.identities.get(i);if(o)return o;let s=r.builder.identityFor(t,n);return r.identities.set(i,s),s}function ko(e){return M(e,{includeIgnored:!1}).filter(Ot).sort()}function l0(e){try{if(!e.generation.metadataRaw)return null;let t=Tt(e.generation.metadataRaw);if(t.kind!=="legacy"&&t.kind!=="supported"||!t.capabilities.usableForEvidenceCache)return null;let n=Ep(t.metadata.fingerprint);return n?{builder:Ka({projectFiles:ko(e),snapshot:n,graph:ae(e),engineIdentity:Ba()}),identities:new Map}:null}catch{return null}}var kd="typescript-reference-fragment-v2",Ya=ce({kind:"typescript-reference-fragments",invalidation:X("typescript-reference-fragments"),serialize:e=>JSON.stringify(e),deserialize:d0});function yie(e,t,n,r=e){let i=ko(e),o=Ka({projectFiles:i,snapshot:t,graph:ae(e),engineIdentity:Ba()}),s=[...n].map(([a,c])=>({relativePath:a,contentHash:o.identityFor(a,kd).key,value:[...c]}));if(s.some(a=>a.contentHash===null))throw new Error("TypeScript reference fragment identity is unavailable for an affected document.");return Ya.writeBatch(r,s.map(a=>({...a,contentHash:a.contentHash}))),s.length}function Pd(e,t,n,r){let i=t.filter(s=>Ot(s.relativePath));if(i.length===0)return Ja("no TypeScript definitions");let o=Ja("shadow did not run");return E("typescript.reference-fragments.shadow",()=>{try{let s=r(i[0].relativePath);if(!s.availability().available||!s.referenceFragmentsForFiles)return o=Ja("TypeScript reference fragment provider is unavailable"),o;let a=ko(e),c=new Set(a),l=s.referenceFragmentsForFiles(a),u=Ha(i,l),d=Nb(i,u0(n,c),u);if(!d.passed)return o={state:"failing",files:a.length,keyedFiles:0,writtenFiles:0,...d},o;let m=[];for(let f of a){let p=Bn(e,f,kd);p?.key&&m.push({relativePath:f,contentHash:p.key,value:l.get(f)??[]})}return Ya.writeBatch(e,m),o={state:"passing",files:a.length,keyedFiles:m.length,writtenFiles:m.length,...d},o}catch(s){return o=Ja(s instanceof Error?s.message:String(s)),o}},()=>({...o}))}function u0(e,t){return new Map([...e].map(([n,r])=>[n,r.filter(i=>t.has(i.file))]))}function Fd(e,t,n){if(t.length===0)return{references:new Map,files:0,cacheHits:0,cacheMisses:0,computedFiles:0};let r="fallback",i=0,o=0,s=0,a=0;return E("typescript.reference-fragments.materialize",()=>{try{let c=ko(e);i=c.length;let l=new Map,u=new Map,d=[];for(let p of c){let g=Bn(e,p,kd);if(!g?.key)return null;l.set(p,g.key);let y=Ya.read(e,p,g.key);y===null?(s+=1,d.push(p)):(o+=1,u.set(p,y))}if(s===0)return r="hit",{references:Ha(t,u),files:i,cacheHits:o,cacheMisses:s,computedFiles:a};let m=n(t[0].relativePath);if(!m.availability().available||!m.referenceFragmentsForFiles)return null;let f=m.referenceFragmentsForFiles(d);if(d.some(p=>!f.has(p)))return null;a=f.size,Ya.writeBatch(e,d.map(p=>({relativePath:p,contentHash:l.get(p),value:f.get(p)??[]})));for(let[p,g]of f)u.set(p,g);return r="computed",{references:Ha(t,u),files:i,cacheHits:o,cacheMisses:s,computedFiles:a}}catch{return null}},()=>({state:r,files:i,cacheHits:o,cacheMisses:s,computedFiles:a}))}function Ja(e){return{state:"unavailable",files:0,keyedFiles:0,writtenFiles:0,expectedCount:0,actualCount:0,missing:[],extra:[],reason:e}}function d0(e){try{let t=JSON.parse(e);return!Array.isArray(t)||!t.every(m0)?null:t}catch{return null}}function m0(e){if(!e||typeof e!="object")return!1;let t=e,n=t.location;return typeof t.targetSymbol=="string"&&!!n&&typeof n.file=="string"&&typeof n.line=="number"&&typeof n.column=="number"}var f0="typescript-import-usage-v1",p0="typescript-signatures-v1",Td=Z("semantic-prefetched-callees",{clearGroups:["whole-project","source-file","semantic-provider"]}),nS=nr({kind:"semantic-import-usage",invalidation:X("semantic-import-usage"),serialize:e=>JSON.stringify(e),deserialize:fS}),rS=nr({kind:"semantic-signatures",invalidation:X("semantic-signatures"),serialize:e=>JSON.stringify(e),deserialize:v0}),iS=ce({kind:"typescript-import-usage",invalidation:X("typescript-import-usage"),serialize:e=>JSON.stringify(e),deserialize:fS}),oS=ce({kind:"typescript-signatures",invalidation:X("typescript-signatures"),serialize:e=>JSON.stringify(e),deserialize:I0});function Ye(e){let t=new Map,n=new Set;return{capability:(r,i)=>pS(e,r,i),importUsage:r=>h0(e,r),references:r=>cS(e,r),materializeReferences:(r,i)=>uS(e,r,t,n,i),callerMap:r=>y0(e,r,t,n),calleeMap:r=>x0(e,r),signature:r=>C0(e,r)}}function g0(e,t){if(t.size===0)return;let n=Td.get(e,()=>new Map);for(let[r,i]of t)n.set(r,[...i])}function aS(e,t){if(!Td.has(e))return{hits:[],misses:[...t]};let n=Td.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 Fo(e,t){return Ye(e).importUsage(t)}function h0(e,t){if(_e(t)==="typescript"){let o="fallback",s=0,a=0,c=0,l=0;return E("typescript.import-usage.materialize",()=>{let u=Bn(e,t,f0);if(u?.key){s=1;let m=iS.read(e,t,u.key);if(m)return o="hit",a=1,m;c=1;let f=jt(e,t);if(!f)return o="unavailable",[];let p=f.importUsage(t);return iS.write(e,t,u.key,p),o="computed",p}l=1;let d=jt(e,t);return d?(o="direct-fallback",d.importUsage(t)):(o="unavailable",[])},()=>({state:o,eligible:s,cacheHits:a,cacheMisses:c,fallbacks:l}))}let n=mS(e,"semantic-import-usage",t);if(n){let o=nS.read(e,t,n);if(o)return o}let r=jt(e,t);if(!r)return[];let i=r.importUsage(t);return n&&nS.write(e,t,n,i),i}function Xa(e,t){return Ye(e).references(t)}function cS(e,t){let n=Dd(e,t);if(n)return n;let r=_y(e,t);if(r)return r;let i=jt(e,t.relativePath);return i?i.referencesFor(t):[]}function $n(e,t){return Ye(e).callerMap(t)}function lS(e,t){let n=new Map,r=new Map;for(let i of t){if(_e(i.relativePath)==="typescript"){let o=jt(e,i.relativePath);if(!o)continue;let s=r.get(o)??[];s.push(i),r.set(o,s);continue}_d(e,n,i,cS(e,i))}for(let[i,o]of r){let s=Fd(e,o,c=>yr(e,c)),a=s?.references??(i.referencesForDefinitions?i.referencesForDefinitions(o,{exact:!0}):new Map(o.map(c=>[c.symbolId,i.referencesFor(c)])));!s&&G()&&Pd(e,o,a,c=>yr(e,c));for(let c of o)_d(e,n,c,a.get(c.symbolId)??[])}return n}function y0(e,t,n=new Map,r=new Set){let i=new Map,o=uS(e,t,n,r),s=0;return E("semantic.callers.from-references",()=>{for(let a of t)s+=_d(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 uS(e,t,n,r,i={}){let o=Ne(e),s=[],a=[],c=[],l=0,u=0,d=0,m=0,f=0,p=0,g=0,y=0,h=0,C=0,b=0,S=0,x=[],v=new Map,R=t.filter(w=>_e(w.relativePath)==="typescript"&&!n.has(w.symbolId)&&!r.has(w.symbolId)),D=Fd(e,R,w=>yr(e,w));if(D){h=R.length,C=D.cacheHits,b=D.cacheMisses,S=D.computedFiles;for(let w of R)n.set(w.symbolId,D.references.get(w.symbolId)??[])}if(E("semantic.references.cache-scan",()=>{for(let[w,k]of xa(t)){let L=[];for(let _ of k)n.has(_.symbolId)?u+=1:r.has(_.symbolId)?y+=1:L.push(_);if(L.length===0){g+=1;continue}let ne=b0(e,o,w);if(!ne){for(let _ of L)_e(_.relativePath)||(l+=1),c.push(_);continue}p+=1;let ee=Bp(e,w,ne);for(let _ of L){let ue=ee.get(_.symbol)??null;if(ue!==null){let re=S0(ue);if(re){d+=1,n.set(_.symbolId,re);continue}m+=1}a.push({definition:_,cacheFingerprint:ne})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:l,cacheHits:d,parseFailures:m,misses:a.length,unkeyed:c.length,inMemoryHits:u,incompleteInMemoryHits:y,fullyInMemoryFiles:g,cacheReadFiles:p})),a.length>0||c.length>0){x=[...c,...a.map(w=>w.definition)],v=E("semantic.references.compute-misses",()=>{let w=Ld(e,x,i);return f=w.size,w},()=>({definitions:x.length,misses:a.length,unkeyed:c.length,rows:f}));for(let w of x)v.has(w.symbolId)?(n.set(w.symbolId,v.get(w.symbolId)??[]),r.delete(w.symbolId)):r.add(w.symbolId);for(let{definition:w,cacheFingerprint:k}of a)v.has(w.symbolId)&&pS(e,"semantic-references",w.relativePath).available&&s.push({relativePath:w.relativePath,symbol:w.symbol,projectFingerprint:k,payload:JSON.stringify(v.get(w.symbolId)??[])})}return s.length>0&&E("semantic.references.cache-write",()=>Hp(e,s),()=>({entries:s.length})),v.size>0&&Pd(e,x,v,w=>yr(e,w)),{definitions:t.length,inMemoryHits:u,incompleteInMemoryHits:y,cacheHits:d,misses:a.length,unkeyed:c.length,skippedUnsupportedLanguage:l,parseFailures:m,computed:f,incomplete:r.size,cacheWrites:s.length,fragmentDefinitions:h,fragmentCacheHits:C,fragmentCacheMisses:b,fragmentComputedFiles:S}}function b0(e,t,n){if(!t)return null;let r=_e(n);return r==="typescript"?t:r==="rust"?Ce(JSON.stringify({kind:"semantic-references",language:r,engine:fr(e.config.projectRoot),projectFingerprint:t})):null}function Ld(e,t,n={}){let r=G(),i=new Map,o=0,s=0,a=0,c=0,l=0,u=0,d=0,m=0,f=0;return E("semantic.references.provider-loop",()=>{let p=eS(e,t),g=Ty(e,t),y=new Map,h=n.prefetchCallees?new Map:null,C=[];for(let S of t){let x,v=()=>(x??=jt(e,S.relativePath),x);if(h){let k=v();if(k?.referencesAndCalleesForDefinitions){let L=h.get(k);L?L.push(S):h.set(k,[S]),f+=1}}let R=p.get(S.symbolId);if(R){a+=1,c+=R.length,Po(i,S.symbolId,R,r,k=>{d+=1,m+=k});continue}let D=g.get(S.symbolId);if(D){l+=1,u+=D.length,Po(i,S.symbolId,D,r,k=>{d+=1,m+=k});continue}let w=v();if(!w){r&&(s+=1);continue}if(r&&(o+=1),w.referencesForDefinitions){let k=y.get(w);k?k.push(S):y.set(w,[S])}else C.push({provider:w,definition:S})}let b=new Set;if(h)for(let[S,x]of h){if(!S.referencesAndCalleesForDefinitions)continue;let v=y.get(S)??[],R=S.referencesAndCalleesForDefinitions(v,x);b.add(S),g0(e,R.callees);for(let D of v){if(!R.references.has(D.symbolId))continue;let w=R.references.get(D.symbolId)??[];Po(i,D.symbolId,w,r,k=>{d+=1,m+=k})}}for(let[S,x]of y){if(b.has(S))continue;let v=S.referencesForDefinitions(x);for(let R of x){if(!v.has(R.symbolId))continue;let D=v.get(R.symbolId)??[];Po(i,R.symbolId,D,r,w=>{d+=1,m+=w})}}for(let{provider:S,definition:x}of C){let v=S.referencesFor(x);Po(i,x.symbolId,v,r,R=>{d+=1,m+=R})}return i},()=>({definitions:t.length,providerHits:o,providerMisses:s,rustDefaultFastPathRows:a,rustDefaultFastPathReferences:c,rustScipOccurrenceFastPathRows:l,rustScipOccurrenceFastPathReferences:u,prefetchCalleeDefinitions:f,definitionsWithReferences:d,referenceCount:m,rows:i.size}))}function Po(e,t,n,r,i){e.set(t,n),r&&n.length>0&&i(n.length)}function _d(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 S0(e){try{return JSON.parse(e)}catch{return null}}function Qa(e,t){return Ye(e).calleeMap(t)}function x0(e,t){let n=G(),r=new Map,i=0,o=0,s=0,a=0;return E("semantic.callees.provider-loop",()=>{let c=new Map,l=[];for(let u of t){let d=jt(e,u.relativePath);if(!d){n&&(o+=1);continue}n&&(i+=1);let m=u;if(d.calleesForDefinitions){let f=c.get(d);f?f.push(m):c.set(d,[m])}else l.push({provider:d,definition:m})}for(let[u,d]of c){let m=u.calleesForDefinitions(d);for(let f of d){let p=m.get(f.symbolId)??[];sS(r,f.symbolId,p,n,g=>{s+=1,a+=g})}}for(let{provider:u,definition:d}of l){let m=u.calleesFor(d);sS(r,d.symbolId,m,n,f=>{s+=1,a+=f})}return r},()=>({definitions:t.length,providerHits:i,providerMisses:o,definitionsWithCallees:s,calleeCount:a,rows:r.size}))}function sS(e,t,n,r,i){n.length>0&&(e.set(t,n),r&&i(n.length))}function dS(e,t){return Ye(e).signature(t)}function C0(e,t){if(_e(t.relativePath)==="typescript"){let s="fallback",a=0,c=0,l=0,u=0;return E("typescript.signature.materialize",()=>{let d=Bn(e,t.relativePath,p0);if(d?.key){a=1;let f=oS.read(e,t.relativePath,d.key)??{};if(Object.prototype.hasOwnProperty.call(f,t.symbol))return s="hit",c=1,f[t.symbol]??null;l=1;let p=jt(e,t.relativePath);if(!p)return s="unavailable",null;let g=p.signatureFor(t);return oS.write(e,t.relativePath,d.key,{...f,[t.symbol]:g}),s="computed",g}u=1;let m=jt(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=mS(e,"semantic-signatures",t.relativePath),r=R0(t);if(n){let s=rS.read(e,r,n);if(s)return s.signature}let i=jt(e,t.relativePath);if(!i)return null;let o=i.signatureFor(t);return n&&rS.write(e,r,n,{signature:o}),o}function mS(e,t,n){let r=Ne(e);if(!r)return null;let i=_e(n);return i!=="rust"?null:Ce(JSON.stringify({kind:t,language:i,engine:fr(e.config.projectRoot),projectFingerprint:r}))}function R0(e){return`${e.relativePath}\0${e.symbol}`}function fS(e){try{let t=JSON.parse(e);return Array.isArray(t)?t:null}catch{return null}}function v0(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 I0(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 pS(e,t,n){let r=_e(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,...yr(e,n).availability()}}catch(i){return{slot:t,language:r,available:!1,reason:i instanceof Error?i.message:String(i)}}}function jt(e,t){if(!_e(t))return null;let n=yr(e,t);return n.availability().available?n:null}var U={references:Xa,referenceMap:Ld,callerMap:(e,t)=>Ye(e).callerMap(t),calleeMap:Md};function Md(e,t){let n=G(),r=new Map,i=aS(e,t),o=[],s=[],a=0,c=0,l=0,u=0,d=0,m=0,f=0;for(let{definition:b,callees:S}of i.hits)d+=1,S.length>0&&(m+=1,f+=S.length,r.set(b.symbolId,S));let p=w0(e,i.hits);if(p.entries.length>0&&E("semantic.callees.prefetch-cache-write",()=>Fl(e,p.entries),()=>({entries:p.entries.length,sourceMissing:p.sourceMissing,skippedUnsupportedLanguage:p.skippedUnsupportedLanguage})),E("semantic.callees.cache-scan",()=>{for(let[b,S]of xa(i.misses)){if(!_e(b)){n&&(a+=S.length);continue}let x=P(e,b);if(!x){n&&(c+=S.length),s.push(...S);continue}let v=me(e,b,x),R=gS(e,b);if(!R){s.push(...S);continue}let D=jp(e,b,v,R);for(let w of S){let k=D.get(w.symbol)??null;if(k!==null){let L=D0(k);if(L){n&&(l+=1),L.length>0&&r.set(w.symbolId,L);continue}n&&(u+=1)}o.push({def:w,contentHash:v,depsDigest:R})}}},()=>({definitions:t.length,skippedUnsupportedLanguage:a,sourceMissing:c,cacheHits:l,parseFailures:u,misses:o.length,unkeyed:s.length,inMemoryHits:d,inMemoryRows:m,inMemoryCalleeCount:f,resultRows:r.size})),o.length===0&&s.length===0)return r;let g=[...s,...o.map(b=>b.def)],y=0,h=E("semantic.callees.compute-misses",()=>{let b=Qa(e,g);return y=b.size,b},()=>({definitions:g.length,misses:o.length,unkeyed:s.length,rows:y}));for(let[b,S]of h)r.set(b,S);let C=o.filter(b=>Ye(e).capability("semantic-callees",b.def.relativePath).available).map(b=>({relativePath:b.def.relativePath,symbol:b.def.symbol,contentHash:b.contentHash,depsDigest:b.depsDigest,payload:JSON.stringify(h.get(b.def.symbolId)??[])}));return C.length>0?E("semantic.callees.cache-write",()=>Fl(e,C),()=>({entries:C.length})):E("semantic.callees.cache-write-skip",()=>{},()=>({reason:"provider-unavailable",misses:o.length})),r}function w0(e,t){let n=[],r=new Map,i=0,o=0;for(let{definition:s,callees:a}of t){if(!_e(s.relativePath)){o+=1;continue}if(!r.has(s.relativePath)){let l=P(e,s.relativePath),u=l?gS(e,s.relativePath):null;r.set(s.relativePath,l&&u?{contentHash:me(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 E0="typescript-callees-v1";function gS(e,t){let n=_e(t);if(n==="typescript")return Bn(e,t,E0)?.key??null;let r=P0(e,t);return n==="rust"?Ce(JSON.stringify({kind:"semantic-callees",language:n,engine:fr(e.config.projectRoot),positionMapping:"nearby-leaf-v1",depsDigest:r})):r}function D0(e){try{return JSON.parse(e)}catch{return null}}var k0=B("semantic-deps-digest",{clearGroups:["whole-project","source-file"]});function P0(e,t){return k0.get(e,t,()=>{let r=[...ae(e).get(t)??[]].sort().map(i=>`${i}:${me(e,i,P(e,i))}`);return Ce(r.join("|"))})}function Kie(e,t,n={}){let r=$(e,t);if(!r)return[];let o=!oe(r.symbol)&&!e.isIgnored(r.relativePath)?[{relativePath:r.relativePath,line:r.startLine}]:[],s=Nt(e,r,{semantic:n.semantic,semanticEvidence:U}).map(u=>({relativePath:u.file,line:u.line})),a=F0(e,r),c=new Set,l=[];for(let u of[...o,...s,...a]){let d=`${u.relativePath}:${u.line}`;c.has(d)||(c.add(d),l.push(u))}return l}function F0(e,t){if(!t.relativePath.endsWith(".rb"))return[];let n=T0(t.symbol);if(n.length===0)return[];let r=[];for(let i of M(e,{extensions:[".rb"],includeIgnored:!1})){let o=P(e,i);if(!o)continue;let s=o.split(`
|
|
312
|
+
`);for(let a=0;a<s.length;a++){let c=s[a]??"";n.some(l=>new RegExp(`@${l}\\b|\\b${l}:`).test(c))&&r.push({relativePath:i,line:a})}}return r}function T0(e){let n=(e.split(":").pop()??e).replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),r=n.split("_").filter(Boolean),i=new Set;return n&&i.add(n),r.length>=1&&i.add(r[r.length-1]),r.length>=2&&i.add(r.slice(-2).join("_")),[...i]}import{existsSync as _0}from"fs";import{basename as hS,isAbsolute as L0,join as M0}from"path";function Ge(e,t){let n=yS(e,t,{allowMultiple:!1})[0]?.relativePath;return n||A0(e,t)}function fi(e,t){return yS(e,t,{allowMultiple:!0}).map(n=>n.relativePath)}function A0(e,t){if(!t)return null;let n=t.replace(/\\/g,"/").replace(/^\.\//,""),r=L0(n)&&n.startsWith(e.config.projectRoot)?n.slice(e.config.projectRoot.length).replace(/^\/+/,""):n,i=M0(e.config.projectRoot,r);return _0(i)?r:null}function yS(e,t,n){let r=bS(t);if(!r)return[];let i=M(e,{includeIgnored:!1}).map(a=>({relativePath:a,score:N0(a,r)})).filter(a=>a.score>0).sort((a,c)=>c.score-a.score||a.relativePath.localeCompare(c.relativePath));if(i.length===0){let a=$(e,t);return!a||e.isIgnored(a.relativePath)?[]:[{relativePath:a.relativePath,score:700}]}let o=i.filter(a=>a.score>=1100);if(o.length>0)return n.allowMultiple?o:[o[0]];let s=i.filter(a=>a.score>=800);return s.length>0?n.allowMultiple?s:[s[0]]:n.allowMultiple?i:[i[0]]}function N0(e,t){let n=bS(e),r=hS(n),i=hS(t),o=0;return n===t&&(o+=1200),n.endsWith(`/${t}`)&&(o+=1100),r===i&&(o+=900),n.startsWith(`${t}/`)&&(o+=850),n.includes(t)&&(o+=250),o}function bS(e){return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"").replace(/\/+$/,"")}function ioe(e,t){let n=fi(e,t),r=aa(e,n,{sort:!0});if(r.length===0)return[];let i=r.map(a=>({symbol:a.symbol,shortName:a.shortName,startLine:a.startLine,endLine:a.endLine,signature:a.signature,children:[]})),o=new Map;for(let a of i)o.set(a.symbol,a);let s=[];for(let a=0;a<r.length;a++){let c=r[a],l=i[a];if(c.enclosingSymbol&&o.has(c.enclosingSymbol)){o.get(c.enclosingSymbol).children.push(l);continue}let u=null,d=1/0;for(let m of i)if(m!==l&&m.startLine<=l.startLine&&m.endLine>=l.endLine){if(m.startLine===l.startLine&&m.endLine===l.endLine&&!cg(m.symbol,l.symbol))continue;let p=m.endLine-m.startLine;p<d&&(d=p,u=m)}u?u.children.push(l):s.push(l)}return s}import{readFileSync as SS}from"fs";import{extname as O0,join as xS}from"path";function doe(e,t,n={}){let{context:r=0}=n,i=j0(t);if(i)return $0(e,i.filePath,i.startLine,i.endLine,r);let o=$(e,t);return o?B0(e,o,r):null}function j0(e){let t=e.match(/^(.+\.\w+):(\d+)-(\d+)$/);return t?{filePath:t[1],startLine:parseInt(t[2],10),endLine:parseInt(t[3],10)}:null}function B0(e,t,n){let r=e.get("SELECT language FROM documents WHERE relative_path = ?",t.relativePath),i=xS(e.config.projectRoot,t.relativePath),o;try{o=SS(i,"utf-8")}catch{return null}let s=o.split(`
|
|
313
|
+
`),a=Math.max(0,t.startLine-n),c=Math.min(s.length-1,t.endLine+n),l=s.slice(a,c+1).join(`
|
|
314
|
+
`);return{symbol:t.symbol,shortName:I(t.symbol),relativePath:t.relativePath,startLine:a,endLine:c,language:r?.language??CS(t.relativePath),source:l}}function $0(e,t,n,r,i){let o=Ge(e,t);if(!o)return null;let s=e.get("SELECT relative_path, language FROM documents WHERE relative_path = ?",o);if(!s)return null;let a=xS(e.config.projectRoot,s.relative_path),c;try{c=SS(a,"utf-8")}catch{return null}let l=c.split(`
|
|
315
|
+
`),u=Math.max(0,n-1-i),d=Math.min(l.length-1,r-1+i),m=l.slice(u,d+1).join(`
|
|
316
|
+
`);return{symbol:`${s.relative_path}:${n}-${r}`,shortName:`${s.relative_path}:${n}-${r}`,relativePath:s.relative_path,startLine:u,endLine:d,language:s.language??CS(s.relative_path),source:m}}function CS(e){switch(O0(e).toLowerCase()){case".ts":case".tsx":case".mts":case".cts":return"typescript";case".js":case".jsx":case".mjs":case".cjs":return"javascript";case".py":case".pyi":return"python";case".rs":return"rust";case".go":return"go";case".java":return"java";case".kt":case".kts":return"kotlin";case".scala":return"scala";case".rb":return"ruby";case".php":return"php";case".cs":return"csharp";case".vb":return"vb";case".dart":return"dart";case".c":case".h":return"c";case".cc":case".cpp":case".cxx":case".hpp":case".hh":case".hxx":return"cpp";case".vue":return"vue";default:return null}}import{createRequire as H0}from"module";var U0=H0(import.meta.url),It=q0().version;function q0(){for(let e of["../package.json","../../package.json"])try{return U0(e)}catch{}return{version:"0.0.0"}}import{existsSync as km,statSync as OB}from"fs";import{join as jB}from"path";import{createHash as G0}from"crypto";import{mkdirSync as V0,realpathSync as W0}from"fs";import{homedir as z0}from"os";import{join as br,resolve as RS}from"path";function K0(e,t){let n=process.env.SCIP_QUERY_CACHE_DIR;if(n)return Ad(n);if(t?.dbPath)return Ad(RS(e,t.dbPath));let r=Za(e);return Ad(r)}function vS(){let e=process.env.XDG_CACHE_HOME;return br(e||br(z0(),".cache"),"scip-query")}function Za(e){let t=RS(e);try{t=W0(t)}catch{}let n=G0("sha256").update(t).digest("hex").slice(0,12);return br(vS(),"projects",n)}function To(e){if(!/^[a-f0-9]{24}$/.test(e))throw new Error(`invalid repository cache identity: ${e}`);return br(vS(),"repositories",e)}function Nd(e){return process.env.SCIP_QUERY_SHARED_CACHE!=="0"&&!process.env.SCIP_QUERY_CACHE_DIR&&!process.env.SCIP_QUERY_INDEX_DB&&!e?.dbPath}function IS(e,t){let n=K0(e,t);return{cacheDir:n,dbPath:br(n,"index.db"),indexPath:br(n,"index.scip"),metaPath:br(n,"meta.json")}}function Ad(e){return V0(e,{recursive:!0}),e}import J0 from"better-sqlite3";var Y0=["node_modules",".git","dist","build","out","coverage","target",".next",".nuxt",".cache",".turbo",".nbb",".cpcache",".shadow-cljs",".scipquery-cache","__pycache__",".venv","venv"],ec=class{db;config;generation;pathFilter;statementCache=new Map;constructor(t,n){this.config=t,this.pathFilter=n??null;let r=X0(t);this.generation=r.generation,this.db=r.db,this.db.pragma("busy_timeout = 5000"),this.db.pragma("query_only = ON"),this.db.pragma("temp_store = MEMORY"),this.db.pragma("cache_size = -64000"),this.db.pragma("mmap_size = 268435456")}isIgnored(t){return this.pathFilter?.isIgnored(t)??!1}get localSymbolPredicate(){return`(
|
|
317
|
+
EXISTS (
|
|
318
|
+
SELECT 1
|
|
319
|
+
FROM defn_enclosing_ranges local_der
|
|
320
|
+
JOIN documents local_d ON local_der.document_id = local_d.id
|
|
321
|
+
WHERE local_der.symbol_id = gs.id
|
|
322
|
+
${this.pathExclusionsFor("local_d").trimStart()}
|
|
323
|
+
)
|
|
324
|
+
OR EXISTS (
|
|
325
|
+
SELECT 1
|
|
326
|
+
FROM mentions local_m
|
|
327
|
+
JOIN chunks local_c ON local_m.chunk_id = local_c.id
|
|
328
|
+
JOIN documents local_d ON local_c.document_id = local_d.id
|
|
329
|
+
WHERE local_m.symbol_id = gs.id
|
|
330
|
+
AND local_m.role = 1
|
|
331
|
+
${this.pathExclusionsFor("local_d").trimStart()}
|
|
332
|
+
)
|
|
333
|
+
)`}get pathExclusions(){return this.pathExclusionsFor("d")}get symbolNoise(){return this.symbolNoiseFor("gs")}pathExclusionsFor(...t){return t.flatMap(n=>Y0.flatMap(r=>[`AND ${n}.relative_path NOT LIKE '${r}/%'`,`AND ${n}.relative_path NOT LIKE '%/${r}/%'`])).join(`
|
|
334
|
+
`)}symbolNoiseFor(t){return`AND ${t}.symbol NOT LIKE '%().(%' AND ${t}.symbol NOT LIKE '%typeLiteral%'`}all(t,...n){return this.statement(t).all(...n)}get(t,...n){return this.statement(t).get(...n)}close(){this.statementCache.clear(),this.db.close()}statement(t){let n=this.statementCache.get(t);return n||(n=this.db.prepare(t),this.statementCache.set(t,n)),n}};function X0(e){for(let t=0;t<4;t+=1){let n=wd(e),r=new J0(n.databasePath,{readonly:!0,fileMustExist:!0});if(n.source==="immutable")return{db:r,generation:n};try{let i=wd(e);if(n.databaseFileIdentity===dn(n.databasePath)&&i.source==="legacy"&&i.identity===n.identity&&i.databaseFileIdentity===n.databaseFileIdentity&&i.metadataRaw===n.metadataRaw)return{db:r,generation:n}}catch(i){throw r.close(),i}r.close()}throw new Error("SQLite index publication changed repeatedly while opening a coherent generation.")}import Q0 from"ignore";import{readFileSync as Z0,existsSync as wS,readdirSync as eO}from"fs";import{dirname as Od,isAbsolute as ES,join as tc,relative as tO,resolve as nO}from"path";function DS(e){let t=Q0();return rO(e,t)||t.add(sO),{isIgnored:r=>jd(t,e,r),filter:r=>r.filter(i=>!jd(t,e,i))}}function rO(e,t){let n=new Set,r=(s,a)=>{if(!(n.has(s)||!wS(s)))try{let c=Z0(s,"utf-8");t.add(a?iO(c,a):c),n.add(s)}catch{}},i=Od(e),o=0;for(;i!==Od(i)&&o<5&&(r(tc(i,".gitignore"),""),!wS(tc(i,".git")));)i=Od(i),o++;return kS(e,"",t,r),n.size>0}function kS(e,t,n,r){let i=t?tc(e,t):e;r(tc(i,".gitignore"),t);let o;try{o=eO(i,{withFileTypes:!0})}catch{return}for(let s of o){if(!s.isDirectory()||s.name===".git")continue;let a=t?`${t}/${s.name}`:s.name;jd(n,e,`${a}/`)||kS(e,a,n,r)}}function iO(e,t){let n=t.replaceAll("\\","/").replace(/\/+$/,"");return e.split(/\r?\n/).map(r=>oO(r,n)).join(`
|
|
335
|
+
`)}function oO(e,t){let n=e.trimStart();if(!n||n.startsWith("#"))return e;let r=e.slice(0,e.length-n.length),i=n.startsWith("!"),o=i?n.slice(1):n;if(!o||o.startsWith("#"))return e;let s=o.startsWith("/"),a=s?o.slice(1):o,u=(a.endsWith("/")?a.slice(0,-1):a).includes("/")||s?`${t}/${a}`:`${t}/**/${a}`;return`${r}${i?"!":""}${u}`}var sO=`
|
|
336
|
+
# Dependencies
|
|
337
|
+
node_modules/
|
|
338
|
+
vendor/
|
|
339
|
+
.bundle/
|
|
340
|
+
|
|
341
|
+
# Build output
|
|
342
|
+
dist/
|
|
343
|
+
build/
|
|
344
|
+
out/
|
|
345
|
+
target/
|
|
346
|
+
bin/
|
|
347
|
+
obj/
|
|
348
|
+
|
|
349
|
+
# Python
|
|
350
|
+
__pycache__/
|
|
351
|
+
*.pyc
|
|
352
|
+
*.pyo
|
|
353
|
+
.venv/
|
|
354
|
+
venv/
|
|
355
|
+
.env/
|
|
356
|
+
env/
|
|
357
|
+
*.egg-info/
|
|
358
|
+
|
|
359
|
+
# Rust
|
|
360
|
+
target/
|
|
361
|
+
|
|
362
|
+
# Java / Kotlin / Scala
|
|
363
|
+
*.class
|
|
364
|
+
.gradle/
|
|
365
|
+
.mvn/
|
|
366
|
+
|
|
367
|
+
# C# / .NET
|
|
368
|
+
bin/
|
|
369
|
+
obj/
|
|
370
|
+
packages/
|
|
371
|
+
|
|
372
|
+
# Go
|
|
373
|
+
vendor/
|
|
374
|
+
|
|
375
|
+
# Dart
|
|
376
|
+
.dart_tool/
|
|
377
|
+
build/
|
|
378
|
+
|
|
379
|
+
# PHP
|
|
380
|
+
vendor/
|
|
381
|
+
|
|
382
|
+
# IDE / OS
|
|
383
|
+
.idea/
|
|
384
|
+
.vscode/
|
|
385
|
+
*.swp
|
|
386
|
+
*.swo
|
|
387
|
+
.DS_Store
|
|
388
|
+
Thumbs.db
|
|
389
|
+
|
|
390
|
+
# Type definitions (often noise in queries)
|
|
391
|
+
*.d.ts
|
|
392
|
+
`;function jd(e,t,n){let r=aO(t,n);if(!r)return!1;try{return e.ignores(r)}catch{return!1}}function aO(e,t){if(!t||t===".")return null;if(!ES(t)&&!t.startsWith(".."))return t.replaceAll("\\","/");let n=ES(t)?t:nO(e,t),r=tO(e,n).replaceAll("\\","/");return!r||r==="."||r.startsWith("..")?null:r}import{existsSync as hi,readFileSync as MO}from"fs";import{isAbsolute as BS,join as Sr,relative as $S,resolve as HS}from"path";var Hn=1,Un=2,cO="./node_modules/scip-query/docs/schemas/project-config.schema.json";function Bd(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch(a){return{kind:"malformed",reason:`invalid JSON: ${a instanceof Error?a.message:String(a)}`}}if(!q(t))return{kind:"malformed",reason:"project config must be a JSON object"};let n=t.schemaVersion;if(n!==void 0&&!Number.isInteger(n))return{kind:"malformed",reason:"schemaVersion must be an integer"};let r=n===void 0?Hn:n;if(r!==Hn&&r!==Un)return{kind:"unsupported",schemaVersion:r,direction:r<Hn?"older":"future"};let i=t.$schema;if(i!==void 0&&(typeof i!="string"||i.trim()===""))return{kind:"malformed",reason:"$schema must be a non-empty string when present"};let o=nc(t),s=r!==Un||typeof t.$schema!="string";return r===Hn?{kind:"legacy",sourceVersion:Hn,config:o,needsMigration:s}:{kind:"supported",sourceVersion:Un,config:o,needsMigration:s}}function nc(e){let t=e,{$schema:n,schemaVersion:r,...i}=t;return{$schema:typeof n=="string"&&n.trim()!==""?n:cO,schemaVersion:Un,...i}}function PS(e){return`${JSON.stringify(nc(e),null,2)}
|
|
393
|
+
`}import{createHash as MS}from"crypto";import{closeSync as vO,fstatSync as AS,openSync as IO,readFileSync as wO,rmSync as EO}from"fs";import{dirname as DO}from"path";import{randomUUID as lO}from"crypto";import{closeSync as uO,fsyncSync as dO,linkSync as mO,mkdirSync as fO,openSync as pO,readFileSync as gO,statSync as hO,unlinkSync as yO,writeSync as bO}from"fs";import{dirname as Gd}from"path";var Hd="scip-query-process-lock",Ud=1;var rc=Object.freeze({wallNow:()=>Date.now(),isProcessAlive:Ln,readProcessIdentity:Rt,randomToken:()=>lO(),makeDirectory:e=>fO(e,{recursive:!0}),openFile:(e,t,n)=>pO(e,t,n),writeFile:(e,t,n,r)=>bO(e,t,n,r),syncFile:e=>dO(e),closeFile:e=>uO(e),linkFile:(e,t)=>mO(e,t),readFile:e=>gO(e,"utf8"),statFile:e=>{let t=hO(e);return{dev:t.dev,ino:t.ino,size:t.size,mtimeMs:t.mtimeMs}},removeFile:e=>yO(e)});function gi(e,t){let n=t.runtime??rc;n.makeDirectory(Gd(e));let r;for(let i=0;i<2;i+=1)try{return{kind:"acquired",lock:TS(e,t,n),...r?{reclaimed:r}:{}}}catch(o){if(o.code!=="EEXIST")throw o;let s=pi(e,{parseLegacy:t.parseLegacy,runtime:n});if(i===0&&xO(e,s,{creationGraceMs:t.creationGraceMs,parseLegacy:t.parseLegacy,runtime:n})){r=s;continue}return{kind:"contended",observation:s}}return{kind:"contended",observation:pi(e,{parseLegacy:t.parseLegacy,runtime:n})}}function pi(e,t={}){let n=t.runtime??rc,r,i;try{r=n.statFile(e),i=n.readFile(e)}catch(c){return c.code==="ENOENT"?{state:"missing"}:{state:"malformed"}}let o;try{o=JSON.parse(i)}catch{return{state:"malformed",raw:i,identity:r}}let s=SO(o);if(s)return{state:"valid",raw:i,identity:r,record:s,owner:RO(s),parsed:o};let a=t.parseLegacy?.(o)??null;return a?{state:"legacy",raw:i,identity:r,owner:a,parsed:o}:{state:"malformed",raw:i,identity:r,parsed:o}}function SO(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.protocol!==Hd||t.version!==Ud||typeof t.kind!="string"||t.kind.trim()===""||typeof t.pid!="number"||!Number.isSafeInteger(t.pid)||t.pid<=0||typeof t.token!="string"||t.token.trim()===""||typeof t.startedAt!="string"||!Number.isFinite(Date.parse(t.startedAt))||t.detail!==void 0&&(typeof t.detail!="object"||t.detail===null||Array.isArray(t.detail)))return null;let n=t.processIdentity===void 0?null:ln(t.processIdentity);return t.processIdentity!==void 0&&(!n||n.pid!==t.pid)?null:{protocol:Hd,version:Ud,kind:t.kind,pid:t.pid,token:t.token,...n?{processIdentity:n}:{},startedAt:t.startedAt,...t.detail?{detail:t.detail}:{}}}function xO(e,t,n={}){let r=n.runtime??rc;if(!qd(t,r))return!1;let i=CO(`${e}.reclaim`,r);if(!i)return!1;try{let o=pi(e,{parseLegacy:n.parseLegacy,runtime:r});return!_S(t,o)||!qd(o,r)?!1:Vd(e,r)}finally{i.release()}}function TS(e,t,n){let r=t.pid??process.pid,i=n.randomToken(),o=t.processIdentity===void 0?n.readProcessIdentity(r):t.processIdentity,s={protocol:Hd,version:Ud,kind:t.kind,pid:r,token:i,...o?{processIdentity:o}:{},startedAt:new Date(n.wallNow()).toISOString(),...t.detail?{detail:t.detail}:{}},a=`${e}.${i}.candidate`,c=n.openFile(a,"wx",384),l;try{so(c,Buffer.from(`${JSON.stringify(s)}
|
|
394
|
+
`),n,"process lock"),n.syncFile(c)}catch(d){l=d}try{n.closeFile(c)}catch(d){l??=d}if(l!==void 0)throw $d(a,n),l;try{n.linkFile(a,e)}catch(d){throw $d(a,n),d}$d(a,n);try{LS(Gd(e),n)}catch(d){throw FS(e,s,n),d}let u=!1;return{path:e,record:s,release:()=>u?!1:(u=!0,FS(e,s,n))}}function FS(e,t,n=rc){let r=pi(e,{runtime:n});return r.state!=="valid"||!r.record||r.record.pid!==t.pid||r.record.token!==t.token||t.processIdentity&&(!r.record.processIdentity||!ft(t.processIdentity,r.record.processIdentity))?!1:Vd(e,n)}function CO(e,t){for(let n=0;n<2;n+=1)try{return TS(e,{kind:"reclaim-guard",runtime:t},t)}catch(r){if(r.code!=="EEXIST")return null;let i=pi(e,{runtime:t});if(n>0||!qd(i,t))return null;let o=pi(e,{runtime:t});if(!_S(i,o)||!Vd(e,t))return null}return null}function qd(e,t){if(e.state==="missing")return!1;if(e.owner){if(!t.isProcessAlive(e.owner.pid))return!0;if(!e.owner.processIdentity)return!1;let n=t.readProcessIdentity(e.owner.pid);return n!==null&&!ft(e.owner.processIdentity,n)}return!1}function _S(e,t){return e.state===t.state&&e.raw===t.raw&&e.identity!==void 0&&t.identity!==void 0&&e.identity.dev===t.identity.dev&&e.identity.ino===t.identity.ino&&e.identity.size===t.identity.size&&e.identity.mtimeMs===t.identity.mtimeMs}function RO(e){return{pid:e.pid,...e.processIdentity?{processIdentity:e.processIdentity}:{}}}function LS(e,t){let n;try{n=t.openFile(e,"r")}catch(r){if(ei(r,process.platform))return;throw r}try{t.syncFile(n)}catch(r){if(!ei(r,process.platform))throw r}finally{t.closeFile(n)}}function Vd(e,t){try{return t.removeFile(e),LS(Gd(e),t),!0}catch{return!1}}function $d(e,t){try{t.removeFile(e)}catch{}}var kO=2e3,PO=10,FO=3,oc=class extends Error{constructor(n,r,i){super(`Concurrent edit detected for ${n}; expected revision ${OS(r)}, but found ${OS(i)}. The latest file was left untouched.`);this.path=n;this.original=r;this.latest=i;this.name="FileRevisionConflictError"}path;original;latest},_o=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 sc(e,t,n={}){let r=TO(e,n.lockTimeoutMs??kO,n.monotonicNow??we);try{let i=Math.max(0,Math.floor(n.maxRetries??FO));for(let o=0;;o+=1){let s=ic(e),a=t(s,o);if(a.kind==="unchanged")return{changed:!1,attempts:o+1,previous:s,current:s};n.onBeforeCommit?.({attempt:o,snapshot:s,mutation:a});let c=ic(e);if(!LO(s.revision,c.revision)){if(o<i)continue;throw new oc(e,s.revision,c.revision)}try{_O(e,a,s.revision)}catch(l){if(l.code==="EEXIST"){let u=ic(e);if(o<i)continue;throw new oc(e,s.revision,u.revision)}throw l}return{changed:!0,attempts:o+1,previous:s,current:ic(e)}}}finally{r.release()}}function ic(e){for(let t=0;t<4;t+=1){let n;try{n=IO(e,"r");let r=NS(AS(n)),i=wO(n,"utf8"),o=NS(AS(n));if(!jS(r,o))continue;return{path:e,text:i,revision:{exists:!0,hash:MS("sha256").update(i).digest("hex"),identity:o}}}catch(r){if(r.code==="ENOENT")return{path:e,text:"",revision:{exists:!1,hash:MS("sha256").update("").digest("hex")}};throw r}finally{n!==void 0&&vO(n)}}throw new Error(`Could not read a stable revision of ${e}; the file is changing continuously.`)}function TO(e,t,n){let r=`${e}.scip-query-write.lock`,i=n()+Math.max(0,t);for(;;){let o=gi(r,{kind:"revisioned-file-mutation",detail:{target:e}});if(o.kind==="acquired")return o.lock;if(n()>=i)throw new Error(`Timed out after ${t}ms waiting to update ${e}; the file was left untouched.`);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,PO)}}function _O(e,t,n){if(t.kind==="delete"){if(!n.exists)return;EO(e),vt(DO(e));return}let r=t.mode??n.identity?.mode;n.exists?ao(e,t.text,{durability:"durable",mode:r}):co(e,t.text,{durability:"durable",mode:r})}function LO(e,t){return e.exists===t.exists&&e.hash===t.hash&&(e.identity===void 0?t.identity===void 0:t.identity!==void 0&&jS(e.identity,t.identity))}function NS(e){return{dev:e.dev,ino:e.ino,size:e.size,mtimeMs:e.mtimeMs,mode:e.mode&511}}function jS(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.mode===t.mode}function OS(e){return e.exists?e.hash.slice(0,12):"<absent>"}var xr=".scipquery.json",GS=250,VS=0,WS=10*6e4,AO={enabled:!1,debounceMs:GS,cooldownMs:VS,gitPollMs:2e3,idleTimeoutMs:WS,autoRefresh:!0,ignore:[]};var NO=new Set(["$schema","schemaVersion","languages","indexerConcurrency","watch","hooks","indexer","dbPath","entryRoots","semantic","suppressions","declaredCouplings","locality","architecture","coverageContracts","docs"]),OO=new Set(["enabled","debounceMs","cooldownMs","gitPollMs","idleTimeoutMs","autoRefresh","ignore"]),jO=new Set(["router"]),BO=new Set(["pathPrefixes","files","symbolPatterns","qualifiedVars"]),$O=new Set(["typescript","rust"]),HO=new Set(["tsconfigs"]),UO=new Set(["rustAnalyzerPath"]),US=new Set(Oi),qO=new Set(["pnpmWorkspaces","projectMode","projects","configPath"]),GO=new Set(["architecturalBoundarySegments"]),VO=new Set(["boundaries","allowedDependencies","requireCompletePolicy","requireAcyclic","requireResolvedBoundaries","requireMinimalPolicy","maxBoundaryFanOut","maxBoundaryFiles","testPaths"]),WO=new Set(["name","paths","subUnits","maxFiles"]),zO=new Set(["snapshotPaths"]),KO=new Set(["name","files","reason"]),JO=new Set(["id","check","file","reason","expiresAt","createdAt"]),YO=new Set(["name","file","keys","mustEqual","allowExtra"]),XO=new Set(["type","identifier","marker"]),QO=new Set(["type","path","pattern"]),ZO=new Set(["object-literal-keys","string-array","markdown-list"]),ej=new Set(["top-level-dirs","file-glob","registered-commands","builtin-skills"]);function zS(e){let t=Sr(e,xr);if(!hi(t))return{};let n;try{n=MO(t,"utf-8")}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`unable to read ${xr} at ${t}: ${i}`,{cause:r})}return YS(Bd(n),t,"read").config}function Joe(e,t={}){let n=[];oj(e,n);let r=e;r.schemaVersion!==void 0&&r.schemaVersion!==Un&&n.push({level:"error",path:"schemaVersion",message:`Must be ${Un}; unversioned and v${Hn} files are migrated while loading.`}),r.$schema!==void 0&&(typeof r.$schema!="string"||r.$schema.trim()==="")&&n.push({level:"error",path:"$schema",message:"Must be a non-empty string."});let i=new Set(Oi);for(let[l,u]of(e.languages??[]).entries())i.has(u)||n.push({level:"error",path:`languages[${l}]`,message:`Unsupported language: ${u}`});e.indexerConcurrency!==void 0&&(!Number.isInteger(e.indexerConcurrency)||e.indexerConcurrency<=0)&&n.push({level:"error",path:"indexerConcurrency",message:"Must be a positive integer."}),e.watch?.debounceMs!==void 0&&e.watch.debounceMs<=0&&n.push({level:"error",path:"watch.debounceMs",message:"Must be greater than 0."}),e.watch?.cooldownMs!==void 0&&(!Number.isInteger(e.watch.cooldownMs)||e.watch.cooldownMs<0)&&n.push({level:"error",path:"watch.cooldownMs",message:"Must be a non-negative integer; 0 disables cooldown spacing."}),e.watch?.gitPollMs!==void 0&&e.watch.gitPollMs<=0&&n.push({level:"error",path:"watch.gitPollMs",message:"Must be greater than 0."}),e.watch?.idleTimeoutMs!==void 0&&(!Number.isInteger(e.watch.idleTimeoutMs)||e.watch.idleTimeoutMs<0)&&n.push({level:"error",path:"watch.idleTimeoutMs",message:"Must be a non-negative integer; 0 disables idle shutdown."}),e.watch?.autoRefresh!==void 0&&typeof e.watch.autoRefresh!="boolean"&&n.push({level:"error",path:"watch.autoRefresh",message:"Must be a boolean."}),e.hooks?.router!==void 0&&e.hooks.router!=="off"&&e.hooks.router!=="single"&&n.push({level:"error",path:"hooks.router",message:'Must be "off" or "single".'});let o=e.indexer?.typescript;if(o?.projectMode!==void 0&&o.projectMode!=="single"&&o.projectMode!=="workspace"&&n.push({level:"error",path:"indexer.typescript.projectMode",message:'Must be "single" or "workspace".'}),o?.projects!==void 0)if(!Array.isArray(o.projects))n.push({level:"error",path:"indexer.typescript.projects",message:"Must be an array."});else for(let[l,u]of o.projects.entries()){let d=`indexer.typescript.projects[${l}]`;if(typeof u!="string"||u.trim()==="")n.push({level:"error",path:d,message:"Project path must be a non-empty string."});else if(t.projectRoot){let m=HS(t.projectRoot,u),f=$S(t.projectRoot,m);f.startsWith("..")||BS(f)?n.push({level:"error",path:d,message:"Project path must stay inside the project root."}):hi(m)||n.push({level:"warning",path:d,message:`TypeScript project path does not exist: ${u}`})}}o?.projectMode==="workspace"&&o.pnpmWorkspaces===!0&&n.push({level:"warning",path:"indexer.typescript.pnpmWorkspaces",message:'Ignored when projectMode is "workspace"; explicit TypeScript projects are indexed directly.'});let s=e.semantic?.rust;s?.rustAnalyzerPath!==void 0&&(typeof s.rustAnalyzerPath!="string"||s.rustAnalyzerPath.trim()==="")&&n.push({level:"error",path:"semantic.rust.rustAnalyzerPath",message:"Rust analyzer path must be a non-empty string."});let a=e.indexer?.clojure;if(a?.configPath!==void 0){let l="indexer.clojure.configPath";if(typeof a.configPath!="string"||a.configPath.trim()==="")n.push({level:"error",path:l,message:"Config path must be a non-empty string."});else if(t.projectRoot){let u=HS(t.projectRoot,a.configPath),d=$S(t.projectRoot,u);d.startsWith("..")||BS(d)?n.push({level:"error",path:l,message:"Config path must stay inside the project root."}):hi(u)||n.push({level:"warning",path:l,message:`Clojure indexer config path does not exist: ${a.configPath}`})}}if(e.locality!==void 0)if(!q(e.locality))n.push({level:"error",path:"locality",message:"Must be an object."});else{let l=e.locality.architecturalBoundarySegments;if(l!==void 0)if(!Array.isArray(l))n.push({level:"error",path:"locality.architecturalBoundarySegments",message:"Must be an array."});else for(let[u,d]of l.entries()){let m=`locality.architecturalBoundarySegments[${u}]`;typeof d!="string"||d.trim()===""?n.push({level:"error",path:m,message:"Boundary segment must be a non-empty string."}):(d.includes("/")||d.includes("\\"))&&n.push({level:"error",path:m,message:"Boundary segment must be a single folder name, not a path."})}}if(tj(e,n),e.declaredCouplings!==void 0&&!Array.isArray(e.declaredCouplings))n.push({level:"error",path:"declaredCouplings",message:"Must be an array."});else for(let[l,u]of(e.declaredCouplings??[]).entries()){let d=`declaredCouplings[${l}]`;if((!u.name||u.name.trim()==="")&&n.push({level:"error",path:`${d}.name`,message:"Declared coupling name is required."}),!Array.isArray(u.files)||u.files.length<2)n.push({level:"error",path:`${d}.files`,message:"Declared coupling needs at least two files."});else for(let[m,f]of u.files.entries())!f||f.trim()===""?n.push({level:"error",path:`${d}.files[${m}]`,message:"Declared coupling file path is required."}):t.projectRoot&&!hi(Sr(t.projectRoot,f))&&n.push({level:"warning",path:`${d}.files[${m}]`,message:`Declared coupling file does not exist: ${f}`});u.reason!==void 0&&u.reason.trim()===""&&n.push({level:"error",path:`${d}.reason`,message:"Declared coupling reason cannot be blank."})}let c=t.now??new Date;e.suppressions!==void 0&&!Array.isArray(e.suppressions)&&n.push({level:"error",path:"suppressions",message:"Must be an array."});for(let[l,u]of(Array.isArray(e.suppressions)?e.suppressions:[]).entries()){let d=`suppressions[${l}]`;if(!q(u)){n.push({level:"error",path:d,message:"Suppression must be an object."});continue}if((!u.reason||u.reason.trim()==="")&&n.push({level:"error",path:`${d}.reason`,message:"Suppression reason is required."}),u.id!==void 0&&u.id.trim()===""&&n.push({level:"error",path:`${d}.id`,message:"Suppression id cannot be blank."}),u.check!==void 0&&u.check.trim()===""&&n.push({level:"error",path:`${d}.check`,message:"Suppression check cannot be blank."}),!u.id&&(!u.check||!u.file)?n.push({level:"error",path:d,message:"Suppression must include id or both check and file."}):!u.id&&u.check&&u.file&&n.push({level:"warning",path:d,message:"Check+file suppressions waive every matching finding in that file; prefer a stable id when available."}),u.file!==void 0&&(u.file.trim()===""?n.push({level:"error",path:`${d}.file`,message:"Suppression file path cannot be blank."}):t.projectRoot&&!hi(Sr(t.projectRoot,u.file))&&n.push({level:"warning",path:`${d}.file`,message:`Suppression file does not exist: ${u.file}`})),u.expiresAt){let m=Date.parse(u.expiresAt);Number.isNaN(m)?n.push({level:"error",path:`${d}.expiresAt`,message:"Must be an ISO date string."}):m<=c.getTime()&&n.push({level:"warning",path:`${d}.expiresAt`,message:"Suppression has expired."})}}return ij(e,n,t),rj(e,n),n}function tj(e,t){if(e.architecture===void 0)return;if(!q(e.architecture)){t.push({level:"error",path:"architecture",message:"Must be an object."});return}let n=e.architecture.boundaries;if(!Array.isArray(n)||n.length===0){t.push({level:"error",path:"architecture.boundaries",message:"Must be a non-empty array."});return}let r=new Set,i=new Set;for(let[a,c]of n.entries()){let l=`architecture.boundaries[${a}]`;if(!q(c)){t.push({level:"error",path:l,message:"Architecture boundary must be an object."});continue}let u=c.name;typeof u!="string"||u.trim()===""?t.push({level:"error",path:`${l}.name`,message:"Boundary name is required."}):r.has(u)?t.push({level:"error",path:`${l}.name`,message:`Duplicate boundary name: ${u}`}):r.add(u);let d=c.subUnits;d!==void 0&&d!=="directory"&&d!=="file"&&t.push({level:"error",path:`${l}.subUnits`,message:"Must be 'directory' or 'file'."});let m=c.maxFiles;m!==void 0&&(typeof m!="number"||!Number.isInteger(m)||m<0)&&t.push({level:"error",path:`${l}.maxFiles`,message:"Must be a non-negative integer."});let f=c.paths;if(!Array.isArray(f)||f.length===0){t.push({level:"error",path:`${l}.paths`,message:"Boundary paths must be a non-empty array."});continue}for(let[p,g]of f.entries()){let y=`${l}.paths[${p}]`;if(typeof g!="string"||g.trim()===""){t.push({level:"error",path:y,message:"Boundary path must be a non-empty string."});continue}nj(g)||t.push({level:"error",path:y,message:"Boundary path must be project-relative and may use only one trailing /* or /** glob."}),i.has(g)?t.push({level:"error",path:y,message:`Duplicate boundary path: ${g}`}):i.add(g)}}let o=e.architecture.allowedDependencies;if(o!==void 0&&!q(o))t.push({level:"error",path:"architecture.allowedDependencies",message:"Must be an object keyed by boundary name."});else if(q(o))for(let[a,c]of Object.entries(o)){let l=`architecture.allowedDependencies.${a}`;if(r.has(a)||t.push({level:"error",path:l,message:`Unknown source boundary: ${a}`}),!Array.isArray(c)){t.push({level:"error",path:l,message:"Dependency row must be an array."});continue}let u=new Set;for(let[d,m]of c.entries()){let f=`${l}[${d}]`;typeof m!="string"||m.trim()===""?t.push({level:"error",path:f,message:"Target boundary name is required."}):r.has(m)?u.has(m)?t.push({level:"error",path:f,message:`Duplicate target boundary: ${m}`}):u.add(m):t.push({level:"error",path:f,message:`Unknown target boundary: ${m}`})}}e.architecture.requireAcyclic!==void 0&&typeof e.architecture.requireAcyclic!="boolean"&&t.push({level:"error",path:"architecture.requireAcyclic",message:"Must be a boolean."});for(let a of["requireResolvedBoundaries","requireMinimalPolicy"])e.architecture[a]!==void 0&&typeof e.architecture[a]!="boolean"&&t.push({level:"error",path:`architecture.${a}`,message:"Must be a boolean."});for(let a of["maxBoundaryFanOut","maxBoundaryFiles"]){let c=e.architecture[a];c!==void 0&&(typeof c!="number"||!Number.isInteger(c)||c<0)&&t.push({level:"error",path:`architecture.${a}`,message:"Must be a non-negative integer."})}let s=e.architecture.testPaths;if(s!==void 0&&(!Array.isArray(s)||s.some(a=>typeof a!="string"))&&t.push({level:"error",path:"architecture.testPaths",message:"Must be an array of strings."}),e.architecture.requireCompletePolicy!==void 0&&typeof e.architecture.requireCompletePolicy!="boolean")t.push({level:"error",path:"architecture.requireCompletePolicy",message:"Must be a boolean."});else if(e.architecture.requireCompletePolicy===!0){let a=q(o)?o:{};for(let c of[...r].sort())Object.hasOwn(a,c)||t.push({level:"error",path:`architecture.allowedDependencies.${c}`,message:"A dependency row is required by architecture.requireCompletePolicy."})}}function nj(e){let t=e.replace(/\\/g,"/");if(t.startsWith("/")||t==="."||t===".."||t.split("/").includes(".."))return!1;let n=t.replace(/\/\*\*?$/,"");return n.length>0&&!/[*?[\]]/.test(n)}function rj(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 ij(e,t,n){if(e.coverageContracts!==void 0){if(!Array.isArray(e.coverageContracts)){t.push({level:"error",path:"coverageContracts",message:"Must be an array."});return}for(let[r,i]of e.coverageContracts.entries()){let o=`coverageContracts[${r}]`;if(!q(i)){t.push({level:"error",path:o,message:"Coverage contract must be an object."});continue}(typeof i.name!="string"||i.name.trim()==="")&&t.push({level:"error",path:`${o}.name`,message:"Coverage contract name is required."}),typeof i.file!="string"||i.file.trim()===""?t.push({level:"error",path:`${o}.file`,message:"Coverage contract file is required."}):n.projectRoot&&!hi(Sr(n.projectRoot,i.file))&&t.push({level:"warning",path:`${o}.file`,message:`Coverage contract file does not exist: ${i.file}`}),qS(t,i.keys,`${o}.keys`,ZO,"Unknown coverage-contract key extractor type."),qS(t,i.mustEqual,`${o}.mustEqual`,ej,"Unknown coverage-contract ground-truth source type."),i.allowExtra!==void 0&&typeof i.allowExtra!="boolean"&&t.push({level:"error",path:`${o}.allowExtra`,message:"Must be a boolean."})}}}function qS(e,t,n,r,i){if(!q(t)){e.push({level:"error",path:n,message:'Must be an object with a "type" field.'});return}if(typeof t.type!="string"||!r.has(t.type)){e.push({level:"error",path:`${n}.type`,message:`${i} Got: ${String(t.type)}`});return}let o={"object-literal-keys":["identifier"],"string-array":["identifier"],"markdown-list":["marker"],"top-level-dirs":["path"],"file-glob":["pattern"],"registered-commands":[],"builtin-skills":[]};for(let s of o[t.type]??[])(typeof t[s]!="string"||t[s].length===0)&&e.push({level:"error",path:`${n}.${s}`,message:`"${t.type}" requires a non-empty string "${s}".`})}function Yoe(e){return{...AO,...e.watch}}function Xoe(e,t){let n=Sr(e,xr),r={languages:t,watch:{enabled:!0,debounceMs:GS,cooldownMs:VS,gitPollMs:2e3,idleTimeoutMs:WS,autoRefresh:!0}};return sc(n,i=>i.revision.exists?{kind:"unchanged"}:{kind:"write",text:Wd(r)}),n}function Qoe(e,t,n){let r=Sr(e,xr),i=[...n],o=t,s=sc(r,a=>{let c=KS(a,t);if(JS(t.languages,c.config.languages,i))throw new _o(r,"languages");let l={...c.config,languages:i};return o=l,a.revision.exists&&!c.needsMigration&&ac(l,c.config)?{kind:"unchanged"}:{kind:"write",text:Wd(l)}});return{configPath:r,config:o,changed:s.changed}}function Zoe(e,t,n){let r=Sr(e,xr),i=t,o=sc(r,s=>{let a=KS(s,t);if(JS(t.watch?.enabled,a.config.watch?.enabled,n))throw new _o(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&&ac(c,a.config)?{kind:"unchanged"}:{kind:"write",text:Wd(c)}});return{configPath:r,config:i,changed:o.changed}}function KS(e,t){if(!e.revision.exists)return{config:nc(t),needsMigration:!0};let n=YS(Bd(e.text),e.path,"update");return{config:n.config,needsMigration:n.needsMigration}}function Wd(e){return PS(e)}function ac(e,t){return JSON.stringify(e)===JSON.stringify(t)}function JS(e,t,n){return!ac(e,t)&&!ac(t,n)}function YS(e,t,n){if(e.kind==="legacy"||e.kind==="supported")return e;if(e.kind==="malformed"){let i=n==="read"?`invalid ${xr} 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 ${xr} 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${Hn} and current v${Un}). Upgrade scip-query before retrying; the file was left untouched.`)}function oj(e,t){if(!q(e))return;let n=e;if(ke(t,n,"",NO),ke(t,n.watch,"watch",OO),ke(t,n.hooks,"hooks",jO),ke(t,n.entryRoots,"entryRoots",BO),ke(t,n.semantic,"semantic",$O),ke(t,n.semantic?.typescript,"semantic.typescript",HO),ke(t,n.semantic?.rust,"semantic.rust",UO),ke(t,n.locality,"locality",GO),ke(t,n.architecture,"architecture",VO),ke(t,n.docs,"docs",zO),Array.isArray(n.architecture?.boundaries))for(let[r,i]of n.architecture.boundaries.entries())ke(t,i,`architecture.boundaries[${r}]`,WO);if(q(n.indexer)){ke(t,n.indexer,"indexer",US);for(let[r,i]of Object.entries(n.indexer))US.has(r)&&ke(t,i,`indexer.${r}`,qO)}if(Array.isArray(n.declaredCouplings))for(let[r,i]of n.declaredCouplings.entries())ke(t,i,`declaredCouplings[${r}]`,KO);if(Array.isArray(n.suppressions))for(let[r,i]of n.suppressions.entries())ke(t,i,`suppressions[${r}]`,JO);if(Array.isArray(n.coverageContracts))for(let[r,i]of n.coverageContracts.entries()){let o=`coverageContracts[${r}]`;ke(t,i,o,YO),q(i)&&(ke(t,i.keys,`${o}.keys`,XO),ke(t,i.mustEqual,`${o}.mustEqual`,QO))}}function ke(e,t,n,r){if(q(t))for(let i of Object.keys(t))r.has(i)||e.push({level:"warning",path:n?`${n}.${i}`:i,message:"Unknown config key."})}import{existsSync as dx,readFileSync as Tj}from"fs";import{execFileSync as sj}from"child_process";import{existsSync as aj,readdirSync as QS}from"fs";import{extname as ZS,join as ex}from"path";var tx=new Set([".git",".hg",".svn",".idea",".vscode","node_modules","vendor","dist","build","target","bin","obj",".dart_tool",".gradle",".next",".venv","venv","__pycache__"]),cj=[{language:"typescript",files:["tsconfig.json","tsconfig.base.json"],extensions:[".ts",".tsx",".mts",".cts"]},{language:"rust",files:["Cargo.toml"],extensions:[".rs"]},{language:"go",files:["go.mod"],extensions:[".go"]},{language:"java",files:["pom.xml","build.gradle","build.gradle.kts"],extensions:[".java"]},{language:"kotlin",files:["build.gradle.kts"],extensions:[".kt",".kts"]},{language:"scala",files:["build.sbt"],extensions:[".scala"]},{language:"clojure",files:["deps.edn","project.clj","bb.edn","shadow-cljs.edn"],extensions:[".clj",".cljs",".cljc"]},{language:"python",files:["pyproject.toml","setup.py","setup.cfg","Pipfile"],extensions:[".py",".pyi"]},{language:"ruby",files:["Gemfile"],extensions:[".rb"]},{language:"cpp",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".cc",".cpp",".cxx",".hpp",".hh",".hxx"]},{language:"c",files:["compile_commands.json","CMakeLists.txt","Makefile"],extensions:[".c",".h"]},{language:"csharp",globs:["*.csproj","*.sln"],extensions:[".cs"]},{language:"vb",globs:["*.vbproj"],extensions:[".vb"]},{language:"dart",files:["pubspec.yaml"],extensions:[".dart"]},{language:"php",files:["composer.json"],extensions:[".php"]},{language:"javascript",files:["package.json"],extensions:[".js",".jsx",".mjs",".cjs"]}];function Lo(e){let t=[],n=lj(e),r=fj(e);for(let i of cj){if(uj(e,i.files)){t.push(i.language);continue}if(dj(n,i.globs)){t.push(i.language);continue}gj(r,i.extensions)&&t.push(i.language)}return t.includes("typescript")&&XS(t,"javascript"),t.includes("cpp")&&!r.has(".c")&&XS(t,"c"),t}function lj(e){try{return QS(e)}catch{return[]}}function uj(e,t){return t?.length?t.some(n=>aj(ex(e,n))):!1}function dj(e,t){return t?.length?e.some(n=>t.some(r=>mj(n,r))):!1}function mj(e,t){if(t==="*")return!0;if(!t.includes("*"))return e===t;let[n,r]=t.split("*");return e.startsWith(n??"")&&e.endsWith(r??"")}function fj(e){let t=pj(e);if(t)return t;let n=new Set,r=[e];for(;r.length>0;){let i=r.pop();if(!i)continue;let o;try{o=QS(i,{withFileTypes:!0})}catch{continue}for(let s of o){if(s.name.startsWith(".")&&!s.name.endsWith("proj")&&!s.name.endsWith("sln")&&s.isDirectory())continue;let a=ex(i,s.name);if(s.isDirectory()){tx.has(s.name)||r.push(a);continue}let c=ZS(s.name).toLowerCase();c&&n.add(c)}}return n}function pj(e){try{let t=sj("git",["-C",e,"ls-files","-co","--exclude-standard","--","."],{encoding:"utf-8",maxBuffer:26214400,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"}),n=new Set;for(let r of t.split(`
|
|
395
|
+
`)){if(!r||r.split("/").some(o=>tx.has(o)))continue;let i=ZS(r).toLowerCase();i&&n.add(i)}return n}catch{return null}}function gj(e,t){return t?.length?t.some(n=>e.has(n)):!1}function XS(e,t){let n=e.indexOf(t);n!==-1&&e.splice(n,1)}import{createHash as Xd}from"crypto";import{closeSync as ox,chmodSync as hj,copyFileSync as yj,constants as bj,existsSync as de,fsyncSync as Sj,mkdirSync as nx,openSync as sx,readFileSync as yi,readSync as xj,readdirSync as Cj,renameSync as Yd,rmSync as cc,statSync as lc}from"fs";import{basename as ax,dirname as Bt,join as ie,relative as rx}from"path";function cx(e){let t=gt(e.outputDb),n=Ij(e);e.onStage?.("after-recovery-retained");let r=e.preserveOutputScip?e.outputScip:e.tempOutputScip,i=Zd({generationRoot:t,databasePath:e.tempOutputDb,indexPath:de(r)?r:void 0,metadataPath:de(e.tempMetaPath)?e.tempMetaPath:void 0}),o=(e.now??(()=>new Date))().toISOString(),s={version:hr,currentGeneration:i.identity,artifactSet:"immutable-v1",...n?{previousGeneration:n}:{},...e.publication?{publication:e.publication}:{},publishedAt:o};rt(ie(t,"state.json"),s,{spacing:2,trailingNewline:!0}),e.onStage?.("after-pointer-handoff"),e.preserveOutputScip||Jd(e.tempOutputScip,e.outputScip),e.onStage?.("after-scip-handoff"),Jd(e.tempOutputDb,e.outputDb),e.onStage?.("after-database-handoff"),Jd(e.tempMetaPath,e.metaPath),e.onStage?.("after-metadata-handoff");let a=i.identity,c={...s,stableMirrors:Qd(e.outputDb,e.outputScip)};return rt(ie(t,"state.json"),c,{spacing:2,trailingNewline:!0}),{currentGeneration:a,...n?{previousGeneration:n}:{}}}function Rj(e,t,n,r=()=>new Date){if(!de(e))return null;let i=di(e),o=ie(gt(e),"state.json");if(i?.artifactSet==="immutable-v1"&&Ga(e,i.currentGeneration))return i;let s=gt(e),a=!i&&de(o)?Ej(n,e,t):void 0;if(a&&!Va(s,a))return null;let c=Zd({generationRoot:s,databasePath:e,indexPath:de(t)?t:void 0,metadataPath:de(n)?n:void 0,forcedIdentity:i?.currentGeneration??a}),l={version:hr,currentGeneration:c.identity,artifactSet:"immutable-v1",stableMirrors:Qd(e,t),...i?.previousGeneration?{previousGeneration:i.previousGeneration}:{},...i?.publication?{publication:i.publication}:{},publishedAt:i?.publishedAt??r().toISOString()};return rt(ie(s,"state.json"),l,{spacing:2,trailingNewline:!0}),l}function dse(e,t,n=()=>new Date){if(!de(e)||!de(t))throw new Error("metadata-only generation refresh requires stable database and metadata files");let r=di(e),i=gt(e),o=Zd({generationRoot:i,databasePath:e,indexPath:de(ie(Bt(e),"index.scip"))?ie(Bt(e),"index.scip"):void 0,metadataPath:t}),s=r&&r.currentGeneration!==o.identity?lx(e,r.currentGeneration):void 0,a={version:hr,currentGeneration:o.identity,artifactSet:"immutable-v1",stableMirrors:Qd(e,ie(Bt(e),"index.scip")),...s?{previousGeneration:s}:{},...r?.publication?{publication:r.publication}:{},publishedAt:n().toISOString()};return rt(ie(gt(e),"state.json"),a,{spacing:2,trailingNewline:!0}),a}function Mo(e,t=ie(Bt(e),"meta.json")){let n=ie(gt(e),"state.json");if(!de(n))return{state:"legacy",statePath:n};let r=di(e);if(!r)return{state:"invalid",statePath:n,reason:"generation state is malformed"};try{let i=Ga(e,r.currentGeneration),o=i!==null,s=i?vj(e,t,i,r):!1,a=r.previousGeneration?de(ie(Bt(e),r.previousGeneration.databasePath)):!0;return!s||!o||!a?{state:"drifted",statePath:n,currentMatches:s,recoveryExists:a,generation:r,reason:o?s?"retained recovery database is missing":"stable database or metadata no longer matches the published generation":"published immutable generation is missing"}:{state:"current",statePath:n,currentMatches:s,recoveryExists:a,generation:r}}catch(i){return{state:"drifted",statePath:n,currentMatches:!1,recoveryExists:!1,generation:r,reason:i instanceof Error?i.message:String(i)}}}function vj(e,t,n,r){if(r.stableMirrors&&(r.stableMirrors.databaseFileIdentity!==dn(e)||r.stableMirrors.indexFileIdentity!==void 0&&r.stableMirrors.indexFileIdentity!==dn(ie(Bt(e),"index.scip")))||!ix(e,n.database))return!1;let i=ie(Bt(e),"index.scip");if(n.index&&!ix(i,n.index))return!1;if(!n.metadata)return!de(t);if(!de(t))return!1;let o=ie(gt(e),n.identity,n.metadata.file);return de(o)&&jn(yi(t,"utf8"))===jn(yi(o,"utf8"))}function ix(e,t){return de(e)&&lc(e).isFile()&&lc(e).size===t.size}function Ij(e){let t=Rj(e.outputDb,e.outputScip,e.metaPath);return t?lx(e.outputDb,t.currentGeneration):void 0}function Qd(e,t){return{databaseFileIdentity:dn(e),...de(t)?{indexFileIdentity:dn(t)}:{}}}function lx(e,t){let n=ie(gt(e),t),r=ie(n,ax(e)),i=ie(n,"meta.json");return{generationIdentity:t,databasePath:rx(Bt(e),r),...de(i)?{metadataPath:rx(Bt(e),i)}:{}}}function wj(e){if(de(e))for(let t of Cj(e,{withFileTypes:!0}))t.isDirectory()&&t.name.endsWith(".tmp")&&cc(ie(e,t.name),{recursive:!0,force:!0})}function Ej(e,t,n=ie(Bt(t),"index.scip")){let r=Xd("sha256").update("sqlite-generation-artifacts-v1\0");return r.update(uc(t)),de(n)&&r.update(`\0${uc(n)}`),de(e)&&r.update(`\0${jn(yi(e,"utf8"))}`),r.digest("hex")}function Zd(e){let t=zd(e.databasePath),n=e.indexPath?zd(e.indexPath):void 0,r=e.metadataPath?zd(e.metadataPath):void 0,i=e.forcedIdentity??Dj(t,n,e.metadataPath),o=ie(e.generationRoot,i),s=ie(o,qa);if(de(s)){let c=Va(e.generationRoot,i);if(c&&ux(o,c.database,t)&&Pj(o,c.index,n)&&Fj(o,c.metadata,e.metadataPath))return{identity:i};throw new Error(`SQLite generation ${i} already exists with different or corrupt artifacts.`)}nx(e.generationRoot,{recursive:!0}),wj(e.generationRoot);let a=`${o}.${process.pid}.${Date.now()}.tmp`;cc(a,{recursive:!0,force:!0}),nx(a,{recursive:!0});try{Kd(e.databasePath,ie(a,t.file)),n&&e.indexPath&&Kd(e.indexPath,ie(a,n.file)),r&&e.metadataPath&&Kd(e.metadataPath,ie(a,r.file)),rt(ie(a,qa),{version:Id,identity:i,database:t,...n?{index:n}:{},...r?{metadata:r}:{}},{spacing:2,trailingNewline:!0}),Yd(a,o),vt(e.generationRoot)}finally{cc(a,{recursive:!0,force:!0})}return{identity:i}}function Dj(e,t,n){let r=Xd("sha256").update("sqlite-generation-artifacts-v1\0");return r.update(e.sha256),t&&r.update(`\0${t.sha256}`),n&&r.update(`\0${jn(yi(n,"utf8"))}`),r.digest("hex")}function zd(e){return{file:ax(e),size:lc(e).size,sha256:uc(e)}}function uc(e){let t=Xd("sha256"),n=sx(e,"r"),r=Buffer.allocUnsafe(1024*1024);try{for(;;){let i=kj(n,r);if(i===0)break;t.update(r.subarray(0,i))}}finally{ox(n)}return t.digest("hex")}function kj(e,t){let n=0;for(;n<t.length;){let r=xj(e,t,n,t.length-n,null);if(n+=r,r===0)break}return n}function Kd(e,t){yj(e,t,bj.COPYFILE_FICLONE);let n=sx(t,"r");try{Sj(n)}finally{ox(n)}hj(t,292)}function ux(e,t,n){let r=ie(e,t.file);return t.file===n.file&&t.size===n.size&&t.sha256===n.sha256&&de(r)&&lc(r).size===t.size&&uc(r)===t.sha256}function Pj(e,t,n){return!t||!n?t===n:ux(e,t,n)}function Fj(e,t,n){if(!t||!n)return t===void 0&&n===void 0;let r=ie(e,t.file);return de(r)&&jn(yi(r,"utf8"))===jn(yi(n,"utf8"))}function Jd(e,t){cc(`${t}.tmp-replace`,{force:!0}),Yd(e,`${t}.tmp-replace`),Yd(`${t}.tmp-replace`,t)}function mx(e,t,n){let r=new Date().toISOString();if(!dx(n.dbPath))return{state:"missing",checkedAt:r,metaPath:n.metaPath,reason:"No SQLite index database exists.",remedy:"Run: scip-query reindex"};if(!dx(n.metaPath))return{state:"unknown",checkedAt:r,metaPath:n.metaPath,reason:"No reindex metadata file exists next to the SQLite index.",remedy:"Run: scip-query reindex"};try{let i=Tt(Tj(n.metaPath,"utf-8"));if(i.kind==="unsupported")return{state:"unknown",checkedAt:r,metaPath:n.metaPath,reason:`Reindex metadata version ${i.version} is unsupported by this scip-query build.`,remedy:"Upgrade scip-query or run: scip-query reindex"};if(i.kind==="malformed")return{state:"unknown",checkedAt:r,metaPath:n.metaPath,reason:`Could not decode reindex metadata: ${i.reason}`,remedy:"Run: scip-query reindex"};let o=i.metadata,s=t.languages??Lo(e),a=_j(e,s,t),c=[...o.indexedLanguages??[]].sort(),l=i.capabilities.publishableGeneration&&JSON.stringify(o.fingerprint)===JSON.stringify(a)&&JSON.stringify(c)===JSON.stringify(a.languages),u=Mo(n.dbPath,n.metaPath),d=u.state==="invalid"||u.state==="drifted",m=l&&!d;return{state:m?"fresh":"stale",checkedAt:r,metaPath:n.metaPath,updatedAt:o.updatedAt,lastRefresh:o.lastRefresh,reason:d?`SQLite generation requires repair: ${u.reason}`:l?"Index metadata fingerprint matches current source files.":"Index metadata fingerprint differs from current source files.",remedy:m?void 0:"Run: scip-query reindex"}}catch(i){return{state:"unknown",checkedAt:r,metaPath:n.metaPath,reason:`Could not read reindex metadata: ${i instanceof Error?i.message:String(i)}`,remedy:"Run: scip-query reindex"}}}function _j(e,t,n){return fo(e,t,{pnpmWorkspaces:n.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:n.indexer?.typescript?.projectMode,typescriptProjects:n.indexer?.typescript?.projects,clojureConfigPath:n.indexer?.clojure?.configPath})}import{createHash as Wx,randomUUID as CB}from"crypto";import{constants as RB,copyFileSync as Hx,existsSync as Gn,lstatSync as vB,mkdirSync as Vn,mkdtempSync as zx,readdirSync as IB,readFileSync as Ht,realpathSync as wB,renameSync as vr,rmSync as qn,statSync as EB}from"fs";import{dirname as Kx,join as A,resolve as Et}from"path";import{setTimeout as DB}from"timers/promises";import{pathToFileURL as Ux}from"url";import{deserializeSCIP as Jx}from"@c4312/scip";import kB from"better-sqlite3";import{join as Lj}from"path";var Mj=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e.pid;return typeof t=="number"&&Number.isSafeInteger(t)&&t>0?{pid:t}:null};function tm(e,t={}){return nm(Lj(e,"gc.lock"),t)}function nm(e,t={}){let n=t.waitMs??0,r=t.pollMs??10,i=t.now??we,o=i()+n;do{let s=fx(e);if(s)return px(s);let a=o-i();if(a<=0)return null;Aj(Math.min(r,a))}while(i()<=o);return null}async function Rse(e,t={}){let n=t.waitMs??0,r=t.pollMs??10,i=t.now??we,o=i()+n;do{Oj(t.signal);let s=fx(e);if(s)return px(s);let a=o-i();if(a<=0)return null;await Nj(Math.min(r,a),t.signal)}while(i()<=o);return null}function fx(e){let t=gi(e,{kind:"generic",parseLegacy:Mj});return t.kind==="acquired"?t.lock:null}function px(e){return{release:()=>{e.release()}}}function Aj(e){let t=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));Atomics.wait(t,0,0,e)}function Nj(e,t){return t?.aborted?Promise.reject(em(t)):new Promise((n,r)=>{let i=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e),o=()=>{clearTimeout(i),t?.removeEventListener("abort",o),r(t?em(t):new Error("Lock acquisition was aborted."))};t?.addEventListener("abort",o,{once:!0})})}function Oj(e){if(e?.aborted)throw em(e)}function em(e){return e.reason instanceof Error?e.reason:new Error("Lock acquisition was aborted.")}import{lstatSync as Qj,readdirSync as Zj}from"fs";import{join as eB,relative as tB,resolve as dm,sep as nB}from"path";import{createHash as jj}from"crypto";import{existsSync as im,mkdirSync as Bj,readFileSync as dc,readdirSync as Ese,renameSync as $j,rmSync as Dse,writeFileSync as Hj}from"fs";import{join as bi}from"path";import{create as hx,fromBinary as yx,toBinary as Uj}from"@bufbuild/protobuf";import{deserializeSCIP as mc,DocumentSchema as om,IndexSchema as bx,serializeSCIP as Sx}from"@c4312/scip";var fc=1,Ao="typescript-scip-fragments";function _se(e){if(e.length===0)throw new Error("affected TypeScript mini index requires documents");let t=new Set,n=[];for(let o of e){let s=Cr(o.relativePath);if(t.has(s))throw new Error(`duplicate TypeScript fragment replacement: ${s}`);if(t.add(s),o.bytes===null)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${s}`);let a=yx(om,o.bytes);if(a.relativePath!==s)throw new Error(`TypeScript fragment path mismatch: expected ${s}, got ${a.relativePath}`);n.push(a)}let r=Sx(hx(bx,{documents:n,externalSymbols:[]})),i=mc(r);if(i.documents.length!==n.length||i.externalSymbols.length!==0)throw new Error("affected TypeScript SCIP index failed structural verification");return r}function pc(e){let t=bi(e,Ao);return{rootDir:t,blobDir:bi(t,"blobs"),generationDir:bi(t,"generations")}}function qj(e){let t=mc(e.indexBytes);kx(t.metadata,Px(e)),Dx(t.externalSymbols);let n=new Set,r=[];for(let o of t.documents){let s=Cr(o.relativePath);if(n.has(s))throw new Error(`duplicate TypeScript SCIP document path: ${s}`);n.add(s);let a=Uj(om,o),c=e.documentIdentities.get(s)??(e.allowUntrackedDocuments?Rr(JSON.stringify({version:1,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,untrackedDocument:s,contentHash:Rr(a)})):null);if(!c)throw new Error(`missing TypeScript document identity: ${s}`);r.push(vx(e.cacheDir,{relativePath:s,bytes:a,occurrences:o.occurrences.length,symbols:o.symbols.length,referenceFragments:[]},c))}let i=Ix(e,r);return wx(e.cacheDir,i),i}function Lse(e){let t=pc(e.cacheDir);if(!im(sm(t,e.generationIdentity)))return qj(e);let n=xx({cacheDir:e.cacheDir,generationIdentity:e.generationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity});if(!e.allowUntrackedDocuments&&n.manifest.documents.length!==e.documentIdentities.size)throw new Error("TypeScript fragment generation document identities changed");for(let r of n.manifest.documents){let i=e.documentIdentities.get(r.relativePath);if(!(i===void 0&&e.allowUntrackedDocuments)&&i!==r.documentIdentity)throw new Error(`TypeScript fragment generation document identity changed: ${r.relativePath}`)}return n.manifest}function Mse(e){let t=xx({cacheDir:e.cacheDir,generationIdentity:e.previousGenerationIdentity,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity}).manifest,n=new Map(t.documents.map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let s=Cr(o.relativePath);if(r.has(s))throw new Error(`duplicate TypeScript fragment replacement: ${s}`);if(r.add(s),!n.has(s))throw new Error(`TypeScript fragment replacement has no prior document: ${s}`);let a=e.documentIdentities.get(s);if(!a)throw new Error(`missing TypeScript document identity: ${s}`);o.bytes===null?n.delete(s):n.set(s,vx(e.cacheDir,o,a))}if(r.size===0)throw new Error("TypeScript fragment generation requires at least one replacement");let i=Ix(e,[...n.values()]);return wx(e.cacheDir,i),i}function xx(e){let t=pc(e.cacheDir),n=sm(t,e.generationIdentity),r;try{r=Ex(dc(n,"utf8"))}catch(o){throw new Error(`TypeScript fragment generation is unavailable: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(r.generationIdentity!==e.generationIdentity)throw new Error("TypeScript fragment generation identity does not match its manifest path");if(e.producerIdentity&&r.producerIdentity!==e.producerIdentity)throw new Error("TypeScript fragment producer identity changed");if(e.projectIdentity&&r.projectIdentity!==e.projectIdentity)throw new Error("TypeScript fragment project identity changed");let i=new Map;for(let o of r.documents){let s=bi(t.blobDir,`${o.blobHash}.scipdoc`),a=dc(s);if(a.byteLength!==o.byteLength||Rr(a)!==o.blobHash)throw new Error(`TypeScript fragment blob is corrupt: ${o.relativePath}`);i.set(o.relativePath,a)}return{manifest:r,fragments:i}}function Cx(e){let t=Rx(e);return rm(t.baseIndex,t.completeDocuments,"assembled")}function Ase(e){let t=Rx(e);return Gj(t.deletedAffectedPaths),{completeIndexBytes:rm(t.baseIndex,t.completeDocuments,"assembled"),affectedIndexBytes:rm(t.baseIndex,t.affectedDocuments,"affected")}}function Rx(e){let t=mc(e.baseIndexBytes);kx(t.metadata,Px(e)),Dx(t.externalSymbols);let n=new Map;for(let a of e.fragments){let c=Cr(a.relativePath);if(n.has(c))throw new Error(`duplicate TypeScript fragment replacement: ${c}`);n.set(c,a)}if(n.size===0)throw new Error("TypeScript index assembly requires at least one replacement");let r=new Set,i=[],o=[],s=[];for(let a of t.documents){let c=Cr(a.relativePath);if(r.has(c))throw new Error(`duplicate TypeScript SCIP document path: ${c}`);r.add(c);let l=n.get(c);if(!l){i.push(a);continue}if(n.delete(c),l.bytes===null){s.push(c);continue}let u=yx(om,l.bytes);if(u.relativePath!==c)throw new Error(`TypeScript fragment path mismatch: expected ${c}, got ${u.relativePath}`);i.push(u),o.push(u)}if(n.size>0)throw new Error(`TypeScript fragment replacement has no prior document: ${[...n.keys()].sort()[0]}`);return{baseIndex:t,completeDocuments:i,affectedDocuments:o,deletedAffectedPaths:s}}function rm(e,t,n){let r=Sx(hx(bx,{metadata:e.metadata,documents:t,externalSymbols:[]})),i=mc(r);if(i.documents.length!==t.length||i.externalSymbols.length!==0)throw new Error(`${n} TypeScript SCIP index failed structural verification`);return r}function Gj(e){if(e.length>0)throw new Error(`affected TypeScript mini index cannot contain a deleted document: ${e[0]}`)}function vx(e,t,n){if(t.bytes===null)throw new Error(`cannot persist an empty TypeScript fragment: ${t.relativePath}`);let r=Cr(t.relativePath),i=Buffer.from(t.bytes),o=Rr(i),s=pc(e);Bj(s.blobDir,{recursive:!0});let a=bi(s.blobDir,`${o}.scipdoc`);if(im(a)){let c=dc(a);if(c.byteLength!==i.byteLength||Rr(c)!==o)throw new Error(`existing TypeScript fragment blob is corrupt: ${r}`)}else{let c=`${a}.${process.pid}.${Date.now()}.tmp`;Hj(c,i),$j(c,a)}return{relativePath:r,blobHash:o,byteLength:i.byteLength,documentIdentity:n}}function Ix(e,t){if(!e.producerIdentity||!e.projectIdentity||!e.generationIdentity)throw new Error("TypeScript fragment generation identities must be non-empty");let n=[...t].sort((r,i)=>r.relativePath.localeCompare(i.relativePath));if(new Set(n.map(r=>r.relativePath)).size!==n.length)throw new Error("TypeScript fragment generation contains duplicate document paths");return{version:fc,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),documents:n}}function wx(e,t){let n=pc(e),r=sm(n,t.generationIdentity);if(im(r)){let i=Ex(dc(r,"utf8"));if(gx(i)!==gx(t))throw new Error(`TypeScript fragment generation is immutable: ${t.generationIdentity}`);return}Ia(r,t,{spacing:2,trailingNewline:!0})}function gx(e){return Rr(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,generationIdentity:e.generationIdentity,documents:e.documents}))}function Ex(e){let t=JSON.parse(e);if(t.version!==fc||typeof t.producerIdentity!="string"||typeof t.projectIdentity!="string"||typeof t.generationIdentity!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.documents))throw new Error("invalid TypeScript fragment generation manifest");let n=new Set;for(let r of t.documents){if(!r||typeof r.relativePath!="string"||typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash)||typeof r.byteLength!="number"||!Number.isInteger(r.byteLength)||r.byteLength<0||typeof r.documentIdentity!="string"||!r.documentIdentity)throw new Error("invalid TypeScript fragment record");if(Cr(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript fragment record");n.add(r.relativePath)}return t}function sm(e,t){return bi(e.generationDir,Vj(t))}function Vj(e){if(!e)throw new Error("TypeScript fragment generation identity must be non-empty");return`${Rr(e)}.json`}function Dx(e){if(e.length>0)throw new Error("scip-typescript emitted external symbols; incremental document assembly is unsupported")}function kx(e,t){if(!e||typeof e!="object")throw new Error("TypeScript SCIP shard has no producer metadata");let n=e,r=n.toolInfo??n.tool_info;if(!r||typeof r!="object")throw new Error("TypeScript SCIP shard has no producer tool identity");let i=r;if(i.name!=="scip-typescript"||i.version!==t)throw new Error("TypeScript SCIP shard producer identity changed")}function Px(e){let t=e.packageVersion??e.runtime?.packageVersion;if(!t)throw new Error("scip-typescript package version is unavailable");return t}function Cr(e){if(!e||e.startsWith("/")||e.startsWith("\\")||e.includes("\\"))throw new Error(`invalid TypeScript SCIP document path: ${e}`);let t=e.split("/");if(t.includes("")||t.includes(".")||t.includes(".."))throw new Error(`invalid TypeScript SCIP document path: ${e}`);return e}function Rr(e){return jj("sha256").update(e).digest("hex")}import{createHash as Wj}from"crypto";import{existsSync as No,mkdirSync as zj,readFileSync as jo,readdirSync as am,renameSync as Kj,rmSync as Fx,writeFileSync as Jj}from"fs";import{join as wt}from"path";var gc=1,Use=64*1024*1024,Bo="typescript-scip-overlays";function qse(e){let t=_x(e.cacheDir,e.previousGenerationIdentity);if(!t&&!e.baseShardCurrent)throw new Error("deferred TypeScript SCIP base has no matching overlay generation");if(t&&(t.producerIdentity!==e.producerIdentity||t.projectIdentity!==e.projectIdentity))throw new Error("TypeScript overlay producer or project identity changed");let n=new Map((t?.overlays??[]).map(o=>[o.relativePath,o])),r=new Set;for(let o of e.fragments){let s=um(o.relativePath);if(r.has(s))throw new Error(`duplicate TypeScript overlay: ${s}`);r.add(s),n.set(s,Yj(e.cacheDir,o))}if(r.size===0)throw new Error("TypeScript overlay generation requires affected documents");let i={version:gc,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:t?.baseGenerationIdentity??e.previousGenerationIdentity,generationIdentity:e.nextGenerationIdentity,createdAt:(e.now??(()=>new Date))().toISOString(),overlays:[...n.values()].sort((o,s)=>o.relativePath.localeCompare(s.relativePath))};return Xj(e.cacheDir,i),i}function Gse(e){let t=_x(e.cacheDir,e.generationIdentity);if(!t)throw new Error("TypeScript overlay generation is unavailable");let n=t.overlays.map(r=>{if(r.blobHash===null)return{relativePath:r.relativePath,bytes:null,occurrences:0,symbols:0,referenceFragments:[]};let i=jo(wt($o(e.cacheDir),"blobs",`${r.blobHash}.scipdoc`));if(i.byteLength!==r.byteLength||Oo(i)!==r.blobHash)throw new Error(`TypeScript overlay blob is corrupt: ${r.relativePath}`);return{relativePath:r.relativePath,bytes:i,occurrences:0,symbols:0,referenceFragments:[]}});return Cx({packageVersion:e.packageVersion,baseIndexBytes:e.baseIndexBytes,fragments:n})}function Vse(e,t){let n=$o(e),r=wt(n,"generations");if(!No(r))return;let i=new Set(t.map(lm)),o=new Set;for(let a of am(r).filter(c=>i.has(c))){let c=cm(jo(wt(r,a),"utf8"));for(let l of c.overlays)l.blobHash&&o.add(`${l.blobHash}.scipdoc`)}for(let a of am(r))i.has(a)||Fx(wt(r,a),{force:!0});let s=wt(n,"blobs");if(No(s))for(let a of am(s))o.has(a)||Fx(wt(s,a),{force:!0})}function _x(e,t){let n=wt($o(e),"generations",lm(t));if(!No(n))return null;let r=cm(jo(n,"utf8"));if(r.generationIdentity!==t)throw new Error("TypeScript overlay generation identity does not match its path");return r}function Yj(e,t){let n=um(t.relativePath);if(t.bytes===null)return{relativePath:n,blobHash:null,byteLength:0};let r=Buffer.from(t.bytes),i=Oo(r),o=wt($o(e),"blobs");zj(o,{recursive:!0});let s=wt(o,`${i}.scipdoc`);if(No(s)){let a=jo(s);if(a.byteLength!==r.byteLength||Oo(a)!==i)throw new Error(`existing TypeScript overlay blob is corrupt: ${n}`)}else{let a=`${s}.${process.pid}.${Date.now()}.tmp`;Jj(a,r),Kj(a,s)}return{relativePath:n,blobHash:i,byteLength:r.byteLength}}function Xj(e,t){let n=wt($o(e),"generations",lm(t.generationIdentity));if(No(n)){let r=cm(jo(n,"utf8"));if(Tx(r)!==Tx(t))throw new Error(`TypeScript overlay generation is immutable: ${t.generationIdentity}`);return}Ia(n,t,{spacing:2,trailingNewline:!0})}function cm(e){let t=JSON.parse(e);if(t.version!==gc||typeof t.producerIdentity!="string"||!t.producerIdentity||typeof t.projectIdentity!="string"||!t.projectIdentity||typeof t.baseGenerationIdentity!="string"||!t.baseGenerationIdentity||typeof t.generationIdentity!="string"||!t.generationIdentity||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!Array.isArray(t.overlays))throw new Error("invalid TypeScript overlay manifest");let n=new Set;for(let r of t.overlays){if(!r||typeof r.relativePath!="string"||r.blobHash!==null&&(typeof r.blobHash!="string"||!/^[a-f0-9]{64}$/.test(r.blobHash))||!Number.isInteger(r.byteLength)||r.byteLength<0||r.blobHash===null&&r.byteLength!==0)throw new Error("invalid TypeScript overlay record");if(um(r.relativePath),n.has(r.relativePath))throw new Error("duplicate TypeScript overlay record");n.add(r.relativePath)}return t}function $o(e){return wt(e,Bo)}function lm(e){if(!e)throw new Error("TypeScript overlay generation identity must be non-empty");return`${Oo(e)}.json`}function Tx(e){return Oo(JSON.stringify({version:e.version,producerIdentity:e.producerIdentity,projectIdentity:e.projectIdentity,baseGenerationIdentity:e.baseGenerationIdentity,generationIdentity:e.generationIdentity,overlays:e.overlays}))}function um(e){if(!e||e.startsWith("/")||e.includes("\\")||e.split("/").some(t=>!t||t==="."))throw new Error(`invalid TypeScript overlay path: ${e}`);if(e.split("/").includes(".."))throw new Error(`invalid TypeScript overlay path: ${e}`);return e}function Oo(e){return Wj("sha256").update(e).digest("hex")}var Ho=1,mm="language-indexes",Lx=["index.db","index.scip","meta.json"],Mx=[mm,Ao,Bo];function hc(e){let t=[];for(let n of Lx)rB(e,n),t.push(n);for(let n of Mx)Ax(e,n,t);return{version:Ho,files:t.sort()}}function yc(e){if(!e||e.includes("\0")||e.startsWith("/")||e.includes("\\"))throw new Error(`invalid index artifact path: ${e||"<empty>"}`);let t=e.split("/");if(t.some(r=>!r||r==="."||r===".."))throw new Error(`invalid index artifact path: ${e}`);let n=t[0];if(!Lx.includes(e)&&!Mx.includes(n))throw new Error(`index artifact path is not shareable: ${e}`);return e}function $t(e,t){let n=yc(t),r=dm(e),i=dm(r,...n.split("/"));if(i!==r&&!i.startsWith(`${r}${nB}`))throw new Error(`index artifact escapes cache: ${t}`);return i}function Ax(e,t,n){let r=eB(e,t),i;try{i=Zj(r,{withFileTypes:!0,encoding:"utf8"})}catch{return}for(let o of i){let s=`${t}/${o.name}`;if(o.isSymbolicLink())throw new Error(`index artifact cannot be a symlink: ${s}`);o.isDirectory()?Ax(e,s,n):o.isFile()&&n.push(yc(s))}}function rB(e,t){let n=$t(e,t),r;try{r=Qj(n)}catch{throw new Error(`required index artifact is missing: ${t}`)}if(!r.isFile()||r.isSymbolicLink())throw new Error(`required index artifact is not a regular file: ${t}`);if(tB(dm(e),n).startsWith(".."))throw new Error(`index artifact escapes cache: ${t}`)}import{readFileSync as pm,writeFileSync as gm}from"fs";import{create as Uo}from"@bufbuild/protobuf";import{deserializeSCIP as hm,serializeSCIP as ym,DocumentSchema as dB,IndexSchema as Ox,MetadataSchema as mB,SymbolInformationSchema as fB}from"@c4312/scip";import{readFileSync as iB,writeFileSync as oB}from"fs";import{create as Nx}from"@bufbuild/protobuf";import{deserializeSCIP as sB,DocumentSchema as aB,IndexSchema as cB,serializeSCIP as lB,SymbolRole as uB}from"@c4312/scip";function tae(e){let t;try{t=sB(iB(e))}catch{return{removedDefinitionOccurrences:0,touchedDocuments:0}}let n=fm(t);return n.removedDefinitionOccurrences>0&&oB(e,Buffer.from(lB(n.index))),{removedDefinitionOccurrences:n.removedDefinitionOccurrences,touchedDocuments:n.touchedDocuments}}function fm(e){let t=new Set;for(let o of e.documents)for(let s of o.symbols)s.symbol&&t.add(s.symbol);for(let o of e.externalSymbols)o.symbol&&t.add(o.symbol);let n=0,r=0,i=[];for(let o of e.documents){let s=o.occurrences.filter(a=>(a.symbolRoles&uB.Definition)===0||t.has(a.symbol)?!0:(n+=1,!1));if(s.length===o.occurrences.length){i.push(o);continue}r+=1,i.push(Nx(aB,{language:o.language,relativePath:o.relativePath,occurrences:s,symbols:o.symbols,text:o.text,positionEncoding:o.positionEncoding}))}return{index:n===0?e:Nx(cB,{metadata:e.metadata,documents:i,externalSymbols:e.externalSymbols}),removedDefinitionOccurrences:n,touchedDocuments:r}}function jx(e){if(e.length===0)throw new Error("Cannot merge zero SCIP indexes");if(e.length===1)return e[0];let t=gB(e),n=hB(e.flatMap(i=>i.documents??[])),r=$x(e.flatMap(i=>i.externalSymbols??[]));return Uo(Ox,{metadata:t,documents:n,externalSymbols:r})}function aae(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>hm(pm(i))),r=jx(n);return gm(t,Buffer.from(ym(r))),{documentCount:r.documents.length,externalSymbolCount:r.externalSymbols.length,inputCount:e.length}}function cae(e,t){if(e.length===0)throw new Error("Cannot merge zero SCIP files");let n=e.map(i=>hm(pm(i))),r=fm(jx(n));return gm(t,Buffer.from(ym(r.index))),{documentCount:r.index.documents.length,externalSymbolCount:r.index.externalSymbols.length,inputCount:e.length,removedDefinitionOccurrences:r.removedDefinitionOccurrences,touchedDocuments:r.touchedDocuments}}function pB(e,t,n){let r=e.metadata;if(!r)throw new Error("Cannot rebase a SCIP index without metadata");if(r.projectRoot!==t)throw new Error(`Cannot rebase SCIP project root: expected ${t}, got ${r.projectRoot}`);return Uo(Ox,{metadata:Uo(mB,{...r,projectRoot:n}),documents:e.documents,externalSymbols:e.externalSymbols})}function Bx(e,t,n){let r=hm(pm(e)),i=pB(r,t,n);gm(e,Buffer.from(ym(i)))}function gB(e){let t=e[0]?.metadata;if(!t)return;let n=t.projectRoot;for(let r of e.slice(1)){let i=r.metadata?.projectRoot;if(n&&i&&i!==n)throw new Error(`Cannot merge SCIP indexes with different project roots: ${n} vs ${i}`)}return t}function hB(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);if(!r){t.set(n.relativePath,n);continue}t.set(n.relativePath,Uo(dB,{language:r.language||n.language,relativePath:r.relativePath||n.relativePath,occurrences:yB([...r.occurrences,...n.occurrences]),symbols:$x([...r.symbols,...n.symbols]),text:SB(r.text,n.text),positionEncoding:r.positionEncoding||n.positionEncoding}))}return[...t.values()]}function yB(e){let t=new Set,n=[];for(let r of e){let i=JSON.stringify(r);t.has(i)||(t.add(i),n.push(r))}return n}function $x(e){let t=new Map;for(let n of e){let r=t.get(n.symbol);if(!r){t.set(n.symbol,n);continue}t.set(n.symbol,Uo(fB,{symbol:r.symbol,documentation:xB([...r.documentation,...n.documentation]),relationships:bB([...r.relationships,...n.relationships]),kind:r.kind||n.kind,displayName:r.displayName||n.displayName,enclosingSymbol:r.enclosingSymbol||n.enclosingSymbol,signatureDocumentation:r.signatureDocumentation??n.signatureDocumentation}))}return[...t.values()]}function bB(e){let t=new Set,n=[];for(let r of e){let i=[r.symbol,r.isReference?"1":"0",r.isImplementation?"1":"0",r.isTypeDefinition?"1":"0",r.isDefinition?"1":"0"].join("|");t.has(i)||(t.add(i),n.push(r))}return n}function SB(e,t){return e?t?e.length>=t.length?e:t:e:t}function xB(e){return[...new Set(e)]}var Cm=1,qx="SCIP_QUERY_SHARED_CACHE",bm=JSON.stringify({cliVersion:It,artifactCatalogVersion:Ho,sqliteGenerationStoreVersion:hr,typescriptFragmentStoreVersion:fc,typescriptOverlayStoreVersion:gc}),Yx="manifest.json",Xx="shared-cache.json",Rm=[mm,Ao,Bo];function bc(e,t){if(!e.clean||!e.treeOid)return;let n=Vo(JSON.stringify({version:Cm,repositoryId:e.repositoryId,treeOid:e.treeOid,fingerprint:t,producerIdentity:bm}));return{repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,fingerprint:t,producerIdentity:bm,generationId:n,repositoryCacheDir:To(e.repositoryId)}}function Qx(e,t,n){if(process.env[qx]==="0")return`${qx}=0`;if(!Nd(n))return"explicit cache or database override";if(Et(t)!==Et(A(Za(e),"index.db")))return"index database is outside the managed worktree cache"}function Zx(e,t,n){if(!Nd(t))return;let r=n??Nr(e);return r?A(To(r.repositoryId),"evidence.db"):void 0}function Ir(e,t=!0){let n=wm(e),r;try{r=PB(Ht(A(n,Yx),"utf8"))}catch{return null}if(r.generationId!==e.generationId||r.repositoryId!==e.repositoryId||r.treeOid!==e.treeOid||r.producerIdentity!==e.producerIdentity||JSON.stringify(r.fingerprint)!==JSON.stringify(e.fingerprint))return null;if(!t)return r;try{for(let i of r.artifacts){let o=$t(n,i.path),s=EB(o);if(!s.isFile()||s.size!==i.size||Vo(Ht(o))!==i.sha256)return null}}catch{return null}return r}function eC(e){let t=Ir(e.snapshot);if(t)return t;if(!Si(e.sourceCacheDir,e.sourceProjectRoot,e.snapshot.fingerprint))throw new Error("source index is incomplete, incompatible, or corrupt");let n=Gx(e.sourceCacheDir);if(!n)throw new Error("source index artifacts are incomplete");let r=hc(e.sourceCacheDir),i=A(e.snapshot.repositoryCacheDir,"generations");Vn(i,{recursive:!0});let o=zx(A(i,`.tmp-${process.pid}-`));try{let s=[];for(let d of r.files){let m=$t(e.sourceCacheDir,d),f=$t(o,d);Go(m,f);let p=Ht(f);s.push({path:d,size:p.byteLength,sha256:Vo(p)})}let a=Jx(Ht(A(o,"index.scip"))).metadata?.projectRoot;if(!a)throw new Error("shared SCIP generation has no project root metadata");let c=Em(e.sourceProjectRoot);if(a!==c)throw new Error("shared SCIP generation root does not match its source worktree");if(Gx(e.sourceCacheDir)!==n||e.sourceStillValid&&!e.sourceStillValid())throw new Error("source index changed while staging a shared generation");let l={version:Cm,artifactCatalogVersion:Ho,generationId:e.snapshot.generationId,repositoryId:e.snapshot.repositoryId,treeOid:e.snapshot.treeOid,fingerprint:e.snapshot.fingerprint,producerIdentity:e.snapshot.producerIdentity,sourceProjectRoot:e.sourceProjectRoot,scipProjectRoot:a,createdAt:(e.now??(()=>new Date))().toISOString(),artifacts:s.sort((d,m)=>d.path.localeCompare(m.path))};rt(A(o,Yx),l,{spacing:2,trailingNewline:!0});let u=wm(e.snapshot);try{if(Gn(u)&&!Ir(e.snapshot)){let d=`${u}.corrupt-${process.pid}-${Date.now()}`;vr(u,d),qn(d,{recursive:!0,force:!0})}vr(o,u)}catch(d){let m=Ir(e.snapshot);if(m)return m;throw d}return l}finally{qn(o,{recursive:!0,force:!0})}}function Sm(e){let t=wm(e.snapshot);Vn(e.targetCacheDir,{recursive:!0});let n=nm(A(e.targetCacheDir,"cache-lifecycle.lock"),{waitMs:3e4});if(!n)throw new Error("timed out waiting for another cache hydration");let r,i,o=!1;try{r=zx(A(e.targetCacheDir,".shared-hydrate-")),AB(e.manifest,e.snapshot);for(let c of e.manifest.artifacts){let l=$t(t,c.path),u=$t(r,c.path);Go(l,u);let d=Ht(u);if(d.byteLength!==c.size||Vo(d)!==c.sha256)throw new Error(`shared artifact is corrupt: ${c.path}`)}let s=Em(e.targetProjectRoot);if(s!==e.manifest.scipProjectRoot)for(let c of e.manifest.artifacts)c.path.endsWith(".scip")&&Bx($t(r,c.path),e.manifest.scipProjectRoot,s);if(!Si(r,e.targetProjectRoot,e.snapshot.fingerprint,!1))throw new Error("staged shared generation failed completeness or integrity validation");i=_B(e.targetCacheDir,r),o=!0,LB(r,e.targetCacheDir,i),cx({tempOutputScip:A(r,"index.scip"),tempOutputDb:A(r,"index.db"),tempMetaPath:A(r,"meta.json"),outputScip:A(e.targetCacheDir,"index.scip"),outputDb:A(e.targetCacheDir,"index.db"),metaPath:A(e.targetCacheDir,"meta.json"),now:e.now});let a=Mo(A(e.targetCacheDir,"index.db"),A(e.targetCacheDir,"meta.json"));if(a.state==="invalid"||a.state==="drifted")throw new Error(`hydrated SQLite generation failed validation: ${a.reason}`);xm(e.snapshot,e.targetCacheDir,e.action??"attached",e.now)}catch(s){throw o&&i&&MB(e.targetCacheDir,i),s}finally{r&&qn(r,{recursive:!0,force:!0}),n.release()}}function tC(e,t,n,r){let i=Qx(e,n.dbPath,t);if(i)return{kind:"bypassed",reason:i};try{let o=r??Nr(e);if(!o)return{kind:"missed",reason:"Git worktree identity is unavailable"};if(!o.clean)return Sc(o,n.cacheDir,"missed",void 0,"worktree has uncommitted changes"),{kind:"missed",reason:"worktree has uncommitted changes"};let s=t.languages??Lo(e),a=fo(e,s,rC(t)),c=bc(o,a);if(!c)return{kind:"missed",reason:"clean committed snapshot is unavailable"};let l=Ir(c);if(l)return Sm({snapshot:c,manifest:l,targetCacheDir:n.cacheDir,targetProjectRoot:e}),{kind:"attached",generationId:c.generationId};let u=FB(c,e);return u?(l=u.manifest,Sm({snapshot:c,manifest:l,targetCacheDir:n.cacheDir,targetProjectRoot:e,action:"peer-imported"}),{kind:"peer-imported",generationId:c.generationId,sourceProjectRoot:u.sourceProjectRoot}):(Sc(o,n.cacheDir,"missed",void 0,"no exact shared or peer generation exists"),{kind:"missed",reason:"no exact shared or peer generation exists"})}catch(o){return{kind:"failed",reason:o instanceof Error?o.message:String(o)}}}function vm(e,t,n,r){let i=Qx(e,n.dbPath,t);if(i)return{kind:"bypassed",reason:i};try{let o=r??Nr(e);if(!o)return{kind:"missed",reason:"Git worktree identity is unavailable"};if(!o.clean)return Sc(o,n.cacheDir,"missed",void 0,"worktree is not a clean committed snapshot"),{kind:"missed",reason:"worktree is not a clean committed snapshot"};let s=t.languages??Lo(e),a=fo(e,s,rC(t)),c=bc(o,a);if(!c)return Sc(o,n.cacheDir,"missed",void 0,"worktree is not a clean committed snapshot"),{kind:"missed",reason:"worktree is not a clean committed snapshot"};let l=Ir(c);if(l)return Si(n.cacheDir,e,a)?(xm(c,n.cacheDir,"local-fresh"),{kind:"local-fresh"}):(Sm({snapshot:c,manifest:l,targetCacheDir:n.cacheDir,targetProjectRoot:e}),{kind:"attached",generationId:c.generationId});let u=xc(n.cacheDir);return!u||JSON.stringify(u.fingerprint)!==JSON.stringify(a)||JSON.stringify([...u.indexedLanguages??[]].sort())!==JSON.stringify([...s].sort())?{kind:"missed",reason:"local metadata does not match the clean worktree snapshot"}:Si(n.cacheDir,e,a)?(eC({snapshot:c,sourceCacheDir:n.cacheDir,sourceProjectRoot:e,sourceStillValid:()=>{let d=Nr(e);return(d?bc(d,a):void 0)?.generationId===c.generationId}}),xm(c,n.cacheDir,"built"),{kind:"built",generationId:c.generationId}):{kind:"missed",reason:"local index artifacts are incomplete or incompatible"}}catch(o){return{kind:"failed",reason:o instanceof Error?o.message:String(o)}}}async function _ae(e,t={}){let n=t.timeoutMs??3e4,r=t.pollMs??100,i=t.now??we,o=i()+n,s=A(e.repositoryCacheDir,"locks"),a=A(s,`${e.generationId}.lock`),c=l=>{if(!l||typeof l!="object"||Array.isArray(l))return null;let u=l.pid;return typeof u=="number"&&Number.isSafeInteger(u)&&u>0?{pid:u}:null};for(;i()<=o;){if(Ir(e))return{kind:"generation-ready"};let l=gi(a,{kind:"shared-generation-build",detail:{generationId:e.generationId},parseLegacy:c});if(l.kind==="acquired")return{kind:"owner",release:()=>l.lock.release()};let u=o-i();if(u<=0)break;await DB(Math.min(r,u))}return Ir(e)?{kind:"generation-ready"}:{kind:"timeout"}}function xm(e,t,n,r=void 0){let i={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,baseGenerationId:e.generationId,activeGenerationId:e.generationId,lastAction:n,lastSeenAt:(r??(()=>new Date))().toISOString()},o={...i,ownershipChecksum:Im(i)};return iC(e.repositoryCacheDir,o,!0),o}function Sc(e,t,n,r=void 0,i=void 0){let o={version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:e.projectRoot,treeOid:e.treeOid,localCacheDir:t,lastAction:n,...i?{lastReason:i}:{},lastSeenAt:(r??(()=>new Date))().toISOString()},s={...o,ownershipChecksum:Im(o)};return iC(To(e.repositoryId),s,!1),s}function Im(e){return Vo(JSON.stringify({version:1,repositoryId:e.repositoryId,worktreeId:e.worktreeId,projectRoot:Et(e.projectRoot),localCacheDir:Et(e.localCacheDir)}))}function nC(e,t,n=void 0,r,i={}){try{let o=Vx(t);if(!o)return null;let s=To(o.repositoryId);i.onBeforeRepositoryLock?.();let a=tm(s,{waitMs:5e3});if(!a)return null;try{let c=Vx(t);if(!c||c.repositoryId!==o.repositoryId||c.worktreeId!==o.worktreeId)return null;let l=A(s,"worktrees",`${c.worktreeId}.json`),u=JSON.parse(Ht(l,"utf8")),d=r??Nr(e);if(!d?.clean||!d.treeOid||u.version!==1||u.repositoryId!==c.repositoryId||u.worktreeId!==c.worktreeId||u.repositoryId!==d.repositoryId||u.worktreeId!==d.worktreeId||Et(u.projectRoot)!==Et(d.projectRoot)||u.treeOid!==d.treeOid||Et(u.localCacheDir)!==Et(t)||u.ownershipChecksum!==Im(u))return null;let m=xc(t);if(!NB(m?.fingerprint))return null;let f=bc(d,m.fingerprint);if(!f||f.repositoryCacheDir!==s||u.baseGenerationId!==f.generationId||u.activeGenerationId!==f.generationId||!Si(t,e,f.fingerprint,!0,!1))return null;let p=(n??(()=>new Date))();if(Number.isFinite(Date.parse(u.lastSeenAt))&&p.getTime()-Date.parse(u.lastSeenAt)<6e4)return u;let g={...u,lastSeenAt:p.toISOString()};return rt(l,g,{spacing:2,trailingNewline:!0}),g}finally{a.release()}}catch{return null}}function PB(e){let t=JSON.parse(e);if(t.version!==Cm||t.artifactCatalogVersion!==Ho||typeof t.generationId!="string"||!/^[a-f0-9]{64}$/.test(t.generationId)||typeof t.repositoryId!="string"||!/^[a-f0-9]{24}$/.test(t.repositoryId)||typeof t.treeOid!="string"||!t.treeOid||typeof t.producerIdentity!="string"||t.producerIdentity!==bm||typeof t.sourceProjectRoot!="string"||typeof t.scipProjectRoot!="string"||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))||!t.fingerprint||!Array.isArray(t.artifacts))throw new Error("invalid shared generation manifest");let n=new Set;for(let r of t.artifacts){if(!r||typeof r.path!="string"||typeof r.size!="number"||r.size<0||typeof r.sha256!="string"||!/^[a-f0-9]{64}$/.test(r.sha256))throw new Error("invalid shared generation artifact");if(yc(r.path),n.has(r.path))throw new Error(`duplicate shared generation artifact: ${r.path}`);n.add(r.path)}for(let r of["index.db","index.scip","meta.json"])if(!n.has(r))throw new Error(`shared generation is missing ${r}`);return t}function Go(e,t){Vn(Kx(t),{recursive:!0});try{Hx(e,t,RB.COPYFILE_FICLONE)}catch{Hx(e,t)}}function FB(e,t){for(let n of og(t)){if(Et(n.path)===Et(t))continue;let r=Za(n.path),i=xc(r);if(!(!i||JSON.stringify(i.fingerprint)!==JSON.stringify(e.fingerprint)||JSON.stringify([...i.indexedLanguages??[]].sort())!==JSON.stringify([...e.fingerprint.languages].sort()))&&Si(r,n.path,e.fingerprint))try{return{manifest:eC({snapshot:e,sourceCacheDir:r,sourceProjectRoot:n.path}),sourceProjectRoot:n.path}}catch{continue}}return null}function TB(e,t,n){Vn(e,{recursive:!0}),rt(A(e,Xx),{version:1,repositoryId:t,worktreeId:n},{spacing:2,trailingNewline:!0})}function Gx(e){try{let t=hc(e),n=Wx("sha256");for(let r of t.files){let i=Ht($t(e,r));n.update(r).update("\0").update(String(i.byteLength)).update("\0").update(i).update("\0")}return n.digest("hex")}catch{return null}}function xc(e){try{let t=Tt(Ht(A(e,"meta.json"),"utf8"));return(t.kind==="legacy"||t.kind==="supported")&&t.capabilities.publishableGeneration?t.metadata:void 0}catch{return}}function rC(e){return{pnpmWorkspaces:e.indexer?.typescript?.pnpmWorkspaces,typescriptProjectMode:e.indexer?.typescript?.projectMode,typescriptProjects:e.indexer?.typescript?.projects,clojureConfigPath:e.indexer?.clojure?.configPath}}function wm(e){return A(e.repositoryCacheDir,"generations",e.generationId)}function Vx(e){let t=JSON.parse(Ht(A(e,Xx),"utf8"));return t.version!==1||typeof t.repositoryId!="string"||!/^[a-f0-9]{24}$/.test(t.repositoryId)||typeof t.worktreeId!="string"||!/^[a-f0-9]{24}$/.test(t.worktreeId)?null:{version:t.version,repositoryId:t.repositoryId,worktreeId:t.worktreeId}}function iC(e,t,n){let r=tm(e,{waitMs:5e3});if(!r)throw new Error("repository cache cleanup is busy");try{if(n){let o=t.activeGenerationId;if(!o||!Gn(A(e,"generations",o)))throw new Error("shared generation disappeared before its lease was attached")}let i=A(e,"worktrees");Vn(i,{recursive:!0}),rt(A(i,`${t.worktreeId}.json`),t,{spacing:2,trailingNewline:!0}),TB(t.localCacheDir,t.repositoryId,t.worktreeId)}finally{r.release()}}function _B(e,t){let n=A(t,".rollback"),r=new Map,i=new Map;Vn(n,{recursive:!0});for(let a of["index.scip","index.db","meta.json"]){let c=A(e,a),l=Gn(c);r.set(a,l),l&&Go(c,A(n,"stable",a))}for(let a of Rm){let c=A(e,a),l=Gn(c);if(l){let u=vB(c);if(!u.isDirectory()||u.isSymbolicLink())throw new Error(`managed artifact path is not a directory: ${a}`)}i.set(a,l)}let o=A(e,Do),s=Gn(o);return s&&oC(o,A(n,"sqlite-generations")),{root:n,stableFiles:r,managedDirectories:i,generationStoreExisted:s}}function LB(e,t,n){for(let r of Rm){let i=A(t,r);if(n.managedDirectories.get(r)){let s=A(n.root,"managed",r);Vn(Kx(s),{recursive:!0}),vr(i,s)}let o=A(e,r);Gn(o)&&vr(o,i)}}function MB(e,t){for(let i of Rm){let o=A(e,i),s=A(t.root,"managed",i);t.managedDirectories.get(i)?Gn(s)&&(qn(o,{recursive:!0,force:!0}),vr(s,o)):qn(o,{recursive:!0,force:!0})}for(let[i,o]of t.stableFiles){let s=A(e,i);if(!o){qn(s,{force:!0});continue}let a=`${s}.shared-restore-${CB()}`;Go(A(t.root,"stable",i),a),qn(s,{force:!0}),vr(a,s)}let n=A(e,Do);qn(n,{recursive:!0,force:!0});let r=A(t.root,"sqlite-generations");t.generationStoreExisted&&Gn(r)&&vr(r,n)}function oC(e,t){Vn(t,{recursive:!0});for(let n of IB(e,{withFileTypes:!0})){let r=A(e,n.name),i=A(t,n.name);if(n.isSymbolicLink())throw new Error(`managed cache backup cannot contain a symlink: ${r}`);n.isDirectory()?oC(r,i):n.isFile()&&Go(r,i)}}function AB(e,t){if(e.generationId!==t.generationId||e.repositoryId!==t.repositoryId||e.treeOid!==t.treeOid||e.producerIdentity!==t.producerIdentity||JSON.stringify(e.fingerprint)!==JSON.stringify(t.fingerprint))throw new Error("shared generation manifest does not match the requested snapshot")}function Si(e,t,n,r=!0,i=!0){try{let o=xc(e);if(!o||JSON.stringify(o.fingerprint)!==JSON.stringify(n)||JSON.stringify([...o.indexedLanguages??[]].sort())!==JSON.stringify([...n.languages].sort()))return qo("source validation rejected metadata"),!1;let s=hc(e),a=Mo(A(e,"index.db"),A(e,"meta.json"));if(r?a.state!=="current":a.state==="invalid"||a.state==="drifted")return qo(`source validation rejected SQLite generation state ${a.state}`),!1;let c=new kB(A(e,"index.db"),{readonly:!0,fileMustExist:!0});try{if(i){if(c.pragma("quick_check(1)",{simple:!0})!=="ok")return!1}else c.pragma("schema_version",{simple:!0})}finally{c.close()}let l=Em(t),d=(i?s.files.filter(m=>m.endsWith(".scip")):["index.scip"]).every(m=>{let f=Jx(Ht($t(e,m))).metadata?.projectRoot;return f!==l&&qo(`source validation rejected SCIP root for ${m}: ${String(f)}`),f===l});return d||qo("source validation rejected SCIP project roots"),d}catch(o){return qo(`source validation failed: ${o instanceof Error?o.message:String(o)}`),!1}}function qo(e){process.env.SCIP_QUERY_DEBUG&&console.error(`shared-cache: ${e}`)}function Em(e){try{return Ux(wB(e)).href}catch{return Ux(Et(e)).href}}function NB(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===2&&Array.isArray(t.languages)&&typeof t.pnpmWorkspaces=="boolean"&&(t.typescriptProjectMode==="single"||t.typescriptProjectMode==="workspace")&&Array.isArray(t.typescriptProjects)&&Array.isArray(t.files)&&t.files.every(n=>n!==null&&typeof n=="object"&&typeof n.path=="string"&&typeof n.size=="number"&&typeof n.hash=="string")}function Vo(e){return Wx("sha256").update(e).digest("hex")}function sC(){return process.env.SCIP_QUERY_PROJECT_ROOT??process.cwd()}var Dm;function qae(e){Dm=e}function aC(e=sC(),t=void 0){if(t===void 0&&Dm?.projectRoot===e)return Dm;let n=zS(e),r=IS(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(km(r.dbPath))return{projectRoot:e,config:n,paths:r,dbPath:r.dbPath,dbPathSource:"configured",gitContext:t};let o=jB(e,"index.db");return{projectRoot:e,config:n,paths:r,dbPath:o,dbPathSource:"root-fallback",rootFallbackWarning:UB(o,r.dbPath),gitContext:t}}function Gae(e){return aC(e).dbPath}function Vae(e,t,n,r={}){return km(n.dbPath)&&nC(e,n.cacheDir,void 0,r.gitContext)?{kind:"local-fresh"}:r.gitContext?.clean===!1&&r.watcherGeneration!==void 0&&Kb(n.dbPath)===r.watcherGeneration?vm(e,t,n,r.gitContext):mx(e,t,n).state==="fresh"?vm(e,t,n,r.gitContext):tC(e,t,n,r.gitContext)}function Wae(e){return!e.startsWith("__")&&!BB.has(e)}var BB=new Set(["bench","config-validate","hook-context","hook-stop","init","setup","setup-agent","setup-ci","setup-hooks","uninstall","work-audit"]);function $B(){try{return HB(sC(),{warnOnRootFallback:!0})}catch(e){console.error(`error: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}function HB(e,t={}){let{config:n,paths:r,dbPath:i,dbPathSource:o,rootFallbackWarning:s,gitContext:a}=aC(e);if(!km(i))throw new Error("No index.db found. Run: scip-query reindex");t.warnOnRootFallback&&o==="root-fallback"&&s&&console.error(s);let c={dbPath:i,indexPath:process.env.SCIP_QUERY_INDEX_SCIP??r.indexPath,projectRoot:e,sharedEvidenceDbPath:Zx(e,n,a),entryRoots:n.entryRoots,semantic:n.semantic,suppressions:n.suppressions,declaredCouplings:n.declaredCouplings,locality:n.locality,architecture:n.architecture,coverageContracts:n.coverageContracts,docs:n.docs},l=DS(e);return new ec(c,l)}function UB(e,t){let n="unknown time";try{n=OB(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 mn(e){let t=$B();try{return e(t)}finally{t.close()}}function zae(e,t){return t.concat([e])}function cC(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 Kae(e){switch(e.state){case"idle":return"Watching (idle)";case"waiting":{let t=Math.round((e.reindexAt-Date.now())/1e3);return`${e.changedFiles} file(s) changed, reindexing in ${t}s...`}case"indexing":return`Reindexing... (${Math.round((Date.now()-e.startedAt)/1e3)}s)`;case"cooldown":return`Cooldown (${Math.round((e.until-Date.now())/1e3)}s)${e.dirty?" \u2014 changes pending":""}`;case"draining":return`Stopping safely \u2014 ${e.reason}`;default:return qB(e)}}function qB(e){throw new Error(`Unhandled watcher status: ${JSON.stringify(e)}`)}function lC(e){return e+1}function GB(e,t){return`${lC(e)}-${lC(t)}`}function Yae(e,t,n){return`${e}:${GB(t,n)}`}function Xae(e,t=180){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-3)}...`:n}var Ut={empty(e){console.log(e)},list(e,t){for(let n of e)console.log(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(o),r=o),console.log(t(i))}},sectionedReport(e){let t=!0;for(let n of e)if(!(n.skipIfEmpty&&n.rows.length===0)){t||console.log(""),t=!1,n.title!==void 0&&console.log(`\u2550\u2550\u2550 ${n.title} \u2550\u2550\u2550`),n.explanation!==void 0&&console.log(n.explanation);for(let r of n.rows)console.log(r)}},table(e,t,n){console.log(` ${e.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(i)}};import{availableParallelism as zQ}from"os";import{fileURLToPath as Sp}from"url";import{existsSync as Cc,readFileSync as VB,readdirSync as dC}from"fs";import{join as Wo}from"path";var WB={files:new Set,pathPrefixes:[]},Pm=/^(?:dist|build|lib|out|output|esm|cjs|umd)\//,zB=/\.(?:d\.ts|d\.mts|d\.cts|ts|tsx|mts|cts|js|jsx|mjs|cjs)$/,mC=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],KB=new Set([".git",".next",".turbo","build","coverage","dist","node_modules","out"]),JB=4,YB=Z("package-surface",{clearGroups:["whole-project"]});function XB(e){return YB.get(e,()=>QB(e.config.projectRoot))}function wr(e,t){let n=XB(e);return n.files.has(t)?!0:n.pathPrefixes.some(r=>t.startsWith(r))}function QB(e){let t=new Set,n=[];for(let{manifest:r,packageRoot:i}of ZB(e))for(let o of e$(r))t$(e,i,o,t,n);return t.size===0&&n.length===0?WB:{files:t,pathPrefixes:n}}function ZB(e){let t=[],n=pC(e,"");return n&&t.push({manifest:n,packageRoot:""}),fC(e,"",t,0),t}function fC(e,t,n,r){if(r>=JB)return;let i=Wo(e,t);if(Cc(i))for(let o of dC(i,{withFileTypes:!0})){if(!o.isDirectory()||KB.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name,a=pC(e,s);a&&n.push({manifest:a,packageRoot:s}),fC(e,s,n,r+1)}}function pC(e,t){try{let n=VB(Wo(e,t,"package.json"),"utf-8"),r=JSON.parse(n);return r&&typeof r=="object"?r:null}catch{return null}}function e$(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 gC(e.exports,t),t}function gC(e,t){if(typeof e=="string"){t.push(e);return}if(!(!e||typeof e!="object"))for(let n of Object.values(e))gC(n,t)}function t$(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 uC(c))l!==""&&i.push(fn(t,l));return}let a=o.replace(zB,"");for(let c of uC(a)){c===a&&c===o&&r.add(fn(t,o));for(let l of mC)n$(e,r,t,c+l)}r.add(fn(t,o))}function uC(e){let t=[e];return Pm.test(e)&&(t.push(e.replace(Pm,"src/")),t.push(e.replace(Pm,""))),t}function n$(e,t,n,r){let i=fn(n,r);if(t.add(i),!r.startsWith("src/")||Cc(Wo(e,i)))return;let o=mC.find(u=>r.endsWith(u));if(!o)return;let s=r.slice(0,-o.length);r$(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 hC(e,n,c,`${l}${o}`))t.add(u)}function r$(e,t,n,r,i){let o=fn(n,`${r}/index${i}`);Cc(Wo(e,o))&&t.add(o)}function hC(e,t,n,r){let i=Wo(e,t,n);if(!Cc(i))return[];let o=[];for(let s of dC(i,{withFileTypes:!0})){let a=`${n}/${s.name}`;s.isDirectory()?o.push(...hC(e,t,a,r)):s.isFile()&&s.name===r&&o.push(fn(t,a))}return o}function fn(e,t){return e?`${e}/${t}`:t}import{existsSync as Rc,readFileSync as i$,readdirSync as o$}from"fs";import{dirname as s$,join as vc}from"path";var a$={rootFiles:new Set,sourcePrefixes:[]},c$=new Set([".git",".scipquery","node_modules","target"]),l$=6,u$=Z("rust-library-surface",{clearGroups:["whole-project"]});function yC(e,t,n){if(!n.endsWith(".rs")||!f$(d$(e),n))return!1;let r=Q(e,n).find(i=>i.symbol===t);return r?p$(Ee(e,n)[r.startLine]??""):!1}function d$(e){return u$.get(e,()=>m$(e.config.projectRoot))}function m$(e){let t=new Set,n=new Set;for(let r of g$(e)){let i=vc(e,r,"Cargo.toml"),o=i$(i,"utf8"),s=h$(o),a=fn(r,"src/lib.rs"),c=s?fn(r,s):!y$(o)&&Rc(vc(e,a))?a:null;if(!c)continue;t.add(c);let l=s$(c).replaceAll("\\","/");n.add(l==="."?"":`${l}/`)}return t.size===0?a$:{rootFiles:t,sourcePrefixes:[...n].sort()}}function f$(e,t){return t.endsWith(".rs")?e.rootFiles.has(t)?!0:b$(t)?!1:e.sourcePrefixes.some(n=>t.startsWith(n)):!1}function p$(e){return/^\s*pub\s+(?!\()/.test(e)}function g$(e){if(!Rc(e))return[];let t=[];return bC(e,"",t,0),t}function bC(e,t,n,r){let i=vc(e,t);if(Rc(i)&&(Rc(vc(i,"Cargo.toml"))&&n.push(t),!(r>=l$)))for(let o of o$(i,{withFileTypes:!0})){if(!o.isDirectory()||c$.has(o.name))continue;let s=t?`${t}/${o.name}`:o.name;bC(e,s,n,r+1)}}function h$(e){let t=!1;for(let n of e.split(`
|
|
396
|
+
`)){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 y$(e){let t=!1;for(let n of e.split(`
|
|
397
|
+
`)){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 b$(e){return/(?:^|\/)src\/main\.rs$/.test(e)||/(?:^|\/)src\/bin\//.test(e)||/(?:^|\/)(?:examples|tests|benches)\//.test(e)}function W(e){let t=se(e);return A$(t)?"test":N$(t)?"worker":O$(t)?"entry":j$(t)?"barrel":"source"}function xi(e){return W(e)==="barrel"}function xC(e){return S$.get(e,()=>{let n=M(e,{includeIgnored:!1}).filter(s=>{let a=W(s);return a==="entry"||a==="worker"});if(n.length===0)return new Set;let r=ae(e),i=new Set,o=new Set;for(;n.length>0;){let s=n.shift();if(!i.has(s)){i.add(s),W(s)==="barrel"&&o.add(s);for(let a of r.get(s)??[])i.has(a)||n.push(a)}}return o})}var S$=Z("live-barrels",{clearGroups:["whole-project"]});function Fm(e,t){return xC(e).has(se(t))}function CC(e){let t=xC(e);return M(e,{includeIgnored:!1}).filter(n=>xi(n)&&!t.has(n)&&!x$(e,n))}function x$(e,t){let n=se(t),r=mt(e).forFile(n,{facts:!0}).facts?.callables;return r&&r.length>0?!0:(e.get(`SELECT COUNT(*) AS n
|
|
398
|
+
FROM defn_enclosing_ranges der
|
|
399
|
+
JOIN documents d ON d.id = der.document_id
|
|
400
|
+
WHERE d.relative_path = ?
|
|
401
|
+
AND der.end_line - der.start_line >= 2`,n)?.n??0)>0}function Le(e,t){let n=se(t),r=W(t);return r==="entry"||r==="worker"||_$(n)||Fm(e,n)}function ge(e,t,n){let r=se(n);if(wr(e,r)||R$(e,t,r)||yC(e,t,r)||T$(t,r))return!0;let i=e.config.entryRoots;return i?!!(i.files?.some(o=>se(o)===r)||i.pathPrefixes?.some(o=>r.startsWith(se(o)))||i.qualifiedVars?.some(o=>B$(t,o))||i.symbolPatterns?.some(o=>{try{return new RegExp(o).test(t)}catch{return!1}})):!1}var C$=Z("package-surface-reachability",{clearGroups:["whole-project"]});function R$(e,t,n){let r=v$(e).get(n);return r===void 0?!1:r===null||r.has(F(t))}function v$(e){return C$.get(e,()=>{let t=new Map,n=[];for(let r of M(e,{includeIgnored:!1}))wr(e,r)&&(t.set(r,null),n.push(r));for(;n.length>0;){let r=n.shift(),i=t.get(r);if(i!==void 0)for(let o of rn(e,r)){if(!o.sourcePath||e.isIgnored(o.sourcePath))continue;let s=I$(i,o);s!==void 0&&w$(t,o.sourcePath,s)&&n.push(o.sourcePath)}}return t})}function I$(e,t){if(e===null)return t.kind==="named"?new Set(t.names):null;if(t.kind==="star")return new Set(e);if(t.kind==="star-as")return;let n=t.names.filter(r=>e.has(r));return n.length>0?new Set(n):void 0}function w$(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 RC=new Set(["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"]),E$=new Set(["default","generateMetadata","generateStaticParams"]),D$=new Set(["default","getStaticProps","getServerSideProps","getStaticPaths","config"]),k$=new Set(["default","loader","action","clientLoader","clientAction","headers","links","meta","shouldRevalidate","ErrorBoundary","HydrateFallback"]),P$=new Set(["load","actions","entries",...RC]),F$=new Set(["default"]);function T$(e,t){let n=F(e);return n===""?!1:vC(t)?RC.has(n):IC(t)?E$.has(n):wC(t)?D$.has(n):EC(t)?k$.has(n):DC(t)?P$.has(n):M$(t)?F$.has(n):!1}function _$(e){return vC(e)||IC(e)||wC(e)||L$(e)||EC(e)||DC(e)}function vC(e){return/(?:^|\/)app(?:\/[^/]+)*\/route\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function IC(e){return/(?:^|\/)app(?:\/[^/]+)*\/(?:page|layout|template|loading|error|not-found|global-error|head|default)\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function wC(e){return/(?:^|\/)pages\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function L$(e){let t="(?:middleware|proxy|instrumentation)\\.(?:ts|js|mts|mjs)";return new RegExp(`^(?:src/)?${t}$`).test(e)||new RegExp(`(?:^|/)src/${t}$`).test(e)||new RegExp(`(?:^|/)(?:apps|services|packages)/[^/]+/(?:src/)?${t}$`).test(e)}function EC(e){return/(?:^|\/)app\/routes\/.+\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(e)}function DC(e){return/(?:^|\/)src\/routes\/(?:.*\/)?\+(?:page|page\.server|layout|layout\.server|server)\.(?:ts|js)$/.test(e)}function M$(e){return/(?:^|\/)src\/(?:pages|views|routes)\/.+\.(?:ts|tsx|js|jsx|vue)$/.test(e)}function A$(e){return!!(/\.(?:test|spec)\.[a-z0-9]+$/i.test(e)||/(?:^|\/)(?:_)?test_[^/]+$/i.test(e)||/(?:^|\/)spec_[^/]+$/i.test(e)||/(?:^|\/)[^/]+_test\.[a-z0-9]+$/i.test(e)||/(?:^|\/)[^/]+_tests\.rs$/i.test(e)||/(?:^|\/)tests\.rs$/i.test(e)||/(?:^|\/)[^/]+_spec\.[a-z0-9]+$/i.test(e)||/(?:^|\/)__tests__\//i.test(e)||/(?:^|\/)test\//i.test(e)||/(?:^|\/)tests\//i.test(e)||/(?:^|\/)__fixtures__\//i.test(e)||/(?:^|\/)__mocks__\//i.test(e)||/(?:^|\/)test-support\//i.test(e)||/(?:^|\/)test-utils\//i.test(e)||/(?:^|\/)testing\//i.test(e))}function N$(e){return/(?:^|\/)[^/]*worker\.(?:ts|tsx|js|mjs|cjs|rs|py|go)$/.test(e)}function O$(e){let t=e.split("/"),n=t[t.length-1]??e;return n==="cli.ts"||n==="cli.js"||n==="postinstall.ts"||n==="postinstall.js"||n==="main.ts"||n==="main.js"||n==="main.rs"||n==="main.go"||n==="main.py"||n==="build.rs"||n==="lib.rs"||/\bsrc\/bin\/[^/]+\.rs$/.test(e)||/(?:^|\/)examples\/[^/]+\.rs$/.test(e)||/(?:^|\/)tests\/[^/]+\.rs$/.test(e)||/(?:^|\/)benches\/[^/]+\.rs$/.test(e)?!0:n==="index.ts"||n==="index.js"?/(?:^|\/)(?:apps|services)\/[^/]+\/src\/index\.(?:ts|js)$/.test(e)?!0:t.length<=2:!1}function j$(e){return e==="index.ts"||e==="index.js"||e.endsWith("/index.ts")||e.endsWith("/index.js")||e.endsWith("/mod.rs")||e.endsWith("/__init__.py")}function B$(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(SC(r)+"/")&&e.includes(SC(i)+".")}function SC(e){return/^[A-Za-z0-9_$+-]+$/.test(e)?e:"`"+e.replace(/`/g,"``")+"`"}import{SymbolInformation_Kind as K}from"@c4312/scip";var Ic=new Map(Object.entries(K).filter(([e,t])=>Number.isInteger(Number(e))&&typeof t=="string").map(([e,t])=>[Number(e),t])),kC=new Map([...Ic.entries()].map(([e,t])=>[t.toLowerCase(),e]));function zo(e){return Ic.get(e)??"Unknown"}function qt(){return[K.Function,K.Method,K.Macro,K.Constructor,K.Getter,K.Setter,K.StaticMethod,K.SingletonMethod,K.AbstractMethod,K.ProtocolMethod,K.TraitMethod]}function PC(){return[K.Class,K.Interface,K.Struct,K.Trait,K.Type,K.TypeAlias,K.Enum,K.Union,K.Protocol]}function Cce(){return[K.Constant,K.Variable,K.Value,K.Field,K.Property,K.StaticDataMember,K.StaticField,K.StaticProperty,K.StaticVariable,K.EnumMember]}function ht(e,t,n={}){let r=wc(e,[t],{additive:n.additive,semantic:n.semantic,semanticEvidence:n.semanticEvidence}),i=n.callableOnly?(r.get(t.symbolId)??[]).filter(o=>fe(o.symbol)||o.source==="ast-callsite"):r.get(t.symbolId)??[];return typeof n.limit=="number"?i.slice(0,n.limit):i}function Dt(e,t,n){return _m(e,[t],n).get(t.symbolId)??[]}function _m(e,t,n){let r=U$(e)?G$(e,t,{semantic:n.semantic!==!1,semanticEvidence:n.semanticEvidence}):q$(e,n.semanticEvidence);return typeof n.limit!="number"?new Map(t.map(i=>[i.symbolId,r.get(i.symbolId)??[]])):new Map(t.map(i=>[i.symbolId,(r.get(i.symbolId)??[]).slice(0,n.limit)]))}var $$=Z("caller-rows",{clearGroups:["whole-project"]}),H$=2e4;function U$(e){return(e.get("SELECT COUNT(*) AS count FROM global_symbols")?.count??0)>H$}function q$(e,t){return $$.get(e,()=>{let n=De(e),r=wc(e,n,{semanticEvidence:t}),i=new Map;for(let a of n)i.set(a.symbol,a.symbolId);let o=new Map,s=new Map;for(let a of n){let c=r.get(a.symbolId);if(!(!c||c.length===0))for(let l of c){let u=i.get(l.symbol);if(u===void 0||u===a.symbolId)continue;let d=o.get(u);d||(d=[],o.set(u,d),s.set(u,new Set));let m=`${a.symbol}|${a.relativePath}`;s.get(u).has(m)||(s.get(u).add(m),d.push({symbol:a.symbol,file:a.relativePath,source:"caller-map-inversion"}))}}return o})}function G$(e,t,n){let r=n.semantic&&n.semanticEvidence?t.flatMap(a=>{let c=V$(e,a);return c?[c]:[]}):[],i=new Map(r.map(a=>[a.symbolId,a])),o=n.semanticEvidence?.referenceMap(e,r)??new Map,s=new Map;for(let a of t){let c=[],l=new Set,u=m=>{if(m.symbol===a.symbol)return;let f=`${m.symbol}|${m.file}`;l.has(f)||(l.add(f),c.push(m))};for(let m of oo(e,a))m.file!==a.relativePath&&u({symbol:m.enclosingSymbol??m.file,file:m.file,source:"resolved-reference"});let d=i.get(a.symbolId);if(d)for(let m of o.get(d.symbolId)??[]){if(m.file===a.relativePath||e.isIgnored(m.file))continue;let f=At(Q(e,m.file),m.line);u({symbol:f?.symbol??m.file,file:m.file,source:"semantic-reference"})}s.set(a.symbolId,c)}return s}function V$(e,t){let n=qt().join(", "),r=PC().join(", ");return e.get(`SELECT
|
|
402
|
+
d.id AS documentId,
|
|
403
|
+
gs.id AS symbolId,
|
|
404
|
+
gs.symbol,
|
|
405
|
+
d.relative_path AS relativePath,
|
|
406
|
+
COALESCE(der.start_line, c.start_line) AS startLine,
|
|
407
|
+
COALESCE(der.end_line, c.end_line) AS endLine,
|
|
408
|
+
COALESCE(gs.display_name, '') AS leaf,
|
|
409
|
+
NULL AS parentTypeName,
|
|
410
|
+
CASE WHEN gs.kind IN (${n}) OR gs.symbol LIKE '%().' THEN 1 ELSE 0 END AS isFunctionLike,
|
|
411
|
+
CASE WHEN gs.kind IN (${r}) THEN 1 ELSE 0 END AS isTypeLike,
|
|
412
|
+
gs.kind AS kind,
|
|
413
|
+
gs.documentation AS documentation,
|
|
414
|
+
gs.enclosing_symbol AS enclosingSymbol
|
|
415
|
+
FROM global_symbols gs
|
|
416
|
+
LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
417
|
+
LEFT JOIN chunks c ON c.document_id = der.document_id
|
|
418
|
+
JOIN documents d ON d.id = COALESCE(der.document_id, c.document_id)
|
|
419
|
+
WHERE gs.id = ?
|
|
420
|
+
LIMIT 1`,t.symbolId)??null}function wc(e,t,n={}){if(t.length===0)return new Map;let r=n.additive??!1,i=[],o=[];for(let u of t)N(u.relativePath)&&wn(e,u.relativePath)!==null?i.push(u):o.push(u);let s=new Map,a=new Map,c=u=>{for(let[d,m]of u){let f=s.get(d);f||(f=[],s.set(d,f));let p=a.get(d);p||(p=new Set,a.set(d,p));for(let g of m){let y=`${g.symbol}|${g.chunkId}`;p.has(y)||(p.add(y),f.push(g))}}};i.length>0&&c(W$(e,i)),n.semantic!==!1&&n.semanticEvidence&&c(Q$(n.semanticEvidence.calleeMap(e,t)));let l=r?t:o;return l.length>0&&c(Y$(e,l)),s}function W$(e,t){let n=new Map,r=z$(t,n),i=cn(e);for(let[o,s]of r){let a=wn(e,o);if(!a)continue;let c=Du(s);for(let l of a){let u=c.get(l.line);if(!u)continue;let d=K$(e,o,i,l);d&&d.symbol!==u.symbol&&n.get(u.symbolId).push({symbol:d.symbol,file:d.file,chunkId:l.line,source:"ast-callsite"})}}return n}function z$(e,t){let n=new Map;for(let r of e){let i=n.get(r.relativePath);i?i.push(r):n.set(r.relativePath,[r]),t.set(r.symbolId,[])}for(let r of n.values())r.sort((i,o)=>i.endLine-i.startLine-(o.endLine-o.startLine));return n}function K$(e,t,n,r){let i=ga(t,n.get(r.calleeLeaf)??[]);if(i.length===0)return null;let o=J$(e,t,i,r.calleeQualifier);return o||ha(e,t,i,r.memberAccess)}function J$(e,t,n,r){if(!r||N(t)!=="clojure")return null;let o=te(e,t).filter(s=>s.kind==="namespace"&&s.localName===r&&s.sourcePath).map(s=>s.sourcePath);for(let s of o){let a=n.find(c=>Qe(s,c.file));if(a)return a}return n.find(s=>/`([^`]+)`\//.exec(s.symbol)?.[1]===r)??null}function Y$(e,t){if(t.length===0)return new Map;let r=Tm(t.map(f=>f.documentId)).flatMap(f=>e.all(`SELECT c.document_id, c.id AS chunk_id, c.start_line, c.end_line, m.symbol_id
|
|
421
|
+
FROM mentions m
|
|
422
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
423
|
+
WHERE m.role != 1
|
|
424
|
+
AND c.document_id IN (${f.map(()=>"?").join(",")})`,...f)),i=new Map;for(let f of r)i.has(f.document_id)||i.set(f.document_id,[]),i.get(f.document_id).push(f);let s=Tm(r.map(f=>f.symbol_id)).flatMap(f=>e.all(`SELECT gs.id AS symbol_id, gs.symbol,
|
|
425
|
+
COALESCE(der.document_id, def_chunk.document_id) AS document_id
|
|
426
|
+
FROM global_symbols gs
|
|
427
|
+
LEFT JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
428
|
+
LEFT JOIN (
|
|
429
|
+
SELECT m.symbol_id, MIN(c.document_id) AS document_id
|
|
430
|
+
FROM mentions m
|
|
431
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
432
|
+
WHERE m.role = 1
|
|
433
|
+
AND m.symbol_id IN (${f.map(()=>"?").join(",")})
|
|
434
|
+
GROUP BY m.symbol_id
|
|
435
|
+
) def_chunk ON def_chunk.symbol_id = gs.id
|
|
436
|
+
WHERE gs.id IN (${f.map(()=>"?").join(",")})`,...f,...f)),a=Tm([...t.map(f=>f.documentId),...s.flatMap(f=>f.document_id===null?[]:[f.document_id])]),c=new Map(a.flatMap(f=>e.all(`SELECT id, relative_path FROM documents
|
|
437
|
+
WHERE id IN (${f.map(()=>"?").join(",")})`,...f).map(p=>[p.id,p.relative_path]))),l=new Map;for(let f of s)l.has(f.symbol_id)||l.set(f.symbol_id,{symbol:f.symbol,file:f.document_id!==null?c.get(f.document_id)??"":""});let u=new Map,d=c,m=X$(t);for(let[f,p]of m){let y=[...i.get(f)??[]].sort((S,x)=>S.start_line-x.start_line||S.end_line-x.end_line),h=[...p].sort((S,x)=>S.startLine-x.startLine||S.endLine-x.endLine),C=new Set,b=0;for(let S of h){for(;b<y.length&&y[b].start_line<=S.endLine;)C.add(y[b]),b+=1;for(let w of C)w.end_line<S.startLine&&C.delete(w);let x=new Set,v=[],R=null,D=()=>{if(R)return R;let w=d.get(S.documentId)??"",k=new Set;if(w){let L=Vh(e,w),ne=Math.max(0,S.startLine),ee=Math.min(L.length-1,S.endLine);for(let _=ne;_<=ee;_+=1)for(let ue of L[_])k.add(ue)}return R=k,k};for(let w of C){if(w.symbol_id===S.symbolId)continue;let k=l.get(w.symbol_id);if(!k)continue;if(!(w.start_line>=S.startLine&&w.end_line<=S.endLine)){if(!(w.start_line<=S.endLine&&w.end_line>=S.startLine))continue;let _=F(k.symbol);if(!_||!D().has(_))continue}let ne=`${k.symbol}|${w.chunk_id}`;x.has(ne)||(x.add(ne),v.push({...k,chunkId:w.chunk_id,source:"scip-chunk"}))}u.set(S.symbolId,v)}}return u}var FC=500;function Tm(e){let t=[...new Set(e)],n=[];for(let r=0;r<t.length;r+=FC)n.push(t.slice(r,r+FC));return n}function X$(e){let t=new Map;for(let n of e){let r=t.get(n.documentId);r?r.push(n):t.set(n.documentId,[n])}return t}function Q$(e){let t=new Map;for(let[n,r]of e){let i=[];for(let o of r)i.push({symbol:o.symbol,file:o.file,chunkId:-1,source:"semantic-callee"});t.set(n,i)}return t}function TC(e,t,n={}){let r=new Map;if(t&&t.length===0)return r;let i=M(e,{includeIgnored:!1}),o=cn(e),s=t??De(e),a=new Set(s.map(l=>l.symbolId)),c=o1(s);return Z$(e,r,i,o,a,c),e1(e,r,s,a),i1(e,r,i,o,a,c),n.semantic!==!1&&n.semanticEvidence&&a1(r,n.semanticEvidence.callerMap(e,s1(s))),r}function Z$(e,t,n,r,i,o){for(let s of n){if(!N(s))continue;let a=wn(e,s);if(a)for(let c of a){if(o&&!o.has(c.calleeLeaf))continue;let l=ga(s,r.get(c.calleeLeaf)??[]);if(!l||l.length===0)continue;let u=ha(e,s,l,c.memberAccess);u&&i.has(u.symbolId)&&u.file!==s&&Lm(t,u.symbolId,s)}}}function e1(e,t,n,r){let i=n1(n);for(let o of t1(e,r))e.isIgnored(o.relative_path)||r1(o,i.get(o.symbol_id))||Lm(t,o.symbol_id,o.relative_path)}function t1(e,t){return Qr(e,t?[...t]:void 0)}function n1(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 r1(e,t){return!!t&&t.docId===e.document_id&&e.chunk_start>=t.startLine&&e.chunk_end<=t.endLine}function i1(e,t,n,r,i,o){for(let s of n){if(N(s)!=="rust")continue;let a=ar(e,s,{includeRustAttributeNames:!0});if(a.length!==0)for(let{name:c}of a){if(o&&!o.has(c))continue;let l=r.get(c);if(l)for(let u of l)i.has(u.symbolId)&&u.file!==s&&Lm(t,u.symbolId,s)}}}function Lm(e,t,n){let r=e.get(t);r||(r=new Set,e.set(t,r)),r.add(n)}function o1(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"?F(n.symbol):"";r&&t.add(r)}return t.size>0?t:null}function s1(e){return e.filter(t=>"relativePath"in t&&"symbol"in t&&"leaf"in t)}function a1(e,t){for(let[n,r]of t){let i=e.get(n);i||(i=new Set,e.set(n,i));for(let o of r)i.add(o)}}function Mm(e,t,n={}){return TC(e,t,n)}function Ko(e,t,n={}){return ty(e,t,n)}function _C(e,t,n={}){let r=Mm(e,t,{semantic:n.semantic,semanticEvidence:n.semanticEvidence});return n.sourceFallback===!1?r:pn(r,Ko(e,t))}function pn(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 LC(e,t,n){let r=t.identifierResolution==="strict"?Zr:Zh,i=t.candidateNames?ro(t.candidateNames):null,o=0,s=0,a=0,c=0,l="";for(let u of t.paths)if(o+=1,l=u,!(!N(u)&&!(t.includeVueSfc&&Yt(u)))&&!e.isIgnored(u)&&!t.skipPath?.(u))try{if(i&&!ya(P(e,u),i))continue;s+=1;let m=(p,g,y,h)=>{if(t.candidateNames&&!t.candidateNames.has(p))return;a+=1;let C=t.resolveTargets?t.resolveTargets({sourceFile:u,name:p,kind:g,defaultTargets:h}):h();for(let b of C)c+=1,n({sourceFile:u,name:p,target:b,occurrences:y,kind:g})},f=an(e,u);for(let[p,g]of f)m(p,"identifier",g.length,()=>r(e,u,p));for(let p of ar(e,u,{includeCrossLanguageDispatchNames:t.includeCrossLanguageDispatchNames,includeRustAttributeNames:t.includeRustAttributeNames})){let g=p.kind==="cross-language-dispatch"?()=>Zr(e,u,p.name):()=>r(e,u,p.name);m(p.name,p.kind,p.occurrences,g)}}finally{t.afterPath?.(u),o%10===0&&E("source-reference-scan.progress",()=>{},()=>({scannedPaths:o,currentPath:l,candidateMatchedPaths:s,visitedNames:a,visitedHits:c}))}}function O(e){return e.endLine-e.startLine+1}function MC(e,t={}){let{scope:n,files:r,minLoc:i=1,maxLoc:o=Number.POSITIVE_INFINITY,excludeSymbol:s,excludeEntrySurfaces:a=!1,excludeTypesFiles:c=!1,excludeRootedSymbols:l=!1,requireFunctionLikeSymbol:u=!1,requireCallableSymbol:d=!1,excludeRustTraitImplMembers:m=!1,includeSuppressed:f=!1,sortByLocDesc:p=!1}=t,g=[],y=c1(e,{scope:n,files:r,requireFunctionLikeSymbol:u,requireCallableSymbol:d}),h=new Map,C=new Map,b=x=>{let v=h.get(x);if(v!==void 0)return v;let R=Le(e,x);return h.set(x,R),R},S=x=>{let v=C.get(x);if(v!==void 0)return v;let R=W(x);return C.set(x,R),R};for(let x of y){let v=x.relativePath;if(e.isIgnored(v)||a&&b(v)||!l1(x,{requireFunctionLikeSymbol:u,requireCallableSymbol:d})||s!==void 0&&x.symbol===s)continue;let R=O(x);R<i||R>o||c&&u1(v)||l&&ge(e,x.symbol,v)||m&&Fe(x.symbol)||S(v)!=="test"&&(Or(x.symbol)||!f&&Ts(e,v,x.startLine)||g.push(x))}return p?g.sort((x,v)=>O(v)-O(x)):g}function c1(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=>Q(e,r)):t.requireCallableSymbol?Zi(e,{scope:t.scope,symbolMatches:fe,sqlPrefilter:"callable"}):t.requireFunctionLikeSymbol?Zi(e,{scope:t.scope,symbolMatches:oe,sqlPrefilter:"function-like"}):Bh(e,t.scope)}function l1(e,t){return t.requireCallableSymbol?fe(e.symbol):t.requireFunctionLikeSymbol?oe(e.symbol):e.isFunctionLike}function u1(e){return(e.split("/").pop()??"").includes("types")}var T=class{constructor(t){this.db=t}db;scopedDefinitions(t){return Eu(this.db,t)}definitionsForFile(t){return Q(this.db,t)}productionCallableDefinitions(t={}){return MC(this.db,t)}calleeMap(t,n={}){return wc(this.db,t,{...n,semanticEvidence:U})}crossFileCallerMap(t,n={}){return Mm(this.db,t,{...n,semanticEvidence:U})}sourceFallbackCallerFiles(t,n={}){return Ko(this.db,t,n)}callerFileMap(t,n={}){return _C(this.db,t,{...n,semanticEvidence:U})}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 M(this.db,{includeIgnored:!1}))if(N(i)==="rust")for(let{name:o}of ar(this.db,i,{includeRustAttributeNames:!0}))for(let s of n.get(o)??[])r.add(s);return r}symbolsWithNonSelfCallees(t,n={}){if(t.length===0)return new Set;let r=new Map(t.map(o=>[o.symbolId,o.symbol])),i=this.calleeMap(t,n);return new Set([...i.entries()].filter(([o,s])=>{let a=r.get(o);return s.some(c=>c.symbol!==a)}).map(([o])=>o))}fileDependencyGraph(t){return ae(this.db,t)}fileKind(t){return W(t)}hasSuppressionComment(t){return Ts(this.db,t.relativePath,t.startLine)}sourceFiles(){return ze(this.db)}scanSourceReferences(t,n){LC(this.db,t,n)}callableSignature(t){let n=mt(this.db).forFile(t.relativePath,{facts:!0}).facts?.callables.find(r=>r.startLine===t.startLine&&r.endLine===t.endLine);return n?{paramCount:n.paramCount}:null}};import{statSync as d1}from"fs";function Er(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,...m1(e.generation.databasePath)}}function m1(e){try{let t=d1(e);return{indexSizeBytes:t.size,lastBuilt:t.mtime}}catch{return{indexSizeBytes:0,lastBuilt:null}}}function f1(e){return/[*?]/.test(e)?e.replace(/\*\*/g,"%").replace(/\*/g,"%").replace(/\?/g,"_"):`%${e}%`}function p1(e,t){let n=f1(t);return M(e,{like:n,includeIgnored:!1}).filter(r=>g1(t,r)).map(r=>({relativePath:r}))}function g1(e,t){if(!/[*?]/.test(e))return t.includes(e);let n=e.includes("/")?e:`**/${e}`;return Ec(n.split("/"),t.split("/"))}function Ec(e,t){if(e.length===0)return t.length===0;let[n,...r]=e;return n==="**"?Ec(r,t)||t.length>0&&Ec(e,t.slice(1)):t.length===0||!h1(n??"",t[0]??"")?!1:Ec(r,t.slice(1))}function h1(e,t){let n="^";for(let r of e)r==="*"?n+="[^/]*":r==="?"?n+="[^/]":n+=y1(r);return n+="$",new RegExp(n).test(t)}function y1(e){return/[\\^$.*+?()[\]{}|]/.test(e)?`\\${e}`:e}import{basename as b1}from"path";function S1(e,t){let n=$(e,t);if(!n)return[];let r=F(n.symbol),o=new T(e).definitionsForFile(n.relativePath).filter(l=>fe(l.symbol)),s=o.filter(l=>l.parentTypeName===r||l.symbol.includes(r)),c=(s.length>0?s:x1(b1(n.relativePath))===r?o.filter(l=>l.symbol.includes("<invalid-global-code>")):[]).map(l=>({startLine:l.startLine,endLine:l.endLine,name:F(l.symbol)}));return N(n.relativePath)!=="clojure"?c:R1(c,C1(e,n))}function x1(e){return e.replace(/\.[^.]+$/,"")}function C1(e,t){let n=F(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 R1(e,t){let n=new Map;for(let r of[...e,...t])n.set(`${r.name}:${r.startLine}:${r.endLine}`,r);return[...n.values()].sort((r,i)=>r.startLine-i.startLine||r.endLine-i.endLine)}function Am(e,t,n={}){let r=$(e,t);if(!r)return{definitions:[],referencedBy:[]};let i=e.get("SELECT display_name, documentation FROM global_symbols WHERE id = ?",r.symbolId),o=sn(i?.documentation??null),s=e.isIgnored(r.relativePath)?[]:[{relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,signature:I1(o,i?.display_name??null,r.symbol),source:v1(e,r.relativePath,r.startLine,r.endLine)}],a=Nt(e,r,{semantic:n.semantic,semanticEvidence:U}).map(c=>({relativePath:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol,enclosingShort:c.enclosingSymbol?I(c.enclosingSymbol):"(top-level)"}));return{definitions:s,referencedBy:a}}function v1(e,t,n,r){let i=P(e,t);if(!i)return null;let s=i.split(`
|
|
438
|
+
`).slice(n,r+1).join(`
|
|
439
|
+
`).trimEnd();return s.length>0?s:null}function I1(e,t,n){let r=on(e);if(r&&!w1(r))return r;let i=(t??"").trim();return i?oe(n)&&!i.endsWith("()")?`${i}()`:i:I(n)}function w1(e){return e.startsWith("undefined")||e.includes("|")||e.includes("```")}function Nm(e,t){let n=Ge(e,t);return n?e.all(`SELECT DISTINCT d2.relative_path
|
|
440
|
+
FROM mentions m
|
|
441
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
442
|
+
JOIN documents d1 ON c.document_id = d1.id
|
|
443
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
444
|
+
JOIN (
|
|
445
|
+
SELECT m2.symbol_id, c2.document_id
|
|
446
|
+
FROM mentions m2
|
|
447
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
448
|
+
WHERE m2.role = 1
|
|
449
|
+
GROUP BY m2.symbol_id
|
|
450
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
451
|
+
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
452
|
+
WHERE d1.relative_path = ?
|
|
453
|
+
AND d2.relative_path <> d1.relative_path
|
|
454
|
+
AND ${e.localSymbolPredicate}
|
|
455
|
+
ORDER BY d2.relative_path`,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function Om(e,t){let n=Ge(e,t);return n?e.all(`SELECT DISTINCT d1.relative_path
|
|
456
|
+
FROM mentions m
|
|
457
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
458
|
+
JOIN documents d1 ON c.document_id = d1.id
|
|
459
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
460
|
+
JOIN (
|
|
461
|
+
SELECT m2.symbol_id, c2.document_id
|
|
462
|
+
FROM mentions m2
|
|
463
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
464
|
+
WHERE m2.role = 1
|
|
465
|
+
GROUP BY m2.symbol_id
|
|
466
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
467
|
+
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
468
|
+
WHERE d2.relative_path = ?
|
|
469
|
+
AND d1.relative_path != ?
|
|
470
|
+
ORDER BY d1.relative_path`,n,n).filter(i=>!e.isIgnored(i.relative_path)).map(i=>({relativePath:i.relative_path})):[]}function jm(e,t){let n=fi(e,t);if(n.length===0)return{files:[],symbols:[],dependsOn:[],dependedOnBy:[]};let r=n.map(()=>"?").join(", "),o=e.all(`SELECT relative_path FROM documents
|
|
471
|
+
WHERE relative_path IN (${r})
|
|
472
|
+
ORDER BY relative_path`,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d)),s=aa(e,o,{onlyDocumented:!0,sort:!0}).map(({relativePath:d,...m})=>m),c=e.all(`SELECT DISTINCT d2.relative_path
|
|
473
|
+
FROM mentions m
|
|
474
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
475
|
+
JOIN documents d1 ON c.document_id = d1.id
|
|
476
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
477
|
+
JOIN (
|
|
478
|
+
SELECT m2.symbol_id, c2.document_id
|
|
479
|
+
FROM mentions m2
|
|
480
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
481
|
+
WHERE m2.role = 1
|
|
482
|
+
GROUP BY m2.symbol_id
|
|
483
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
484
|
+
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
485
|
+
WHERE d1.relative_path IN (${r})
|
|
486
|
+
AND d2.relative_path NOT IN (${r})
|
|
487
|
+
AND ${e.localSymbolPredicate}
|
|
488
|
+
ORDER BY d2.relative_path`,...n,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d)),u=e.all(`SELECT DISTINCT d1.relative_path
|
|
489
|
+
FROM mentions m
|
|
490
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
491
|
+
JOIN documents d1 ON c.document_id = d1.id
|
|
492
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
493
|
+
JOIN (
|
|
494
|
+
SELECT m2.symbol_id, c2.document_id
|
|
495
|
+
FROM mentions m2
|
|
496
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
497
|
+
WHERE m2.role = 1
|
|
498
|
+
GROUP BY m2.symbol_id
|
|
499
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
500
|
+
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
501
|
+
WHERE d2.relative_path IN (${r})
|
|
502
|
+
AND d1.relative_path NOT IN (${r})
|
|
503
|
+
ORDER BY d1.relative_path`,...n,...n).map(d=>d.relative_path).filter(d=>!e.isIgnored(d));return{files:o,symbols:s,dependsOn:c,dependedOnBy:u}}function Bm(e,t){let n=fi(e,t);return n.length===0?[]:k1([...E1(e,n),...D1(e,n)]).filter(r=>!e.isIgnored(r.relative_path)).map(P1)}function E1(e,t){let n=t.map(()=>"?").join(", ");return e.all(`SELECT DISTINCT d1.relative_path, gs.symbol
|
|
504
|
+
FROM mentions m
|
|
505
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
506
|
+
JOIN documents d1 ON c.document_id = d1.id
|
|
507
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
508
|
+
WHERE d1.relative_path NOT IN (${n})
|
|
509
|
+
AND (
|
|
510
|
+
EXISTS (
|
|
511
|
+
SELECT 1
|
|
512
|
+
FROM defn_enclosing_ranges der
|
|
513
|
+
JOIN documents d2 ON der.document_id = d2.id
|
|
514
|
+
WHERE der.symbol_id = gs.id
|
|
515
|
+
AND d2.relative_path IN (${n})
|
|
516
|
+
)
|
|
517
|
+
OR EXISTS (
|
|
518
|
+
SELECT 1
|
|
519
|
+
FROM mentions def_m
|
|
520
|
+
JOIN chunks def_c ON def_m.chunk_id = def_c.id
|
|
521
|
+
JOIN documents d2 ON def_c.document_id = d2.id
|
|
522
|
+
WHERE def_m.symbol_id = gs.id
|
|
523
|
+
AND def_m.role = 1
|
|
524
|
+
AND d2.relative_path IN (${n})
|
|
525
|
+
)
|
|
526
|
+
)
|
|
527
|
+
AND m.role != 1
|
|
528
|
+
AND ${e.localSymbolPredicate}
|
|
529
|
+
${e.pathExclusionsFor("d1")}
|
|
530
|
+
ORDER BY d1.relative_path`,...t,...t,...t)}function D1(e,t){let n=new T(e);return t.flatMap(r=>n.definitionsForFile(r).filter(i=>fe(i.symbol)).map(i=>({relative_path:r,symbol:i.symbol})))}function k1(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 P1(e){return{consumer:e.relative_path,symbol:e.symbol,shortName:I(e.symbol)}}var Jo=new WeakMap,AC=ce({kind:"definition-exclusions",invalidation:X("definition-exclusions"),serialize:e=>JSON.stringify(e),deserialize:F1});function OC(e,t){let n=N(t);if(!(n==="rust"||n==="typescript"||n==="tsx"||n==="javascript"))return[];let i=P(e,t);if(!i)return[];let o=me(e,t,i),s=AC.read(e,t,o);if(s)return s;let a=n==="rust"?j1(e,t):M1(e,t);return AC.write(e,t,o,a),a}function F1(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=t.map(T1);return n.some(r=>r===null)?null:n}catch{return null}}function T1(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.startLine!="number"||!Number.isFinite(t.startLine)||typeof t.endLine!="number"||!Number.isFinite(t.endLine)||typeof t.reason!="string"||t.containerName!==void 0&&typeof t.containerName!="string")return null;let n=t.disposition===void 0?Y1(t.reason):t.disposition;return n!=="exclude"&&n!=="implicit-usage"?null:{startLine:t.startLine,endLine:t.endLine,reason:t.reason,disposition:n,...t.containerName?{containerName:t.containerName}:{}}}var jC=new Set(["describe","it","test","fdescribe","fit","xdescribe","xit","beforeEach","afterEach","beforeAll","afterAll","before","after","suite","bench","benchmark"]),_1=/\b(?:describe|it|test|fdescribe|fit|xdescribe|xit|beforeEach|afterEach|beforeAll|afterAll|before|after|suite|bench|benchmark)\s*\(/,L1=/\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 M1(e,t){let n=P(e,t);if(!n||!A1(n))return[];let r=Y(e,t);if(!r)return[];let i=Jo.get(r);if(i)return i;let o=!1,s=r.rootNode;for(let c of s.namedChildren){if(c.type!=="expression_statement")continue;let l=c.namedChild(0);if(!l||l.type!=="call_expression")continue;let u=l.namedChild(0);if(!u)continue;let d=u.type==="member_expression"?u.namedChild(u.namedChildCount-1)?.text:u.text;if(d&&jC.has(d)){o=!0;break}}let a=[];o&&a.push({startLine:0,endLine:s.endPosition.row,reason:"TS/JS test file (describe/it/test at top level)",disposition:"exclude"});for(let c of s.namedChildren){let l=null,u=null;if(c.type==="function_declaration")l=c.namedChild(0)?.text??null,u=c;else if(c.type==="export_statement"){let d=c.namedChild(0);d?.type==="function_declaration"&&(l=d.namedChild(0)?.text??null,u=d)}else if(c.type==="lexical_declaration"){let d=c.namedChild(0);if(d?.type==="variable_declarator"){let m=d.namedChild(0)?.text,f=d.namedChild(1);m&&(f?.type==="arrow_function"||f?.type==="function_expression")&&(l=m,u=d)}}l&&/^use[A-Z]/.test(l)&&u&&a.push({startLine:u.startPosition.row,endLine:u.endPosition.row,reason:"React custom hook (use*)",disposition:"exclude"})}return a.push(...BC(r,new Set(["function_declaration","method_definition","class_declaration","interface_declaration","type_alias_declaration","enum_declaration","variable_declarator","export_statement"]),new Set(["comment"]))),Jo.set(r,a),a}function A1(e){if(e.includes("scip-query"))return!0;let t=!1;for(let n of jC)if(e.includes(n)){t=!0;break}return t&&_1.test(e)?!0:e.includes("use")&&L1.test(e)}var N1=/scip-query[\s:-]*ignore[\s:-]*(?:dead(?:-code)?|stale)?/i;function O1(e){return N1.test(e)}function BC(e,t,n){let r=[],i=o=>{if(t.has(o.type)&&o.parent){let a=o.parent.children,c=-1;for(let l=0;l<a.length;l+=1)if(a[l].startIndex===o.startIndex&&a[l].type===o.type){c=l;break}if(c>0)for(let l=c-1;l>=0;l-=1){let u=a[l];if(n.has(u.type)){if(O1(u.text)){r.push({startLine:o.startPosition.row,endLine:o.endPosition.row,reason:"scip-query suppression comment",disposition:"exclude"});break}continue}if(!(u.type==="attribute_item"||u.type==="inner_attribute_item"))break}}for(let s of o.namedChildren)i(s)};return i(e.rootNode),r}function j1(e,t){let n=Y(e,t);if(!n)return[];let r=Jo.get(n);if(r)return r;let i=[],o=B1(n);return o?(Jo.set(n,o),o):($C(n.rootNode,i,!1,!1),i.push(...BC(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(...K1(n.rootNode)),Jo.set(n,i),i)}function B1(e){return X1(e.rootNode)?[{startLine:0,endLine:e.rootNode.endPosition.row,reason:"generated file (@generated header)",disposition:"exclude"}]:null}function $C(e,t,n,r){let i=n,o=r;e.type==="trait_item"&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait declaration body (dynamic dispatch)",disposition:"implicit-usage"}),e.type==="impl_item"&&e.childForFieldName("trait")&&(o=!0,t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl block (dynamic dispatch)",disposition:"implicit-usage"})),e.type==="function_item"||e.type==="function_signature_item"?$1(e,t,n,r):r&&z1(e)?t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"trait impl associated item (dynamic dispatch)",disposition:"implicit-usage"}):e.type==="struct_item"||e.type==="enum_item"||e.type==="union_item"?H1(e,t,n):e.type==="mod_item"&&$m(e).some(s=>/#\[\s*cfg\s*\(\s*test\s*\)/.test(s))&&(i=!0);for(let s of e.namedChildren)$C(s,t,i,o)}function $1(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(HC(s)){o={reason:"#[allow(dead_code)]",disposition:"exclude"};break}let a=V1(s);if(a){o=a;break}}o&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:o.reason,disposition:o.disposition})}function H1(e,t,n){let r=$m(e),i=e.namedChildren.find(o=>o.type==="type_identifier")?.text;r.some(W1)&&t.push({startLine:e.startPosition.row,endLine:e.endPosition.row,reason:"#[derive(...)] - generated impl may access fields",disposition:"implicit-usage",containerName:i}),r.some(HC)&&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=-1;for(let o=0;o<n.length;o+=1)if(n[o].startIndex===e.startIndex&&n[o].type===e.type){r=o;break}if(r<=0)return[];let i=[];for(let o=r-1;o>=0;o-=1){let s=n[o];if(s.type==="attribute_item"||s.type==="inner_attribute_item")i.push(s.text);else{if(s.type==="line_comment"||s.type==="block_comment")continue;break}}return i}var U1=new Set(["test","bench","tokio::test","async_std::test"]),q1=new Set(["no_mangle","export_name","link_name","used","macro_export","proc_macro","proc_macro_derive","proc_macro_attribute"]),G1=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 V1(e){if(/#\[\s*cfg\s*\(\s*test\s*\)/.test(e))return{reason:"#[cfg(test)]",disposition:"exclude"};let t=J1(e);return t?U1.has(t)?{reason:`#[${t}]`,disposition:"exclude"}:q1.has(t)?{reason:`Rust ABI/export attribute #[${t}]`,disposition:"implicit-usage"}:G1.has(t)?null:{reason:`Rust attribute macro #[${t}]`,disposition:"implicit-usage"}:null}function W1(e){return/#\[\s*derive\s*\(/.test(e)}function HC(e){return/#\[\s*allow\s*\(\s*dead_code\s*\)/.test(e)}function z1(e){return e.type==="const_item"||e.type==="type_item"||e.type==="static_item"||e.type==="associated_type"}function K1(e){let t=Q1(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 J1(e){let t=/^#!?\[\s*([A-Za-z_][A-Za-z0-9_]*(?:\s*::\s*[A-Za-z_][A-Za-z0-9_]*)*)/.exec(e);return t?t[1].replace(/\s+/g,""):null}function Y1(e){return e==="#[tauri::command]"||e==="#[command]"||e==="#[wasm_bindgen]"||e==="#[no_mangle]"||e==="#[napi]"||e==="#[pyfunction]"||e==="#[pymethod]"||e==="#[pyo3]"||e==="#[doc(hidden)]"||e.startsWith("trait ")||e.startsWith("#[derive(<reflective>)]")||e.startsWith("#[derive(...)]")||e.startsWith('serde `with = "')||e.startsWith('attribute `with = "')||e.startsWith("Rust attribute macro #[")||e.startsWith("Rust ABI/export attribute #[")?"implicit-usage":"exclude"}function X1(e){for(let t=0;t<Math.min(e.namedChildCount,12);t+=1){let n=e.namedChild(t);if(!n||n.type!=="line_comment"&&n.type!=="block_comment")break;if(/@generated\b/.test(n.text)||/This file is .*generated\b/i.test(n.text)||/Code generated by/i.test(n.text)||/Generated by:\s*https?:\/\/openapi-generator/i.test(n.text)||/openapi-generator/i.test(n.text)&&/Generated by/i.test(n.text))return!0}return!1}var NC=/\bwith\s*=\s*"([^"]+)"/g;function Q1(e){let t=new Set;for(let n of e.descendantsOfType("attribute_item")){NC.lastIndex=0;let r;for(;(r=NC.exec(n.text))!==null;){let i=r[1],o=i.split("::").pop()??i;o&&t.add(o)}}return t}function UC(e){let t=Hm(e);return(n,r,i,o)=>t(n,r,i,o)?.disposition==="exclude"}function Hm(e){let t=new Map,n=r=>{let i=t.get(r);if(i)return i;let o=OC(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 ua(o))l.add(u);for(let u of l){let d=a.containers.get(u);d&&c.push(...d)}return Z1(c)}}function Z1(e){if(e.length===0)return null;let n=e.find(r=>r.disposition==="exclude")??e[0];return{disposition:n.disposition,reason:n.reason}}function Um(e,t={}){wl(e,{groups:t.semanticProvider===!0?["whole-project","semantic-provider"]:["whole-project"]})}function qC(e,t,n={}){wl(e,{groups:n.definitions===!0?["source-file","definition-catalog"]:["source-file"],file:t.replace(/\\/g,"/")})}function GC(e,t){if(t.isIgnoredPath(e.relativePath))return Ve("ignored-file");if(In(e.symbol))return Ve("module-like-symbol");if(!Dc(e.symbol))return Ve("non-value-symbol");if(!e.isFunctionLike&&e.enclosingSymbol&&Dc(e.enclosingSymbol))return Ve("nested-non-callable-value");if(!t.includeTests&&!eH(e.relativePath))return Ve("test-file");if(!t.includeTests&&t.isExcludedRegion(e.relativePath,e.startLine,e.symbol,e.parentTypeName))return Ve("excluded-file-region");let n=F(e.symbol);if(n==="<constructor>")return Ve("implicit-constructor");if(e.symbol.startsWith("scip-python ")){if(n==="__all__")return Ve("python-runtime-metadata");if(/^__[^_].*__$/.test(n))return Ve("python-protocol-member")}return t.isDeclarationOnlyCallable()?Ve("declaration-only-callable"):t.isFrameworkContractCallable()?Ve("framework-contract-member"):Fe(e.symbol)?Ve("rust-trait-impl-member"):Or(e.symbol)?Ve("rust-test-module"):!t.includeMembers&&!tH(e)?Ve("member"):e.endLine-e.startLine+1<t.minLoc?Ve("below-min-loc"):{accepted:!0}}function eH(e){return W(e)!=="test"}function Ve(e){return{accepted:!1,rejectionReason:e}}function Dc(e){return oe(e)||e.endsWith("().")||e.endsWith(".")}function tH(e){return fe(e.symbol)||ua(e.symbol).length===0}function kc(e,t){return O(e)-O(t)||e.relativePath.localeCompare(t.relativePath)}function le(e,t){return typeof t!="number"||t<=0||e.length<=t?e:e.slice(0,t)}function Ci(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 VC(){return new Map}function WC(e,t,n){let r=new Map;for(let i of Wh(e,n))e.isIgnored(i.relative_path)||t.has(i.relative_path)||Fc(r,i.symbol_id,i.relative_path,i.ref_count,"scip-mention");return r}function zC(e,t,n,r={}){let i=new Set;if(r.conservative||n.size===0){for(let o of Kh(e,t))i.add(o.symbol_id);return i}for(let o of zh(e,t))e.isIgnored(o.relative_path)||n.has(o.relative_path)||i.add(o.symbol_id);return i}function qm(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 Pc(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 KC(e){return e?.occurrences??0}function Fc(e,t,n,r,i="source-fallback"){if(r<=0)return;let o=YC(e,t,n);o.occurrences+=r,o.sources.add(i)}function JC(e,t,n,r,i){if(r<=0)return;let o=YC(e,t,n);o.occurrences=Math.max(r,o.occurrences),o.sources.add(i)}function YC(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 nH=new Set(["componentDidCatch","componentDidMount","componentDidUpdate","componentWillUnmount","getDerivedStateFromError","getDerivedStateFromProps","getSnapshotBeforeUpdate","render","shouldComponentUpdate","UNSAFE_componentWillMount","UNSAFE_componentWillReceiveProps","UNSAFE_componentWillUpdate"]);function Ri(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=Y(e,t.relativePath);if(!n)return!1;let r=n.rootNode.descendantsOfType("method_definition").find(s=>s.startPosition.row<=t.startLine&&s.endPosition.row>=t.endLine);if(!r)return!1;if(/\boverride\b/.test(r.text.slice(0,Math.max(0,r.text.indexOf("{")))))return!0;let i=r.parent;for(;i&&i.type!=="class_declaration"&&i.type!=="class";)i=i.parent;if(!i)return!1;let o=i.text.slice(0,Math.max(0,i.text.indexOf("{")));return/\bimplements\b/.test(o)||/\bextends\b/.test(o)?!0:nH.has(t.leaf)&&/\bextends\s+(?:React\.)?(?:Component|PureComponent)\b/.test(o)}var rH=1e3,iH=300;function Dr(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=E("dead.candidates",()=>{let x=le(oH(e,{scope:n,minLoc:r,includeTests:i,includeMembers:s}),c);return u=x.length,x},()=>({definitions:u})),m=0,f=o?E("dead.inactive-barrels",()=>{let x=new Set(CC(e));return m=x.size,x},()=>({paths:m})):new Set,p=0,g=a?VC():E("dead.mention-reference-counts",()=>{let x=WC(e,f,d.map(v=>v.symbolId));return p=x.size,x},()=>({definitions:d.length,symbolsWithReferences:p})),y=0,h=a?E("dead.mentioned-symbol-ids",()=>{let x=zC(e,d.map(v=>v.symbolId),f,{conservative:f.size===0});return y=x.size,x},()=>({definitions:d.length,referencedSymbols:y})):new Set,C=a?d.filter(x=>!h.has(x.symbolId)):d.filter(x=>!Pc(g,x.symbolId,x.relativePath));a?E("dead.source-fallback.dead-code-only",()=>mH(e,C,g,{inactiveBarrelPaths:f}),()=>({definitions:C.length,testReferencesIncluded:!0})):E("dead.source-fallback.ast",()=>dH(e,C,g,{inactiveBarrelPaths:f}),()=>({definitions:C.length,testReferencesIncluded:!0}));let b=a?C.filter(x=>!qm(g,x.symbolId)):C.filter(x=>!Pc(g,x.symbolId,x.relativePath));E("dead.caller-map-supplement",()=>yH(e,b,g,{inactiveBarrelPaths:f,includeSemantic:!a&&l}),()=>({definitions:b.length,semantic:!a&&l}));let S=a?C.filter(x=>!qm(g,x.symbolId)):d;return uH(e,cH(S,g))}function oH(e,t){let n=UC(e),r=[];for(let i of Zi(e,{scope:t.scope,symbolMatches:Dc,sqlPrefilter:"function-like"}))GC(i,{minLoc:t.minLoc,includeTests:t.includeTests,includeMembers:t.includeMembers,isIgnoredPath:s=>e.isIgnored(s),isExcludedRegion:n,isDeclarationOnlyCallable:()=>aH(e,i),isFrameworkContractCallable:()=>Ri(e,i)}).accepted&&r.push(i);return r}var sH=["method_signature","abstract_method_signature","call_signature","construct_signature"];function aH(e,t){if(!t.parentTypeName||!/\.[cm]?[jt]sx?$/.test(t.relativePath))return!1;let n=Y(e,t.relativePath);if(n)return n.rootNode.descendantsOfType([...sH]).some(i=>i.startPosition.row<=t.startLine&&i.endPosition.row>=t.endLine);let r=Ee(e,t.relativePath).slice(t.startLine,t.endLine+1).join(`
|
|
531
|
+
`).trim();return r.endsWith(";")&&!r.includes("=>")&&!r.includes("{")}function cH(e,t){return e.map(n=>lH(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 lH(e,t){let n=t.get(e.symbolId)??new Map,r=KC(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 uH(e,t){let n=Hm(e),r=[],i=0,o=0,s=0,a=0,c=0,l=0;for(let u of t){if(e.isIgnored(u.relative_path))continue;if(Le(e,u.relative_path)){a++;continue}if(ge(e,u.symbol,u.relative_path)){c++;continue}let d=n(u.relative_path,u.start_line,u.symbol,u.parent_type_name),m=d?.disposition==="implicit-usage"?d.reason:void 0,f=m?"implicit-usage":u.same_file_refs===0?"dead-code":"file-internal";f==="dead-code"?i++:f==="file-internal"?o++:s++,l+=u.loc,r.push({relativePath:u.relative_path,startLine:u.start_line,endLine:u.end_line,loc:u.loc,symbol:u.symbol,shortName:I(u.symbol),sameFileRefs:u.same_file_refs,kind:f,...m?{implicitUsageReason:m}:{}})}return{symbols:r,counts:{total:r.length,deadCode:i,fileInternal:o,implicitUsage:s,loc:l},applicability:{entrySurfaceExcluded:a,externalRootExcluded:c,implicitUsageSignals:s},totalCount:r.length,deadCodeCount:i,fileInternalCount:o,implicitUsageCount:s,totalLoc:l}}function dH(e,t,n,r){if(t.length===0)return;let i=new T(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 M(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)&&(gH(e,c)||Fc(n,c.target.symbolId,c.sourceFile,hH(c),"source-fallback"))})}function mH(e,t,n,r){if(t.length===0)return;let i=new T(e),o=fH(t),s=new Set(i.sourceFiles());for(let u of M(e))s.add(u);let a=new Set(o.keys()),c=new Map,l=u=>{let d=c.get(u);return d||(d=ba(e,u),c.set(u,d)),d};i.scanSourceReferences({paths:s,includeVueSfc:!0,includeCrossLanguageDispatchNames:!0,includeRustAttributeNames:!0,identifierResolution:"permissive",candidateNames:a,skipPath:u=>r.inactiveBarrelPaths.has(u),resolveTargets:({sourceFile:u,name:d,kind:m})=>{let f=o.get(d);return f?pH(u,d,f,()=>l(u),{permissive:m!=="cross-language-dispatch"}):[]},afterPath:u=>{c.delete(u),qC(e,u)}},u=>{let d=u.kind==="identifier"&&u.sourceFile===u.target.relativePath?Math.max(0,u.occurrences-1):u.occurrences;u.kind==="identifier"&&XC(e,{sourceFile:u.sourceFile,name:u.name,target:u.target,occurrences:d})||Fc(n,u.target.symbolId,u.sourceFile,d,"source-fallback")})}function fH(e){let t=new Map;for(let n of e){if(!n.leaf)continue;let r=t.get(n.leaf)??[];r.push(n),t.set(n.leaf,r)}return t}function pH(e,t,n,r,i){let o=n.filter(l=>l.relativePath===e);if(o.length>0)return o;if(!i.permissive&&n.length===1)return[...n];let s=r(),a=s.get(t);if(a)for(let l of a){let u=n.filter(d=>Qe(l,d.relativePath));if(u.length>0)return u}let c=new Set;for(let l of s.values())for(let u of l)c.add(u);for(let l of c){let u=n.filter(d=>Qe(l,d.relativePath));if(u.length>0&&u.length===n.length)return u}return i.permissive?[...n]:[]}function gH(e,t){return t.kind==="cross-language-dispatch"&&t.target.relativePath===t.sourceFile?!0:t.kind==="identifier"&&XC(e,t)}function hH(e){return e.kind==="identifier"&&e.target.relativePath===e.sourceFile?Math.max(0,e.occurrences-1):e.occurrences}function XC(e,t){return t.occurrences>1?!1:te(e,t.sourceFile).some(n=>n.used||n.sourcePath!==t.target.relativePath?!1:n.importedName===t.name||n.localName===t.name)}function yH(e,t,n,r){let i=r.includeSemantic!==!1,o=i&&t.length>=rH&&M(e).length>=iH,s=(u,d)=>{d===u.relativePath||e.isIgnored(d)||r.inactiveBarrelPaths.has(d)||JC(n,u.symbolId,d,1,"caller-map")};if(o?E("dead.caller-map.per-symbol-non-semantic",()=>{for(let u of t){let d=Dt(e,u,{semantic:!1,semanticEvidence:U});for(let m of d)s(u,m.file)}},()=>({definitions:t.length,semantic:!1})):E("dead.caller-map.per-symbol",()=>{for(let u of t){let d=Dt(e,u,{semantic:i,semanticEvidence:U});if(d.length!==0)for(let m of d)s(u,m.file)}},()=>({definitions:t.length,semantic:i})),!o)return;let a=0,c=E("dead.caller-map.semantic-candidates",()=>{let u=t.filter(d=>!Pc(n,d.symbolId,d.relativePath));return a=u.length,u},()=>({definitions:t.length,semanticCandidates:a}));if(c.length===0)return;let l=lS(e,c);for(let u of c){let d=l.get(u.symbolId);if(d)for(let m of d)s(u,m)}}function bH(e,t={}){let{limit:n=30,scope:r}=t,i=r?"AND def_d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[],a=e.all(`SELECT
|
|
532
|
+
gs.symbol,
|
|
533
|
+
COUNT(*) AS ref_count,
|
|
534
|
+
COUNT(DISTINCT ref_d.id) AS file_count,
|
|
535
|
+
def_d.relative_path AS defined_in
|
|
536
|
+
FROM mentions m
|
|
537
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
538
|
+
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
539
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
540
|
+
JOIN (
|
|
541
|
+
SELECT m2.symbol_id, c2.document_id
|
|
542
|
+
FROM mentions m2
|
|
543
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
544
|
+
WHERE m2.role = 1
|
|
545
|
+
GROUP BY m2.symbol_id
|
|
546
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
547
|
+
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
548
|
+
WHERE m.role != 1
|
|
549
|
+
AND def_d.id != ref_d.id
|
|
550
|
+
${e.pathExclusionsFor("def_d")}
|
|
551
|
+
${e.symbolNoiseFor("gs")}
|
|
552
|
+
${i}
|
|
553
|
+
GROUP BY gs.id
|
|
554
|
+
ORDER BY ref_count DESC
|
|
555
|
+
LIMIT ?`,...o,n).filter(c=>!e.isIgnored(c.defined_in)).map(c=>({symbol:c.symbol,shortName:I(c.symbol),refCount:c.ref_count,fileCount:c.file_count,definedIn:c.defined_in}));return a.length>0?a:SH(e,r,n)}function SH(e,t,n){return De(e,{scope:t}).filter(r=>!e.isIgnored(r.relativePath)).map(r=>xH(e,r)).filter(r=>r.refCount>0).sort((r,i)=>i.refCount-r.refCount||i.fileCount-r.fileCount).slice(0,n)}function xH(e,t){let r=Dt(e,t,{limit:500,semanticEvidence:U}).filter(i=>i.file!==t.relativePath);return{symbol:t.symbol,shortName:I(t.symbol),refCount:r.length,fileCount:new Set(r.map(i=>i.file)).size,definedIn:t.relativePath}}function CH(e,t,n={}){return TH(e,t,n)?.map(r=>({symbol:r.symbol,shortName:r.shortName,fromFile:r.fromFile}))??[]}function RH(e,t){let n=$(e,t),r=wH(e,t);if(r.length>0&&!DH(n))return r;let i=EH(e,t,n);return Gm(t)&&i.length>0?i:kH([...r,...i])}function vH(e,t,n={}){let r=Ge(e,t);if(!r)return[];let i=ZC(e,r),o=n.semantic===!1?null:QC(e,r);return(o?IH(o,i):i).filter(a=>!a.used).map(a=>({symbol:a.symbol,shortName:a.shortName,importedIn:a.importer}))}function IH(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 wH(e,t){return e.all(`SELECT DISTINCT gs.symbol, d.relative_path AS importer
|
|
556
|
+
FROM mentions m
|
|
557
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
558
|
+
JOIN documents d ON c.document_id = d.id
|
|
559
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
560
|
+
WHERE gs.symbol LIKE ?
|
|
561
|
+
AND m.role = 2
|
|
562
|
+
ORDER BY d.relative_path`,`%${t}%`).filter(r=>!e.isIgnored(r.importer)).map(r=>({symbol:r.symbol,shortName:I(r.symbol),fromFile:r.importer}))}function EH(e,t,n=$(e,t)){let r=n?.relativePath??null,i=n?F(n.symbol):t.replace(/\(\)$/,""),o=n?In(n.symbol):!1,s=new Set;for(let c of M(e,{includeIgnored:!1}))for(let l of te(e,c))PH(l,c,{targetFile:r,targetLeaf:i,targetIsModule:o,targetPattern:t})&&s.add(c);let a=Gm(t)?t.trim():null;return[...s].sort().map(c=>({symbol:a??n?.symbol??i,shortName:a??(n?I(n.symbol):i),fromFile:c}))}function DH(e){return!!(e&&(e.symbol.startsWith("scip-clojure ")||N(e.relativePath)==="clojure"))}function kH(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 PH(e,t,n){return!e.sourcePath||n.targetFile&&se(e.sourcePath)!==se(n.targetFile)?!1:e.kind==="side-effect"||n.targetFile&&AH(t)||e.kind==="namespace"&&FH(e,n.targetPattern)||n.targetIsModule||e.kind==="named"&&e.importedName===n.targetLeaf?!0:e.kind==="namespace"&&e.usedMembers.includes(n.targetLeaf)}function FH(e,t){let n=t.trim().replace(/\(\)$/,"");return Gm(n)?e.importedName===n||e.localName===n:!1}function Gm(e){let t=e.trim().replace(/\(\)$/,"");return t.includes(".")&&!t.includes("/")&&!t.includes(":")}function TH(e,t,n={}){let r=Ge(e,t);return r?_H(e,r,n)??(n.semantic===!1?null:QC(e,r))??ZC(e,r):null}function _H(e,t,n){let i=e.all(`SELECT DISTINCT
|
|
563
|
+
gs.symbol,
|
|
564
|
+
def_d.relative_path AS from_file,
|
|
565
|
+
imp_d.relative_path AS importer,
|
|
566
|
+
EXISTS (
|
|
567
|
+
SELECT 1
|
|
568
|
+
FROM mentions ref_m
|
|
569
|
+
JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
|
|
570
|
+
WHERE ref_m.symbol_id = gs.id
|
|
571
|
+
AND ref_m.role != 1
|
|
572
|
+
AND ref_c.document_id = imp_d.id
|
|
573
|
+
) AS used
|
|
574
|
+
FROM mentions m
|
|
575
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
576
|
+
JOIN documents imp_d ON c.document_id = imp_d.id
|
|
577
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
578
|
+
LEFT JOIN (
|
|
579
|
+
SELECT m2.symbol_id, c2.document_id
|
|
580
|
+
FROM mentions m2
|
|
581
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
582
|
+
WHERE m2.role = 1
|
|
583
|
+
GROUP BY m2.symbol_id
|
|
584
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
585
|
+
LEFT JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
586
|
+
WHERE imp_d.relative_path = ?
|
|
587
|
+
AND m.role = 2
|
|
588
|
+
ORDER BY def_d.relative_path, gs.symbol`,t).filter(o=>!e.isIgnored(o.importer));if(i.length>0){let o=n.semantic===!1?[]:Fo(e,t);return i.map(s=>({symbol:s.symbol,shortName:I(s.symbol),fromFile:s.from_file??"(external)",importer:s.importer,used:s.used!==0||o.some(a=>a.isUsed&&a.sourcePath===s.from_file)}))}return null}function QC(e,t){let n=Fo(e,t);return n.length>0?n.map(r=>{let i=eR(r.importedName,r.localName,r.kind);return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:r.kind==="side-effect"?!0:r.isUsed}}):null}function ZC(e,t){let n=LH(t,P(e,t));return te(e,t).map(r=>{let i=eR(r.importedName,r.localName,r.kind),o=r.kind==="side-effect"||MH(t,r)||n.has(r.localName??r.importedName)?!0:r.used;return{symbol:i,shortName:i,fromFile:r.sourcePath??"(external)",importer:t,used:o}})}function LH(e,t){let n=new Set;if(N(e)!=="python")return n;let r=/(?:^|\n)\s*__all__\s*(?:\+?=)\s*[[(]([\s\S]*?)[\])]/g;for(let i of t.matchAll(r)){let o=i[1]??"";for(let s of o.matchAll(/(['"])([A-Za-z_]\w*)\1/g))n.add(s[2])}return n}function MH(e,t){if(N(e)!=="rust"||t.used||t.kind==="side-effect")return!1;let n=t.localName??t.importedName;return n==="_"||/^[A-Z]/.test(n)}function eR(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 AH(e){return/\.(?:c|h|cc|cpp|cxx|hpp|hh|hxx)$/i.test(e)}function NH(e,t){let n=$(e,t);if(!n)return[];let i=new T(e).definitionsForFile(n.relativePath).filter(o=>o.symbol!==n.symbol).filter(o=>ag(n.symbol,o.symbol)).sort((o,s)=>o.startLine-s.startLine||o.endLine-s.endLine).map(o=>({symbol:o.symbol,shortName:I(o.symbol),startLine:o.startLine,endLine:o.endLine,kind:pe(o.symbol)??"unknown"}));return N(n.relativePath)!=="clojure"?i:jH(i,OH(e,n))}function OH(e,t){let n=F(t.symbol);if(!n)return[];let r=I(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 jH(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 BH(e,t){let n=$(e,t);if(!n)return[];let r=e.get(`SELECT COUNT(DISTINCT c.document_id) AS file_count
|
|
589
|
+
FROM mentions m
|
|
590
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
591
|
+
JOIN (
|
|
592
|
+
SELECT m2.symbol_id, c2.document_id
|
|
593
|
+
FROM mentions m2
|
|
594
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
595
|
+
WHERE m2.role = 1
|
|
596
|
+
GROUP BY m2.symbol_id
|
|
597
|
+
) sym_def ON sym_def.symbol_id = m.symbol_id
|
|
598
|
+
WHERE m.symbol_id = ?
|
|
599
|
+
AND m.role != 1
|
|
600
|
+
AND sym_def.document_id != c.document_id`,n.symbolId);return[{name:I(n.symbol),count:r?.file_count??0,symbol:n.symbol,definedIn:n.relativePath}]}function $H(e,t){let n=Ge(e,t);if(!n)return[];let i=e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
|
|
601
|
+
FROM mentions m
|
|
602
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
603
|
+
JOIN documents d ON c.document_id = d.id
|
|
604
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
605
|
+
JOIN (
|
|
606
|
+
SELECT m2.symbol_id, c2.document_id
|
|
607
|
+
FROM mentions m2
|
|
608
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
609
|
+
WHERE m2.role = 1
|
|
610
|
+
GROUP BY m2.symbol_id
|
|
611
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
612
|
+
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
613
|
+
WHERE d.relative_path = ?
|
|
614
|
+
AND m.role != 1
|
|
615
|
+
AND def_d.id != d.id
|
|
616
|
+
GROUP BY d.id
|
|
617
|
+
ORDER BY symbol_count DESC`,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}));if(i.length>0)return i;let s=ae(e).get(n);return!s||s.size===0?[]:[{name:n,count:s.size}]}function HH(e,t={}){return UH(e,t).map(n=>({name:I(n.symbol),count:n.file_count,symbol:n.symbol,definedIn:n.defined_in}))}function UH(e,t){let{limit:n=30,scope:r}=t,i=r?"AND def_d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[];return e.all(`SELECT gs.symbol,
|
|
618
|
+
COUNT(DISTINCT c.document_id) AS file_count,
|
|
619
|
+
def_d.relative_path AS defined_in
|
|
620
|
+
FROM mentions m
|
|
621
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
622
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
623
|
+
JOIN (
|
|
624
|
+
SELECT m2.symbol_id, c2.document_id
|
|
625
|
+
FROM mentions m2
|
|
626
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
627
|
+
WHERE m2.role = 1
|
|
628
|
+
GROUP BY m2.symbol_id
|
|
629
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
630
|
+
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
631
|
+
WHERE m.role != 1
|
|
632
|
+
AND def_d.id != c.document_id
|
|
633
|
+
${e.pathExclusionsFor("def_d")}
|
|
634
|
+
${e.symbolNoiseFor("gs")}
|
|
635
|
+
${i}
|
|
636
|
+
GROUP BY gs.id
|
|
637
|
+
HAVING file_count > 1
|
|
638
|
+
ORDER BY file_count DESC
|
|
639
|
+
LIMIT ?`,...o,n)}function qH(e,t={}){let{limit:n=30,scope:r}=t,i=r?"AND d.relative_path LIKE ?":"",o=r?[`%${r}%`]:[];return e.all(`SELECT d.relative_path, COUNT(DISTINCT gs.id) AS symbol_count
|
|
640
|
+
FROM mentions m
|
|
641
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
642
|
+
JOIN documents d ON c.document_id = d.id
|
|
643
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
644
|
+
JOIN (
|
|
645
|
+
SELECT m2.symbol_id, c2.document_id
|
|
646
|
+
FROM mentions m2
|
|
647
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
648
|
+
WHERE m2.role = 1
|
|
649
|
+
GROUP BY m2.symbol_id
|
|
650
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
651
|
+
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
652
|
+
WHERE m.role != 1
|
|
653
|
+
AND def_d.id != d.id
|
|
654
|
+
${e.pathExclusionsFor("d")}
|
|
655
|
+
${e.symbolNoiseFor("gs")}
|
|
656
|
+
${i}
|
|
657
|
+
GROUP BY d.id
|
|
658
|
+
ORDER BY symbol_count DESC
|
|
659
|
+
LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.relative_path)).map(a=>({name:a.relative_path,count:a.symbol_count}))}function GH(e,t,n){let r=Ge(e,t)??t,i=Ge(e,n)??n,o=e.get(`SELECT COUNT(DISTINCT gs.id) AS shared
|
|
660
|
+
FROM global_symbols gs
|
|
661
|
+
WHERE (
|
|
662
|
+
-- Defined in file1, referenced in file2
|
|
663
|
+
EXISTS (
|
|
664
|
+
SELECT 1
|
|
665
|
+
FROM mentions def_m
|
|
666
|
+
JOIN chunks def_c ON def_m.chunk_id = def_c.id
|
|
667
|
+
JOIN documents d ON def_c.document_id = d.id
|
|
668
|
+
WHERE def_m.symbol_id = gs.id AND def_m.role = 1 AND d.relative_path = ?
|
|
669
|
+
)
|
|
670
|
+
AND EXISTS (
|
|
671
|
+
SELECT 1 FROM mentions m
|
|
672
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
673
|
+
JOIN documents d ON c.document_id = d.id
|
|
674
|
+
WHERE m.symbol_id = gs.id AND m.role != 1 AND d.relative_path = ?
|
|
675
|
+
)
|
|
676
|
+
) OR (
|
|
677
|
+
-- Defined in file2, referenced in file1
|
|
678
|
+
EXISTS (
|
|
679
|
+
SELECT 1
|
|
680
|
+
FROM mentions def_m
|
|
681
|
+
JOIN chunks def_c ON def_m.chunk_id = def_c.id
|
|
682
|
+
JOIN documents d ON def_c.document_id = d.id
|
|
683
|
+
WHERE def_m.symbol_id = gs.id AND def_m.role = 1 AND d.relative_path = ?
|
|
684
|
+
)
|
|
685
|
+
AND EXISTS (
|
|
686
|
+
SELECT 1 FROM mentions m
|
|
687
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
688
|
+
JOIN documents d ON c.document_id = d.id
|
|
689
|
+
WHERE m.symbol_id = gs.id AND m.role != 1 AND d.relative_path = ?
|
|
690
|
+
)
|
|
691
|
+
)`,r,i,i,r);return{...tR(r,i,o?.shared??0)}}function VH(e,t={}){let{limit:n=20,scope:r}=t,i=r?"AND def_d.relative_path LIKE ? AND ref_d.relative_path LIKE ?":"",o=r?[`%${r}%`,`%${r}%`]:[];return e.all(`SELECT
|
|
692
|
+
def_d.relative_path AS file1,
|
|
693
|
+
ref_d.relative_path AS file2,
|
|
694
|
+
COUNT(DISTINCT gs.id) AS shared
|
|
695
|
+
FROM mentions m
|
|
696
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
697
|
+
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
698
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
699
|
+
JOIN (
|
|
700
|
+
SELECT m2.symbol_id, c2.document_id
|
|
701
|
+
FROM mentions m2
|
|
702
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
703
|
+
WHERE m2.role = 1
|
|
704
|
+
GROUP BY m2.symbol_id
|
|
705
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
706
|
+
JOIN documents def_d ON sym_def.document_id = def_d.id
|
|
707
|
+
WHERE m.role != 1
|
|
708
|
+
AND def_d.id != ref_d.id
|
|
709
|
+
${e.pathExclusionsFor("def_d","ref_d")}
|
|
710
|
+
${i}
|
|
711
|
+
GROUP BY def_d.id, ref_d.id
|
|
712
|
+
ORDER BY shared DESC
|
|
713
|
+
LIMIT ?`,...o,n).filter(a=>!e.isIgnored(a.file1)&&!e.isIgnored(a.file2)).map(a=>tR(a.file1,a.file2,a.shared))}function tR(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 Yo(e,t={}){return iR(e,t).cycles}function iR(e,t={}){let{scope:n,maxDepth:r=10}=t,i=ae(e,n,{scipEdges:"imports-only"}),o=[],s=new Set,a=new Set,c=[],l=!1;function u(m,f){if(f>r){l=!0;return}if(a.has(m)){let g=c.indexOf(m);if(g!==-1){let y=c.slice(g).concat(m),h=y.indexOf(y.reduce((S,x)=>S<x?S:x)),C=[...y.slice(h,-1),...y.slice(0,h),y[h]],b=C.join(" -> ");d.has(b)||(d.add(b),o.push({path:C,kind:WH(C)}))}return}if(s.has(m))return;s.add(m),a.add(m),c.push(m);let p=i.get(m);if(p)for(let g of p)u(g,f+1);c.pop(),a.delete(m)}let d=new Set;for(let m of i.keys())s.has(m)||u(m,0);return o.sort((m,f)=>m.kind!==f.kind?m.kind==="real"?-1:1:m.path.length-f.path.length),{cycles:o,truncated:l,maxDepth:r}}function WH(e){for(let r of e){let i=W(r);if(i==="test"||i==="barrel"||i==="entry")return"module-hierarchy"}if(e.length!==3)return"real";let[t,n]=e;return!t||!n?"real":xi(t)||xi(n)||nR(t,n)||nR(n,t)||rR(t,n)||rR(n,t)||W(t)==="entry"||W(n)==="entry"?"module-hierarchy":"real"}function nR(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=t.replace(/\.rs$/,"/");return e.startsWith(n)?!e.slice(n.length).includes("/"):!1}function rR(e,t){if(!/\.rs$/.test(e)||!/\.rs$/.test(t))return!1;let n=e.replace(/\.rs$/,""),r=t.replace(/\.rs$/,"");if(n===r+"_tests"||n===r+"/tests")return!0;let i=e.split("/"),o=t.split("/");if(i.length===o.length&&i.includes("tests")&&o.includes("src")){let s=i[i.length-1],a=o[o.length-1];if(s&&s===a)return!0}return!1}import{readdirSync as zH}from"fs";import{join as oR}from"path";function Wn(e,t){let n=Tc(e),r=Tc(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 KH(e){return Tc(e).replace(/\/\*\*?$/,"")}function _c(e,t){let n=Tc(t),r=KH(n),i=n.endsWith("/**"),o=[],s=(a,c)=>{let l;try{l=zH(a,{withFileTypes:!0})}catch{return}for(let u of l){if(u.name.startsWith("."))continue;let d=c?`${c}/${u.name}`:u.name;Wn(n,d)&&o.push(d),i&&u.isDirectory()&&s(oR(a,u.name),d)}};return s(oR(e,r),r),o.sort()}function Tc(e){return e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/+$/,"")}function Xo(e){let t=new Map,n=[],r=new Map,i=new Map,o=new Set,s=[],a=0,c=l=>(e.get(l)??[]).values();for(let l of e.keys()){if(r.has(l))continue;let u=[];for(r.set(l,a),i.set(l,a),a+=1,s.push(l),o.add(l),u.push({node:l,iter:c(l),pendingChild:null});u.length>0;){let d=u[u.length-1];if(d.pendingChild!==null){let p=d.pendingChild;d.pendingChild=null,i.set(d.node,Math.min(i.get(d.node),i.get(p)))}let m=d.iter.next();if(m.done){if(i.get(d.node)===r.get(d.node)){let p=[];for(;;){let g=s.pop();if(o.delete(g),p.push(g),t.set(g,n.length),g===d.node)break}n.push(p)}u.pop();continue}let f=m.value;r.has(f)?o.has(f)&&i.set(d.node,Math.min(i.get(d.node),r.get(f))):(r.set(f,a),i.set(f,a),a+=1,s.push(f),o.add(f),d.pendingChild=f,u.push({node:f,iter:c(f),pendingChild:null}))}}return{components:n,componentOf:t}}var JH=/\.(test|spec)\.(ts|tsx|js|jsx|mts|cts)$/,sR=new Map;function aR(e,t,n,r){if(!t?.testPaths?.length)return[];let i=YH(t),o=[];for(let s of XH(e,t.testPaths)){let a=QH(e,s,r),c=a?n(a):null;if(c)for(let l of te(e,s)){let u=l.sourcePath;if(!u)continue;let d=n(u);d&&d!==c&&(i.get(c)?.has(d)||o.push({testFile:s,ownerBoundary:c,importedFile:u,importedBoundary:d,reason:"outside-owner-policy"}))}}return ZH(o)}function YH(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 XH(e,t){let n=`${e.config.projectRoot}\0${t.join("\0")}`,r=sR.get(n);if(r)return r;let i=new Set;for(let s of t)for(let a of _c(e.config.projectRoot,s))JH.test(a)&&i.add(a);let o=[...i].sort();return sR.set(n,o),o}function QH(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=te(e,t).map(s=>s.sourcePath).filter(s=>!!s&&n(s)&&s.split("/").pop()===i);return o.length===1?o[0]:null}function ZH(e){let t=new Map;for(let n of e){let r=`${n.testFile}\0${n.importedBoundary}`;t.has(r)||t.set(r,n)}return[...t.values()].sort((n,r)=>n.testFile.localeCompare(r.testFile)||n.importedBoundary.localeCompare(r.importedBoundary))}var kt="architecture:";function cR(e,t,n,r={}){let i=nU(e,t);if(!n||n.boundaries.length===0)return{configured:!1,boundaries:[],edges:[],forbiddenEdges:[],reciprocalPairs:[],cycles:[],coarseBoundaries:[],staleAllowances:[],boundaryLimits:[],fragileEdges:[],testBoundaryViolations:[],coverage:{totalFiles:i.length,mappedFiles:0,unmappedFiles:[],ambiguousFiles:[]},policyCoverage:{declaredRows:0,totalBoundaries:0,missingRows:[],requiresCompletePolicy:!1,requiresMinimalPolicy:!1}};let o=new Map,s=new Map(n.boundaries.map(b=>[b.name,new Set])),a=[],c=[];for(let b of i){let S=n.boundaries.filter(x=>x.paths.some(v=>Wn(v,b))).map(x=>x.name).sort();if(S.length===0)a.push(b);else if(S.length>1)c.push({file:b,boundaries:S});else{let x=S[0];o.set(b,x),s.get(x).add(b)}}let l=new Map;for(let[b,S]of e){let x=o.get(b);if(x)for(let v of S){let R=o.get(v);if(!R||x===R)continue;let D=vi(x,R),w=l.get(D);w||(w={from:x,to:R,fileEdges:[],importers:new Set,importedFiles:new Set},l.set(D,w)),w.fileEdges.push({fromFile:b,toFile:v}),w.importers.add(b),w.importedFiles.add(v)}}let u=[...l.values()].map(b=>rU(b,n)).sort(dU),d=u,m=new Map(d.map(b=>[vi(b.from,b.to),b])),f=new Map(n.boundaries.map(b=>[b.name,new Set]));for(let b of d)f.get(b.from).add(b.to);let p=[];for(let b of d){if(b.from>=b.to)continue;let S=m.get(vi(b.to,b.from));S&&p.push({boundaries:[b.from,b.to],forward:b,reverse:S})}let{components:g}=Xo(f),y=g.filter(b=>b.length>1).map(b=>oU(b,d,n.requireAcyclic===!0)).sort((b,S)=>S.boundaries.length-b.boundaries.length||b.boundaries.join("/").localeCompare(S.boundaries.join("/"))),h=n.allowedDependencies??{},C=n.boundaries.map(b=>b.name).filter(b=>!Object.hasOwn(h,b)).sort();return{configured:!0,boundaries:n.boundaries.map(b=>({name:b.name,paths:[...b.paths],fileCount:s.get(b.name).size,dependencyPolicyDeclared:Object.hasOwn(h,b.name)})).sort((b,S)=>b.name.localeCompare(S.name)),edges:u,forbiddenEdges:d.filter(b=>b.policyStatus==="forbidden"),reciprocalPairs:p,cycles:y,staleAllowances:aU(n,d),boundaryLimits:cU(n,d,s),fragileEdges:d.filter(b=>b.fragile),testBoundaryViolations:r.testBoundaryViolations??[],coarseBoundaries:sU(e,s,r.isModuleHierarchyFile,n.requireResolvedBoundaries===!0,b=>n.boundaries.find(S=>S.name===b)?.subUnits??"directory"),coverage:{totalFiles:i.length,mappedFiles:o.size,unmappedFiles:a,ambiguousFiles:c},policyCoverage:{declaredRows:n.boundaries.length-C.length,totalBoundaries:n.boundaries.length,missingRows:C,requiresCompletePolicy:n.requireCompletePolicy===!0,requiresMinimalPolicy:n.requireMinimalPolicy===!0}}}function kr(e,t={}){let n=ae(e,t.scope,{scipEdges:"imports-only",sourceEdges:"imports-and-reexports"}),r=M(e,{includeIgnored:!1}).filter(o=>!t.scope||o.includes(t.scope)),i=new Set(r);return cR(n,r,e.config.architecture,{isModuleHierarchyFile:o=>tU(e,o),testBoundaryViolations:aR(e,e.config.architecture,o=>eU(e.config.architecture,o),o=>i.has(o))})}function eU(e,t){let n=(e?.boundaries??[]).filter(r=>r.paths.some(i=>Wn(i,t)));return n.length===1?n[0].name:null}function tU(e,t){let n=W(t);return n==="test"||n==="entry"?!0:n!=="barrel"?!1:Q(e,t).length===0}function Lc(e){let t=e.forbiddenEdges.map(r=>`${kt}forbidden-edge:${encodeURIComponent(r.from)}:${encodeURIComponent(r.to)}`);if(e.policyCoverage.requiresCompletePolicy)for(let r of e.policyCoverage.missingRows)t.push(`${kt}missing-policy-row:${encodeURIComponent(r)}`);if(e.policyCoverage.requiresMinimalPolicy)for(let r of e.staleAllowances)t.push(`${kt}stale-allowance:${encodeURIComponent(r.from)}:${encodeURIComponent(r.to)}`);for(let r of e.testBoundaryViolations)t.push(`${kt}test-boundary:${encodeURIComponent(r.testFile)}:${encodeURIComponent(r.importedBoundary)}`);for(let r of e.boundaryLimits)t.push(`${kt}boundary-limit:${r.kind}:${encodeURIComponent(r.boundary)}`);let n=new Map;for(let r of e.coarseBoundaries)r.violatesPolicy&&n.set(r.boundary,(n.get(r.boundary)??0)+1);for(let[r,i]of n){let o=`${kt}coarse-boundary:${encodeURIComponent(r)}`;t.push(o);for(let s=2;s<=i;s+=1)t.push(`${o}:component:${s}`)}for(let r of e.cycles)r.violatesPolicy&&t.push(`${kt}cycle:${r.boundaries.map(i=>encodeURIComponent(i)).sort().join("|")}`);return[...new Set(t)].sort()}function lR(e){return!!e&&(Object.keys(e.allowedDependencies??{}).length>0||e.requireCompletePolicy===!0||e.requireAcyclic===!0||e.requireResolvedBoundaries===!0||e.requireMinimalPolicy===!0||e.maxBoundaryFanOut!==void 0||e.maxBoundaryFiles!==void 0||e.boundaries.some(t=>t.maxFiles!==void 0)||(e.testPaths?.length??0)>0)}function nU(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 rU(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:iU(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 iU(e,t,n){return!e.allowedDependencies||!Object.hasOwn(e.allowedDependencies,t)?"undeclared":e.allowedDependencies[t].includes(n)?"allowed":"forbidden"}function oU(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 sU(e,t,n=lU,r=!1,i=()=>"directory"){let o=[];for(let[s,a]of t){let c=i(s)==="file"?p=>p:uU,l=[...a].filter(p=>!n(p));if(l.length<2)continue;let u=new Set(l),d=new Map,m=new Map;for(let p of l)m.set(c(p),new Set);for(let p of l)for(let g of e.get(p)??[]){if(!u.has(g))continue;let y=c(p),h=c(g);if(y===h)continue;let C=vi(y,h),b=d.get(C);b||(b={from:y,to:h,fileEdges:[]},d.set(C,b)),b.fileEdges.push({fromFile:p,toFile:g}),m.get(y).add(h)}let{components:f}=Xo(m);for(let p of f){if(p.length<2)continue;let g=new Set(p),y=[...d.values()].filter(C=>g.has(C.from)&&g.has(C.to)).map(C=>({from:C.from,to:C.to,fileEdgeCount:C.fileEdges.length,examples:C.fileEdges.slice(0,5)})).sort((C,b)=>C.from.localeCompare(b.from)||C.to.localeCompare(b.to)),h=Math.min(...y.map(C=>C.fileEdgeCount));o.push({boundary:s,violatesPolicy:r,subUnits:[...p].sort(),internalEdges:y,narrowestEdges:y.filter(C=>C.fileEdgeCount===h)})}}return o.sort((s,a)=>a.subUnits.length-s.subUnits.length||s.boundary.localeCompare(a.boundary))}function aU(e,t){let n=new Set(t.map(s=>vi(s.from,s.to))),r=e.allowedDependencies??{},i=new Set(e.boundaries.map(s=>s.name)),o=[];for(let[s,a]of Object.entries(r))if(i.has(s))for(let c of a)!i.has(c)||n.has(vi(s,c))||o.push({from:s,to:c});return o.sort((s,a)=>s.from.localeCompare(a.from)||s.to.localeCompare(a.to))}function cU(e,t,n){let r=[],i=new Map;for(let o of t)i.set(o.from,(i.get(o.from)??0)+1);for(let o of e.boundaries){if(e.maxBoundaryFanOut!==void 0){let a=i.get(o.name)??0;a>e.maxBoundaryFanOut&&r.push({boundary:o.name,kind:"fan-out",observed:a,limit:e.maxBoundaryFanOut})}let s=o.maxFiles??e.maxBoundaryFiles;if(s!==void 0){let a=n.get(o.name)?.size??0;a>s&&r.push({boundary:o.name,kind:"files",observed:a,limit:s})}}return r.sort((o,s)=>o.boundary.localeCompare(s.boundary)||o.kind.localeCompare(s.kind))}function lU(e){let t=W(e);return t==="test"||t==="entry"}function uU(e){let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)}function vi(e,t){return`${e}\0${t}`}function dU(e,t){return e.from.localeCompare(t.from)||e.to.localeCompare(t.to)}function mU(e,t={}){let{limit:n=20,scope:r,minFanIn:i=2,minFanOut:o=2,scanLimit:s}=t,a=new T(e);return le(a.productionCallableDefinitions({scope:r,requireCallableSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof s=="number"&&s>0}),s).map(u=>fU(e,u,t.semantic!==!1)).filter(u=>u.fanIn>=i&&u.fanOut>=o).sort((u,d)=>d.score-u.score||d.fanIn-u.fanIn).slice(0,n)}function fU(e,t,n){let r=[...new Set(Dt(e,t,{limit:500,semantic:n,semanticEvidence:U}).map(l=>l.file))].sort(),i=new Map;for(let l of ht(e,t,{limit:500,semantic:n,semanticEvidence:U})){if(l.file===t.relativePath)continue;let u=`${l.symbol}|${l.file}`;i.has(u)||i.set(u,{symbol:l.symbol,shortName:I(l.symbol),file:l.file})}let o=[...i.values()].sort((l,u)=>l.file.localeCompare(u.file)||l.symbol.localeCompare(u.symbol)),s=r.length,a=o.length,c=s*a;return{symbol:t.symbol,shortName:I(t.symbol),fanIn:s,fanOut:a,callerFiles:r,externalCallees:o,score:c,definedIn:t.relativePath,actionTier:"signal",riskKind:"coordination-hotspot",evidenceReasons:[`${s} incoming file(s) reference this symbol`,`${a} distinct cross-file callee symbol(s) are reached from it`,`centrality score is ${c} (fan-in * fan-out)`],recommendation:"Review ownership, API stability, and caller groups before changing this central symbol; do not refactor solely from graph centrality."}}function Qo(e,t={}){let{scope:n,minLoc:r=3,scanLimit:i}=t,o=new T(e),s=t.semantic!==!1,a=0,c=E("isolated.candidates",()=>{let v=le(o.productionCallableDefinitions({scope:n,minLoc:r,excludeEntrySurfaces:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0,includeSuppressed:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:typeof i=="number"&&i>0}),i).filter(R=>!Ri(e,R));return a=v.length,v},()=>({definitions:a})),l=0,u=E("isolated.strict-callees",()=>{let x=o.symbolsWithNonSelfCallees(c,{additive:!1,semantic:!1});return l=x.size,x},()=>({definitions:c.length,symbols:l})),d=c.filter(x=>!u.has(x.symbolId)),m=0,f=E("isolated.scip-callers",()=>{let x=o.crossFileCallerMap(d,{semantic:!1});return m=x.size,x},()=>({definitions:d.length,symbols:m})),p=new Set(f.keys());for(let x of o.frameworkReferencedSymbolIds(d))p.add(x);let g=d.filter(x=>!p.has(x.symbolId));if(s&&g.length>0){for(let x of $n(e,g).keys())p.add(x);for(let x of o.symbolsWithNonSelfCallees(g,{additive:!1,semantic:!0}))u.add(x);g=g.filter(x=>!p.has(x.symbolId)).filter(x=>!u.has(x.symbolId))}let y=0,h=E("isolated.source-fallback-callers",()=>{let x=o.sourceFallbackCallerFiles(g,{skipPath:v=>W(v)==="test"});return y=x.size,x},()=>({definitions:g.length,symbols:y}));for(let x of h.keys())p.add(x);let C=g.filter(x=>!p.has(x.symbolId)),b=0,S=E("isolated.additive-callees",()=>{let x=o.symbolsWithNonSelfCallees(C,{additive:!0,semantic:s});return b=x.size,x},()=>({definitions:C.length,symbols:b}));for(let x of S)u.add(x);return C.filter(x=>!u.has(x.symbolId)).sort((x,v)=>O(v)-O(x)||x.relativePath.localeCompare(v.relativePath)||x.startLine-v.startLine).map(x=>({symbol:x.symbol,shortName:I(x.symbol),relativePath:x.relativePath,startLine:x.startLine,endLine:x.endLine,loc:O(x)}))}import{SymbolInformation_Kind as Me}from"@c4312/scip";var uR=500;function pU(e){let t=parseInt(e,10);if(!isNaN(t))return t;let n=e.toLowerCase(),r=kC.get(n);if(r!==void 0)return r;for(let[i,o]of Ic)if(o.toLowerCase().includes(n))return i;return null}function gU(e,t,n={}){let{scope:r,limit:i=100}=n,o=pU(t);return o===null?[]:yU(e,r).map(a=>({row:a,resolvedKind:mR(a)})).filter(a=>a.resolvedKind===o).slice(0,i).map(({row:a,resolvedKind:c})=>({symbol:a.symbol,shortName:I(a.symbol),kind:c,kindName:zo(c),relativePath:a.relative_path,startLine:a.start_line,endLine:a.end_line}))}function hU(e,t={}){let n=bU(e,t.scope);for(let r of SU(e,t.scope)){let i=mR(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:zo(r),count:i}))}function yU(e,t){return De(e,{scope:t}).map(xU)}function bU(e,t){let n=new Map;for(let r of dR(M(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", "),o=e.all(`SELECT gs.kind AS kind, COUNT(*) AS count
|
|
714
|
+
FROM defn_enclosing_ranges der
|
|
715
|
+
JOIN global_symbols gs ON der.symbol_id = gs.id
|
|
716
|
+
JOIN documents d ON der.document_id = d.id
|
|
717
|
+
WHERE gs.kind IS NOT NULL
|
|
718
|
+
AND gs.kind != 0
|
|
719
|
+
AND gs.symbol NOT LIKE '%#'
|
|
720
|
+
AND d.relative_path IN (${i})
|
|
721
|
+
GROUP BY gs.kind`,...r);for(let s of o)n.set(s.kind,(n.get(s.kind)??0)+s.count)}return n}function SU(e,t){let n=[];for(let r of dR(M(e,{scope:t,includeIgnored:!1}))){let i=r.map(()=>"?").join(", ");n.push(...e.all(`SELECT gs.symbol,
|
|
722
|
+
gs.kind,
|
|
723
|
+
gs.documentation,
|
|
724
|
+
gs.enclosing_symbol,
|
|
725
|
+
d.relative_path,
|
|
726
|
+
der.start_line,
|
|
727
|
+
der.end_line
|
|
728
|
+
FROM defn_enclosing_ranges der
|
|
729
|
+
JOIN global_symbols gs ON der.symbol_id = gs.id
|
|
730
|
+
JOIN documents d ON der.document_id = d.id
|
|
731
|
+
WHERE (gs.kind IS NULL OR gs.kind = 0 OR gs.symbol LIKE '%#')
|
|
732
|
+
${e.symbolNoiseFor("gs")}
|
|
733
|
+
AND d.relative_path IN (${i})
|
|
734
|
+
ORDER BY d.relative_path, der.start_line, der.end_line, gs.symbol`,...r))}return n}function dR(e){let t=[];for(let n=0;n<e.length;n+=uR)t.push(e.slice(n,n+uR));return t}function xU(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 mR(e){return e.kind!==null&&e.kind!==0?CU(e.kind,e.symbol,e.documentation):RU(e.symbol,e.documentation,e.enclosing_symbol)}function CU(e,t,n){let r=(n??"").toLowerCase();if(pe(t)==="type"){if(r.includes("type "))return Me.TypeAlias;if(r.includes("interface "))return Me.Interface;if(r.includes("struct "))return Me.Struct;if(r.includes("trait "))return Me.Trait;if(r.includes("class "))return Me.Class}return e}function RU(e,t,n){let r=Re(e);if("kind"in r)return null;let i=r.descriptors,o=i[i.length-2]??null,s=pe(e),a=(t??"").toLowerCase();return s==="type"?a.includes("type ")?Me.TypeAlias:a.includes("interface ")?Me.Interface:a.includes("struct ")?Me.Struct:a.includes("trait ")?Me.Trait:a.includes("class ")?Me.Class:Me.Class:s==="method"?o?.suffix==="type"?Me.Method:Me.Function:s==="namespace"?Me.Module:s!=="term"?null:a.includes("async def ")||a.includes("def ")?Me.Function:(n?pe(n):o?.suffix??null)==="type"?Me.Field:Me.Variable}function vU(e,t={}){let{limit:n=10,scope:r,minDepth:i=3}=t,o=ae(e,r),{components:s,componentOf:a}=Xo(o),c=new Map;for(let g=0;g<s.length;g++)c.set(g,new Set);for(let[g,y]of o){let h=a.get(g);for(let C of y){let b=a.get(C);b!==h&&c.get(h).add(b)}}let l=new Array(s.length),u=new Array(s.length);for(let g=0;g<s.length;g++){let y=[],h=0;for(let C of c.get(g)){let b=u[C];b>h&&(h=b,y=l[C])}l[g]=[g,...y],u[g]=1+h}function d(g){return l[g]}let m=s.map(g=>[...g].sort()),f=new Set,p=[];for(let g=0;g<s.length;g++){let h=d(g).map(S=>m[S]),C=h.map(S=>S[0]);if(h.length<i)continue;let b=C.join(" ");f.has(b)||(f.add(b),p.push(IU(C,h)))}return p.sort((g,y)=>y.depth-g.depth),wU(p).slice(0,n)}function IU(e,t){let n=t.reduce((i,o)=>i+o.length,0),r=t.filter(i=>i.length>1).length;return{chain:e,components:t,depth:t.length,fileCount:n,actionTier:"signal",chainKind:"transitive-dependency-depth",evidenceReasons:[`${t.length} condensed dependency component(s) form the representative transitive path`,`${n} file(s) are represented; ${r} component(s) contain a dependency cycle`,"cycles count once toward depth and retain their full membership separately"],recommendation:"Review whether the chain crosses ownership or layer boundaries; shorten it only when the dependency direction is accidental."}}function wU(e){let t=[];for(let n of e)t.some(r=>EU(n.chain,r.chain))||t.push(n);return t}function EU(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 DU(e,t){let n=$(e,t);if(!n)return[];let r=e.get(`SELECT symbol, enclosing_symbol FROM global_symbols
|
|
735
|
+
WHERE id = ? LIMIT 1`,n.symbolId);if(!r)return[];let i=[{symbol:r.symbol,shortName:I(r.symbol),depth:0}],o=r.enclosing_symbol,s=1,a=new Set([r.symbol]);for(;o&&!a.has(o)&&s<20;){a.add(o);let d=e.get("SELECT symbol, enclosing_symbol FROM global_symbols WHERE symbol = ?",o);if(!d)break;i.push({symbol:d.symbol,shortName:I(d.symbol),depth:s}),o=d.enclosing_symbol,s++}if(i.length>1)return i;let c=Re(r.symbol);if("kind"in c)return i;let l=c.descriptors;if(l.length<=1)return i;let u=[i[0]];for(let d=l.length-2,m=1;d>=0;d--,m++){let p=l.slice(0,d+1).map(g=>g.suffix==="method"?`${g.name}()`:g.name.replace(/\.(ts|tsx|js|jsx|mjs|cjs|py|pyi|rs|java|scala|kt|kts|rb|go|cs|vb|dart|php|c|cc|cpp|cxx|h|hpp)$/,"")).join(":");u.push({symbol:p,shortName:p,depth:m})}return u}function Vm(e,t,n={}){let r=$(e,t);if(!r)return null;let i=n.semantic!==!1,o=Dt(e,r,{semantic:i,semanticEvidence:U}).filter(a=>oe(a.symbol)).slice(0,50),s=Ci(ht(e,r,{limit:50,additive:!0,callableOnly:!0,semantic:i,semanticEvidence:U}));return{symbol:r.symbol,shortName:I(r.symbol),callers:o.map(a=>({symbol:a.symbol,shortName:I(a.symbol),file:a.file})),callees:s.map(a=>({symbol:a.symbol,shortName:I(a.symbol),file:a.file}))}}function yt(e,t){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function Ae(e,t){let n=new Set;for(let r of e)t.has(r)||n.add(r);return n}function zn(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 fR(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 Wm(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 Ii(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 wi(e,t){let n=0;for(let r of e){let i=t.get(r)??0;n+=i*i}return Math.sqrt(n)}function pR(e,t,n,r={}){let i=0,o=0,s=0,a=r.medianIdf??Ii(n),c=[],l=[];for(let m of e){let f=n.get(m)??0;o+=f*f,t.has(m)&&(i+=f*f,f>=a?c.push(m):l.push(m))}if(c.length===0&&l.length===0)return{similarity:0,significantShared:[],trivialShared:[]};for(let m of t){let f=n.get(m)??0;s+=f*f}let u=Math.sqrt(o)*Math.sqrt(s),d=u>0?i/u:0;return c.sort((m,f)=>(n.get(f)??0)-(n.get(m)??0)),{similarity:d,significantShared:c,trivialShared:l}}function gR(e,t,n,r){let i=0,o=r.medianIdf??Ii(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 Mc(e,t,n={}){let{minSimilarity:r=.4,limit:i=20}=n,o=NU(e,t,{semantic:n.semantic!==!1});if(!o)return[];if(!oe(o.symbol))return[];if(o.callees.size===0)return hR(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"});let s=PU(e,o,r,{scanLimit:n.scanLimit,semantic:n.semantic!==!1});return s.length>0?s.slice(0,i):hR(e,t,{minSimilarity:r,limit:i,scanLimit:n.scanLimit,candidateMode:n.sourceCandidateMode??"full"})}function Ym(e,t,n,r={}){let i=$(e,t),o=$(e,n);if(!i||!o)return null;let s=Mc(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:I(i.symbol),file:i.relativePath,loc:a},symbolB:{symbol:o.symbol,shortName:I(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:kU(s)}}function kU(e){let t=e.similarityBasis==="source-tokens"?"source-token":"tracked callee";return e.sharedCallees.length===0?`No shared ${t} evidence survived similar's weighting. Inspect the source before attempting consolidation.`:e.uniqueToA.length===0&&e.uniqueToB.length===0?`The functions have identical ${t} evidence under similar's weighting. Verify signatures, guards, and return values before consolidating.`:e.uniqueToA.length===0?`A's ${t} evidence is a subset of B's. B may subsume part of A's structure, but verify signatures, guards, and non-call logic first.`:e.uniqueToB.length===0?`B's ${t} evidence is a subset of A's. A may subsume part of B's structure, but verify signatures, guards, and non-call logic first.`:e.uniqueToA.length<=2&&e.uniqueToB.length<=2?`Create a shared helper around the ${e.sharedCallees.length} shared ${t}(s). Pass the ${e.uniqueToA.length+e.uniqueToB.length} divergent point(s) as parameters or callbacks.`:`Extract the ${e.sharedCallees.length} shared ${t}(s) into a common helper. Keep each function's unique logic outside that helper (${e.uniqueToA.length} item(s) in A, ${e.uniqueToB.length} in B).`}function PU(e,t,n,r){let i=Ei(e).calleeIndex({minCallees:3,scanLimit:r.scanLimit,semantic:r.semantic}),o=GU(t,i.corpus),s=HU(o,i),a=FU(o,i),c=Ii(a),l=wi(o.callees,a),u=[];for(let d of s){if(d.callees.size<3)continue;let m=wi(d.callees,a),f=xR(o,d,a,{minSimilarity:n,requireSignificantShared:1,requireSharedCount:0,medianIdf:c,magnitudeA:l,magnitudeB:m});f&&u.push(f)}return u.sort((d,m)=>m.similarity-d.similarity),u}function FU(e,t){let n=new Map(t.docFreq);for(let r of e.callees)n.set(r,(n.get(r)??0)+1);return Wm(n,t.corpus.length+1)}function xR(e,t,n,r){let i=_U(e,t,n,r);if(!LU(i,r))return null;let{similarity:o,significantShared:s,trivialShared:a}=i,c=s.length>0?s:a,l=wR(c,"callees");return{symbolA:e.symbol,shortNameA:I(e.symbol),fileA:e.file,symbolB:t.symbol,shortNameB:I(t.symbol),fileB:t.file,similarity:o,similarityBasis:"callees",sharedCallees:c.map(I),uniqueToA:[...Ae(e.callees,t.callees)].map(I),uniqueToB:[...Ae(t.callees,e.callees)].map(I),...l}}function TU(e,t,n,r){let i=r.magnitudeA??wi(e.callees,n),o=r.magnitudeB??wi(t.callees,n),s=0,a=0,c=0,l=r.medianIdf??Ii(n);for(let m of e.callees){if(!t.callees.has(m))continue;let f=n.get(m)??0;s+=f*f,c+=1,f>=l&&(a+=1)}if(c===0)return!1;let u=i*o;return(u>0?s/u:0)<r.minSimilarity?!1:a>=r.requireSignificantShared||c>=r.requireSharedCount}function _U(e,t,n,r){return r.magnitudeA===void 0||r.magnitudeB===void 0?pR(e.callees,t.callees,n,{medianIdf:r.medianIdf}):gR(e.callees,t.callees,n,{medianIdf:r.medianIdf,magnitudeA:r.magnitudeA,magnitudeB:r.magnitudeB})}function LU(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 Zo(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=G(),u=0,d=0,m=0,f=0,p=0,g=0,y=0;return E("similar.all",()=>{let C=Ei(e).calleeIndex({minCallees:o,scope:i,scanLimit:a,semantic:c}),b=C.corpus;u=b.length;let S=t.focusFiles,x=[],v=0;return E("similar.all.pair-scan",()=>{for(let R=0;R<b.length;R+=1){let D=b[R],w=S?.has(D.file)??!1,k=C.weightedMagnitudes[R],L=new Set;for(let ne of D.callees){let ee=C.candidateIndexesByCallee.get(ne);if(ee)for(let _ of ee)_<=R||S&&!w&&!S.has(b[_].file)||L.add(_)}l&&(m+=L.size,L.size>0&&(d+=1));for(let ne of L){let ee=b[ne];if(s&&D.file===ee.file){l&&(p+=1);continue}if(CR(D,ee)){l&&(g+=1);continue}l&&(f+=1);let _=xR(D,ee,C.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:C.medianIdf,magnitudeA:k,magnitudeB:C.weightedMagnitudes[ne]});_&&(MU(x,_,r,v),l&&(y+=1),v+=1)}}},()=>({corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:f,crossFileSkips:p,signatureSkips:g,insertedResults:y,topResults:x.length})),E("similar.all.sort-project",()=>(x.sort((R,D)=>D.result.similarity-R.result.similarity||R.order-D.order),x.map(R=>R.result)),()=>({topResults:x.length}))},()=>({minSimilarity:n,limit:r,scope:i,minCallees:o,crossFileOnly:s,scanLimit:a,semantic:c,corpusSize:u,candidateSets:d,candidatePairs:m,comparedPairs:f,crossFileSkips:p,signatureSkips:g,insertedResults:y}))}function Xm(e,t={}){let{minSimilarity:n=.5,scope:r,minCallees:i=4,crossFileOnly:o=!1,scanLimit:s}=t,a=t.semantic!==!1,c=G(),l=0,u=0,d=0,m=0,f=0,p=0,g=0;return E("similar.all-count",()=>{let h=Ei(e).calleeIndex({minCallees:i,scope:r,scanLimit:s,semantic:a}),C=h.corpus;l=C.length;let b=t.focusFiles;return E("similar.all-count.pair-scan",()=>{for(let S=0;S<C.length;S+=1){let x=C[S],v=b?.has(x.file)??!1,R=h.weightedMagnitudes[S],D=new Set;for(let w of x.callees){let k=h.candidateIndexesByCallee.get(w);if(k)for(let L of k)L<=S||b&&!v&&!b.has(C[L].file)||D.add(L)}c&&(d+=D.size,D.size>0&&(u+=1));for(let w of D){let k=C[w];if(o&&x.file===k.file){c&&(f+=1);continue}if(CR(x,k)){c&&(p+=1);continue}c&&(m+=1),TU(x,k,h.idfWeights,{minSimilarity:n,requireSignificantShared:2,requireSharedCount:4,medianIdf:h.medianIdf,magnitudeA:R,magnitudeB:h.weightedMagnitudes[w]})&&(g+=1)}}},()=>({corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:f,signatureSkips:p,insertedResults:g})),g},()=>({minSimilarity:n,scope:r,minCallees:i,crossFileOnly:o,scanLimit:s,semantic:a,corpusSize:l,candidateSets:u,candidatePairs:d,comparedPairs:m,crossFileSkips:f,signatureSkips:p,insertedResults:g}))}function CR(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 RR=ce({kind:"source-fingerprints",invalidation:X("source-fingerprints"),serialize:uq,deserialize:lq});function MU(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 AU=["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 NU(e,t,n){let r=$(e,t);if(!r||!oe(r.symbol))return null;let i=new T(e),o=ht(e,r,{semantic:n.semantic,semanticEvidence:U});return{symbol:r.symbol,file:r.relativePath,callees:Ac(o.map(s=>s.symbol)),paramCount:i.callableSignature(r)?.paramCount??-1}}var OU=Z("callee-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),jU=Z("callee-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function vR(e,t){let{minCallees:n,scope:r,excludeSymbol:i,scanLimit:o}=t,s=t.semantic!==!1,a=OU.get(e,()=>new Map),c=`${n}|${r??""}|${o??""}|${s}`,l=!0,u=0,d=0;return E("similar.callee-fingerprints.resolve",()=>{let m=a.get(c);if(l=m!==void 0,m||(m=UU(e,{minCallees:n,scope:r,scanLimit:o,semantic:s}),a.set(c,m)),u=m.length,i===void 0)return m;let f=m.filter(p=>p.symbol!==i);return d=m.length-f.length,f},()=>({minCallees:n,scope:r,scanLimit:o,semantic:s,cacheHit:l,corpusSize:u,excludeSymbol:i!==void 0,excludedSymbols:d}))}function BU(e,t){let{minCallees:n,scope:r,scanLimit:i}=t,o=t.semantic!==!1,s=jU.get(e,()=>new Map),a=`${n}|${r??""}|${i??""}|${o}`,c=!0,l=0,u=0,d=0;return E("similar.callee-index.resolve",()=>{let m=s.get(a);return c=m!==void 0,m||(m=$U(vR(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 Ei(e){return{calleeCorpus:t=>vR(e,t),calleeIndex:t=>BU(e,t),sourceCorpus:(t={})=>FR(e,t),sourceIndex:(t={})=>SR(e,t),sourceCandidates:(t,n)=>(n.candidateMode??"full")==="target-pruned"?tq(e,t,{minSimilarity:n.minSimilarity,scanLimit:n.scanLimit}):eq(t,SR(e,{scanLimit:n.scanLimit}))}}function $U(e){let t=G(),n=0,r=E("similar.callee-index.doc-frequency",()=>{let m=new Map;for(let f of e)for(let p of f.callees)m.set(p,(m.get(p)??0)+1);return n=m.size,m},()=>({corpusSize:e.length,uniqueCallees:n})),i=Math.max(8,Math.ceil(Math.sqrt(e.length))),o=E("similar.callee-index.idf-weights",()=>Wm(r,e.length),()=>({corpusSize:e.length,uniqueCallees:r.size})),s=E("similar.callee-index.weighted-magnitudes",()=>e.map(m=>wi(m.callees,o)),()=>({corpusSize:e.length})),a=0,c=0,l=0,u=E("similar.callee-index.candidate-buckets",()=>{let m=new Map;for(let f=0;f<e.length;f+=1){let p=e[f];for(let g of p.callees){if((r.get(g)??0)>i){t&&(c+=1);continue}let y=m.get(g);y||(y=[],m.set(g,y)),y.push(f),t&&(a+=1)}}return t&&(l=m.size),m},()=>({corpusSize:e.length,buckets:l,candidateRefs:a,ubiquitousSkips:c,ubiquityThreshold:i})),d=E("similar.callee-index.median-idf",()=>Ii(o),()=>({uniqueCallees:o.size}));return{corpus:e,candidateIndexesByCallee:u,docFreq:r,idfWeights:o,weightedMagnitudes:s,medianIdf:d,ubiquityThreshold:i}}function HU(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 UU(e,t){let{minCallees:n,scope:r,scanLimit:i,semantic:o}=t,s=G(),a=new T(e),c=0,l=E("similar.callee-fingerprints.candidates",()=>{let g=le(a.productionCallableDefinitions({scope:r,minLoc:5,sortByLocDesc:typeof i=="number"&&i>0}),i);return c=g.length,g},()=>({scope:r,scanLimit:i,candidateCount:c})),u=0,d=E("similar.callee-fingerprints.callee-map",()=>{let g=a.calleeMap(l,{semantic:o});if(s)for(let y of g.values())u+=y.length;return g},()=>({candidateCount:c,semantic:o,calleeEdges:u})),m=0,f=0,p=0;return E("similar.callee-fingerprints.shape",()=>{let g=l.map(C=>({symbol:C.symbol,file:C.relativePath,callees:Ac((d.get(C.symbolId)??[]).map(b=>b.symbol)),paramCount:a.callableSignature(C)?.paramCount??-1})),y=qU(g);s&&(p=y.filter((C,b)=>C.callees.size!==g[b].callees.size).length);let h=y.filter(C=>C.callees.size>=n);return m=h.length,s&&(f=h.reduce((C,b)=>C+b.callees.size,0)),h},()=>({candidateCount:c,fingerprintCount:m,retainedCalleeCount:f,minCallees:n,siblingSaturatedFingerprints:p}))}var IR=5;function qU(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)>=IR);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 GU(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>=IR);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 Ac(e){return new Set([...e].filter(t=>!VU(t)))}function VU(e){return AU.some(t=>e.includes(t))}function hR(e,t,n){let r=JU(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 E("similar.source-shape",()=>{let m=Ei(e).sourceCandidates(r,{minSimilarity:i,scanLimit:n.scanLimit,candidateMode:s});a=m.length;for(let f of m){if(f.symbol===r.symbol||f.tokens.size<3)continue;c+=1;let p=yt(r.tokens,f.tokens);if(p.size<2){l+=1;continue}let g=new Set([...r.tokens,...f.tokens]),y=g.size>0?p.size/g.size:0;if(y<i){u+=1;continue}o.push({symbolA:r.symbol,shortNameA:I(r.symbol),fileA:r.file,symbolB:f.symbol,shortNameB:I(f.symbol),fileB:f.file,similarity:y,similarityBasis:"source-tokens",sharedCallees:[...p].sort(),uniqueToA:[...Ae(r.tokens,f.tokens)].sort(),uniqueToB:[...Ae(f.tokens,r.tokens)].sort(),...wR([...p],"source-tokens")})}return o.sort((f,p)=>p.similarity-f.similarity||f.shortNameB.localeCompare(p.shortNameB)),o.slice(0,n.limit)},()=>({symbol:r.symbol,file:r.file,targetTokens:r.tokens.size,candidateMode:s,candidates:a,comparedPairs:c,sharedSkips:l,similaritySkips:u,results:o.length}))}function wR(e,t){let n=e.flatMap(Km),r=e.flatMap(y=>yR(y,t)),i=zm(n,ER),o=zm(n,DR),s=zm(r,Jm),a=[...new Set(r.filter(bR))],c=e.filter(y=>{let h=yR(y,t);return h.some(C=>Jm.has(C))&&h.some(bR)}).length,l=[];i.length>0&&l.push(`access/query scaffolding: ${i.slice(0,5).join(", ")}`),o.length>0&&l.push(`framework/generic scaffolding: ${o.slice(0,5).join(", ")}`),s.length>0&&l.push(`domain behavior verbs: ${s.slice(0,5).join(", ")}`),s.length>0&&a.length>0&&l.push(`domain-specific terms: ${a.slice(0,5).join(", ")}`);let u=t==="source-tokens"&&n.length>0&&n.every(y=>kR.has(y));u&&l.push("shared source tokens are generic scaffolding");let d=s.length>0&&a.length>0,m=i.length+o.length>0,f=t==="callees"&&d&&e.length>=4&&a.length>=4&&c>=2,p=f?"domain-behavior":d?m?"mixed":"domain-behavior":i.length>0?"access-query-scaffolding":o.length>0||u?"framework-scaffolding":"structural-overlap";p==="structural-overlap"&&e.length>0&&l.push(`shared ${t} overlap has no recognized domain or scaffolding category`);let g=p==="domain-behavior"&&(e.length>=3||f)?"direct":"signal";return{evidenceClass:p,actionTier:g,evidenceClassReasons:l,recommendation:WU(p,g)}}function WU(e,t){return t==="direct"?"Shared domain behavior looks concrete; review for an extract/reuse opportunity.":e==="mixed"?"Shared evidence mixes domain behavior with scaffolding; review semantics before extracting anything.":e==="access-query-scaffolding"?"Shared evidence is mostly access/query scaffolding; compare product semantics before reusing code.":e==="structural-overlap"?"Shared structure has no domain or scaffolding classification; inspect names and behavior before reusing code.":"Shared evidence is mostly framework or generic scaffolding; treat as a contextual signal."}function zm(e,t){return[...new Set(e.filter(n=>t.has(n)))]}function Km(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1)}function yR(e,t){if(t==="source-tokens")return Km(e);let n=F(e);return Km(n.length>0?n:zU(e))}function zU(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 bR(e){return e.length>3&&!Jm.has(e)&&!ER.has(e)&&!DR.has(e)&&!kR.has(e)&&!KU.has(e)}var Jm=new Set(["archive","assign","book","cancel","create","delete","ensure","export","import","notify","persist","publish","restore","schedule","send","set","submit","sync","update","upload","validate","write"]),ER=new Set(["access","auth","authorize","cache","context","db","find","get","guard","list","permission","permissions","prisma","query","request","response","role","route","session","sql","where"]),DR=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"]),kR=new Set(["bytes","crypto","data","false","get","hex","id","key","map","name","num","random","result","secret","set","string","to","token","true","type","value"]),KU=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 JU(e,t){let n=$(e,t);if(!n||!oe(n.symbol))return null;let r=YU(e,n);return r?{symbol:n.symbol,file:n.relativePath,tokens:r}:null}function YU(e,t){let n=F(t.symbol),r=sq(e,t.relativePath,t.startLine,t.endLine,n),i=LR(r,n);return i.size>0?i:null}var XU=Z("source-fingerprint-corpus",{clearGroups:["whole-project","definition-catalog"]}),QU=Z("source-fingerprint-index",{clearGroups:["whole-project","definition-catalog"]});function PR(e){return`${e.scanLimit??""}`}function FR(e,t={}){let n=XU.get(e,()=>new Map),r=PR(t),i=n.get(r);return i||(i=oq(e,t),n.set(r,i)),i}function SR(e,t={}){let n=QU.get(e,()=>new Map),r=PR(t),i=n.get(r);return i||(i=ZU(FR(e,t)),n.set(r,i)),i}function ZU(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 eq(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 tq(e,t,n){let r=G(),i=new T(e),o=nq(t.tokens.size,n.minSimilarity),s=0,a=0,c=0,l=E("similar.source-shape.target-files",()=>{let p=[...t.tokens],g=[];for(let y of M(e,{includeIgnored:!1})){s+=1;let h=P(e,y);h&&(a+=1,rq(h,p,o)&&g.push(y))}return c=g.length,g},()=>({symbol:t.symbol,targetTokens:t.tokens.size,requiredSharedTokens:o,scannedFiles:s,readableFiles:a,candidateFiles:c})),u=0,d=E("similar.source-shape.target-definitions",()=>{let p=le(i.productionCallableDefinitions({files:l,sortByLocDesc:typeof n.scanLimit=="number"&&n.scanLimit>0}),n.scanLimit);return u=p.length,p},()=>({symbol:t.symbol,candidateFiles:c,scanLimit:n.scanLimit,definitionCount:u})),m=0;return E("similar.source-shape.target-fingerprints",()=>{let p=TR(e,d);return r&&(m=p.length),p},()=>({symbol:t.symbol,definitionCount:u,fingerprintCount:m})).filter(p=>p.symbol!==t.symbol)}function nq(e,t){return Math.max(2,Math.ceil(e*t))}function rq(e,t,n){if(t.length<n)return!1;let r=e.toLowerCase(),i=0;for(let o of t)if(iq(r,o)&&(i+=1,i>=n))return!0;return!1}function iq(e,t){return t==="num"?/\b\d+\b/.test(e):e.includes(t)}function oq(e,t={}){let n=new T(e),{scanLimit:r}=t,i=le(n.productionCallableDefinitions({sortByLocDesc:typeof r=="number"&&r>0}),r);return TR(e,i)}function TR(e,t){let n=new Map;for(let i of t){let o=n.get(i.relativePath)??[];o.push(i),n.set(i.relativePath,o)}let r=new Map;for(let[i,o]of n){let s=P(e,i);if(!s)continue;let a=me(e,i,s),c=cq(e,i,a),l=!1,u=null;for(let d of o){let m=aq(d),f=c.get(m),p=f?new Set(f.tokens):null;p||(u??=Ee(e,i),p=LR(_R(u,d.startLine,d.endLine,d.leaf),d.leaf),c.set(m,{key:m,symbol:d.symbol,startLine:d.startLine,endLine:d.endLine,leaf:d.leaf,tokens:[...p].sort()}),l=!0),p.size>0&&r.set(d.symbol,{symbol:d.symbol,file:d.relativePath,tokens:p})}l&&dq(e,i,a,c)}return t.map(i=>r.get(i.symbol)).filter(i=>!!i)}function sq(e,t,n,r,i){let o=Ee(e,t);return o.length===0?"":_R(o,n,r,i)}function _R(e,t,n,r){if(n>=t&&n-t<=12)return e.slice(t,n+1).join(`
|
|
736
|
+
`);let i=[new RegExp(`\\bdef\\s+${H(r)}\\b`),new RegExp(`\\bfun\\s+${H(r)}\\b`),new RegExp(`\\bfn\\s+${H(r)}\\b`),new RegExp(`\\bfunction\\s+${H(r)}\\b`),new RegExp(`\\b${H(r)}\\s*\\(`)],o=e.findIndex(s=>i.some(a=>a.test(s)));if(o>=0){let s=o;for(let a=o+1;a<e.length&&a<=o+8;a++){let c=e[a]??"";if(a>o&&fq(c)||(s=a,c.trim()===""&&a>o+1))break}return e.slice(o,s+1).join(`
|
|
737
|
+
`)}return e.slice(t,Math.min(e.length,t+8)).join(`
|
|
738
|
+
`)}function aq(e){return`${e.symbol}\0${e.startLine}\0${e.endLine}\0${e.leaf}`}function cq(e,t,n){return RR.read(e,t,n)??new Map}function lq(e){try{let t=JSON.parse(e);if(!Array.isArray(t.entries))return null;let n=new Map;for(let r of t.entries){if(!r||typeof r.key!="string"||typeof r.symbol!="string"||typeof r.startLine!="number"||typeof r.endLine!="number"||typeof r.leaf!="string"||!Array.isArray(r.tokens)||!r.tokens.every(i=>typeof i=="string"))return null;n.set(r.key,r)}return n}catch{return null}}function uq(e){let t={entries:[...e.values()].sort((n,r)=>n.key.localeCompare(r.key))};return JSON.stringify(t)}function dq(e,t,n,r){RR.write(e,t,n,new Map(r))}function LR(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=mq(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 mq(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 fq(e){return/^\s*(?:def|fun|fn|function|class|trait|module|object|enum|interface|public|private|protected)\b/.test(e)}function Gt(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 Vt(e){let t=MR(e.profile?.name),n=()=>{let r=[];t=MR(e.profile?.name,e);let i=(s,a)=>{let c=e.profiles[s],l=e.profiles[a];t.candidatePairs+=1,t.comparedPairs+=1;let u=e.compare(c,l);u&&r.push(u)};if(e.filePattern){let s=e.profiles.findIndex(a=>a.file.includes(e.filePattern));if(s>=0){let a=e.profiles[s];for(let c of pq(e,s)){let l=e.profiles[c];e.focusFiles&&!e.focusFiles.has(a.file)&&!e.focusFiles.has(l.file)||i(s,c)}}}else if(e.focusFiles?.size!==0){let s=typeof e.overrunFactor=="number"&&Number.isFinite(e.limit)?e.limit*e.overrunFactor:Number.POSITIVE_INFINITY;for(let a=0;a<e.profiles.length;a+=1){let c=e.profiles[a],l=e.focusFiles?.has(c.file)??!1;for(let u of gq(e,a))e.focusFiles&&!l&&!e.focusFiles.has(e.profiles[u].file)||i(a,u);if(r.length>s){t.overrunApplied=!0;break}}}r.sort(e.sort??((s,a)=>a.similarity-s.similarity)),t.matchedResults=r.length;let o=r.slice(0,e.limit);return t.emittedResults=o.length,e.onProfile?.({...t}),o};return e.profile?E(`pairwise-profile:${e.profile.name}`,n,()=>({...hq(e.profile?.metadata),...t})):n()}function pq(e,t){if(e.candidateIndex)return AR(e,t,-1);let n=[];for(let r=0;r<e.profiles.length;r+=1)r!==t&&n.push(r);return n}function gq(e,t){if(e.candidateIndex)return AR(e,t,t);let n=[];for(let r=t+1;r<e.profiles.length;r+=1)n.push(r);return n}function AR(e,t,n){let r=e.profiles[t],i=new Set;for(let o of e.candidateIndex?.candidatesFor(r,t,e.profiles)??[])o<=n||o!==t&&(o<0||o>=e.profiles.length||i.add(o));return[...i].sort((o,s)=>o-s)}function MR(e,t){return{pipeline:e,profileCount:t?.profiles.length??0,focusedProfileCount:t?.focusFiles?t.profiles.filter(n=>t.focusFiles.has(n.file)).length:0,candidatePairs:0,comparedPairs:0,matchedResults:0,emittedResults:0,candidateIndexApplied:t?.candidateIndex!==void 0,focusApplied:t?.focusFiles!==void 0,filePatternApplied:t?.filePattern!==void 0,overrunApplied:!1}}function hq(e){return typeof e=="function"?e():e??{}}function yq(e,t={}){let{minSimilarity:n=.5,limit:r=20,scope:i,filePattern:o}=t,s=t.minDeps??(o?1:3),{profiles:a,distinctiveDeps:c}=bq(e,{scope:i,minDeps:s}),l=Gt(a,u=>u.deps);return Vt({profiles:a,limit:r,filePattern:o,overrunFactor:5,candidateIndex:l,profile:{name:"similar-files"},compare:(u,d)=>xq(u,d,n,c)})}function bq(e,t){let{scope:n,minDeps:r}=t,i=ae(e,n),{universalDeps:o,distinctiveDeps:s}=Sq(i),a=[];for(let[c,l]of i)l.size>=r&&a.push({file:c,deps:new Set([...l].filter(u=>!o.has(u)))});return{profiles:a,distinctiveDeps:s}}function Sq(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 xq(e,t,n,r){let i=new Set;for(let l of e.deps)t.deps.has(l)&&i.add(l);if(i.size<3||e.deps.size<4||t.deps.size<4)return null;let o=0;for(let l of i)r.has(l)&&o++;if(o<2)return null;let s=zn(e.deps,t.deps);if(s<n)return null;let a=[];for(let l of e.deps)t.deps.has(l)||a.push(l);let c=[];for(let l of t.deps)e.deps.has(l)||c.push(l);return{fileA:e.file,fileB:t.file,similarity:s,sharedDeps:[...i],uniqueToA:a,uniqueToB:c}}function Kn(e){let t=[],n=[],r=[];for(let l of e.primitiveGroups)l.values.length!==0&&NR(l.bucket,n,r).push(`${l.reasonPrefix}: ${l.values.join(", ")}`);for(let l of e.nameGroups)Cq(l.names,l.label,e.genericWords,e.stripPrefixes??[],t,NR(l.fallbackBucket,n,r));let i=t.length>0,o=n.length>0,s=r.length>0,a=i?o||s?"mixed":"domain-behavior":s?"shared-abstraction":"generic-workflow-scaffolding";return{actionTier:a==="domain-behavior"||a==="mixed"?"signal":"support",evidenceClass:a,reasons:[...t,...r,...n].slice(0,6),recommendation:e.recommendation(a)}}function Nc(e,t){if(e.size===0||t.size===0)return 0;let i=yt(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(zn(e,t),i)}function Jn(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 Oc(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 J(e,t){return[...e].filter(n=>n.startsWith(t)).map(n=>n.slice(t.length)).sort()}function je(e){return[...e].sort()}function Cq(e,t,n,r,i,o){let s=[],a=[];for(let c of e)Rq(c,r).filter(u=>!n.has(u)).length>0?s.push(c):a.push(c);s.length&&i.push(`${t} has domain term(s): ${s.slice(0,6).join(", ")}`),a.length&&o.push(`${t} is generic workflow: ${a.slice(0,6).join(", ")}`)}function Rq(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 NR(e,t,n){return e==="generic"?t:n}function es(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=at(e).reactProfiles({scope:o,minJsxTokens:r,scanLimit:s}).filter(d=>d.kind==="component").map(d=>({file:d.file,component:d.name,tokens:d.jsxTokens,profile:d})),u=Gt(l,d=>d.tokens);return Vt({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-component-duplicates"},compare:(d,m)=>vq(d,m,n),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.componentA.localeCompare(m.componentA)||d.fileB.localeCompare(m.fileB)||d.componentB.localeCompare(m.componentB)})}function vq(e,t,n){let r=yt(e.tokens,t.tokens);if(r.size<6||!Iq(r))return null;let i=zn(e.tokens,t.tokens);if(i<n)return null;let o=J(r,"component:"),s=J(r,"native:"),a=J(r,"prop:"),c=J(r,"event:"),l=J(r,"binding:"),u=wq({sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:i,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:je(r),sharedComponents:o,sharedNativeTags:s,sharedProps:a,sharedEvents:c,sharedBindings:l,evidenceClass:u.evidenceClass,actionTier:u.actionTier,evidenceClassReasons:u.reasons,recommendation:u.recommendation,uniqueToA:je(Ae(e.tokens,t.tokens)).slice(0,25),uniqueToB:je(Ae(t.tokens,e.tokens)).slice(0,25),locA:e.profile.loc,locB:t.profile.loc}}function Iq(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 Jn([{name:"component",count:t},{name:"shape",count:n}],[{min:{component:1},reason:"shared custom component"},{min:{shape:4},reason:"shared JSX structure"}]).pass}function wq(e){return Kn({genericWords:Dq,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:Eq})}function Eq(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 Dq=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 ts(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=at(e).reactProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,component:d.name,tokens:d.behaviorTokens,profile:d})),u=Gt(l,d=>d.tokens);return Vt({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"react-hook-candidates"},compare:(d,m)=>kq(d,m,n,r),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.componentA.localeCompare(m.componentA)||d.fileB.localeCompare(m.fileB)||d.componentB.localeCompare(m.componentB)})}function kq(e,t,n,r){let i=yt(e.tokens,t.tokens);if(i.size<r||!Tq(i))return null;let o=Nc(e.tokens,t.tokens);if(o<n)return null;let s=J(i,"hook:"),a=J(i,"react-hook:"),c=J(i,"effect:"),l=J(i,"state:"),u=J(i,"request:"),d=J(i,"handler:"),m=J(i,"handler-verb:"),f=Pq({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m});return{fileA:e.file,componentA:e.component,fileB:t.file,componentB:t.component,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:je(i),sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m,evidenceClass:f.evidenceClass,actionTier:f.actionTier,evidenceClassReasons:f.reasons,recommendation:f.recommendation,uniqueToA:je(Ae(e.tokens,t.tokens)).slice(0,25),uniqueToB:je(Ae(t.tokens,e.tokens)).slice(0,25),reason:_q({sharedHooks:s,sharedReactHooks:a,sharedEffects:c,sharedState:l,sharedRequests:u,sharedHandlers:d,sharedHandlerVerbs:m}),locA:e.profile.loc,locB:t.profile.loc}}function Pq(e){return Kn({genericWords:Lq,stripPrefixes:Mq,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:Fq})}function Fq(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 Tq(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 Jn([{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 _q(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 Lq=new Set(["add","apply","async","callback","cancel","change","clear","close","create","data","delete","draft","edit","effect","error","fetch","filter","form","handle","has","is","item","items","load","loader","loading","memo","name","open","reducer","refresh","ref","remove","request","reset","resource","row","rows","save","saving","search","select","selected","state","store","submit","toggle","update","use","value"]),Mq=[/^use(?=[A-Z])/,/^handle(?=[A-Z])/,/^is(?=[A-Z])/,/^has(?=[A-Z])/];function Qm(e,t={}){let{minComponentLines:n=300,minFileLines:r=800,minJsxTokens:i=80,minBehaviorTokens:o=40,limit:s=20,scope:a,scanLimit:c,filePattern:l}=t;return at(e).reactProfiles({scope:a,scanLimit:c}).filter(d=>d.kind==="component").filter(d=>!l||d.file.includes(l)||d.name.includes(l)).map(d=>Aq(d,{minComponentLines:n,minFileLines:r,minJsxTokens:i,minBehaviorTokens:o})).filter(d=>d!==null).sort((d,m)=>m.componentLines-d.componentLines||m.fileLines-d.fileLines||d.file.localeCompare(m.file)).slice(0,s)}function Aq(e,t){let n=Math.max(80,Math.floor(t.minComponentLines/2)),r=Oc(e,Nq({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=Oq(e),c=jq(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:Bq(c,a),reasons:i,loc:e.loc}}function Nq(e){return[{axis:"component",value:t=>t.loc,qualifies:(t,n)=>n>=e.minComponentLines,reason:(t,n)=>`${n} component line(s)`},{axis:"file",value:t=>t.fileLines,qualifies:(t,n)=>n>=e.minFileLines&&t.loc>=e.substantialComponentLines,reason:(t,n)=>`${n} file line(s)`},{axis:"jsx-structure",value:t=>t.jsxTokens.size,weightedValue:(t,n)=>n*3,qualifies:(t,n)=>n>=e.minJsxTokens,reason:(t,n)=>`${n} JSX structure token(s)`},{axis:"hook-behavior",value:t=>t.behaviorTokens.size,weightedValue:(t,n)=>n*4,qualifies:(t,n)=>n>=e.minBehaviorTokens,reason:(t,n)=>`${n} behavior token(s)`}]}function Oq(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=>Hq.has(m))>=0,s=n.some(m=>$q.has(m));if(OR(r)||OR(e.name))return"component";let c=Uq.has(r.toLowerCase()),l=/(?:Page|Route|Screen)$/.test(e.name),u=o&&/View$/.test(e.name),d=!s&&r.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()===e.name.replace(/[^A-Za-z0-9]+/g,"").toLowerCase()&&/(?:Page|Route|Screen|View)$/.test(r);return c||l||u||d?"route-page":"component"}function OR(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.toLowerCase());return t.at(-1)&&jR.has(t.at(-1))?!0:[...jR].some(n=>e.endsWith(qq(n)))}function jq(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 Bq(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 $q=new Set(["component","components","panel","panels","partial","partials"]),jR=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"]),Hq=new Set(["landing","page","pages","route","routes","screen","screens","view","views"]),Uq=new Set(["page","route","screen"]);function qq(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ns(e,t={}){let{minSimilarity:n=.62,minTokens:r=8,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=Gq(e,{scope:o,minTokens:r,scanLimit:s}),u=Gt(l,d=>d.tokens);return Vt({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-component-duplicates"},compare:(d,m)=>Wq(d,m,n),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function Gq(e,t){return at(e).vueProfiles({scope:t.scope,minTemplateTokens:t.minTokens,scanLimit:t.scanLimit}).map(n=>({file:n.file,tokens:n.templateTokens,loc:Vq(n)}))}function Vq(e){return e.totalLines}function Wq(e,t,n){let r=yt(e.tokens,t.tokens);if(r.size<6||!zq(r))return null;let i=zn(e.tokens,t.tokens);if(i<n)return null;let o=J(r,"component:"),s=J(r,"prop:"),a=J(r,"event:"),c=J(r,"directive:"),l=J(r,"slot:"),u=J(r,"id:"),d=Kq({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:je(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:je(Ae(e.tokens,t.tokens)).slice(0,25),uniqueToB:je(Ae(t.tokens,e.tokens)).slice(0,25),locA:e.loc,locB:t.loc}}function zq(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 Jn([{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 Kq(e){return Kn({genericWords:Yq,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:Jq})}function Jq(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 Yq=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 rs(e,t={}){let{minSimilarity:n=.45,minSharedBehaviors:r=6,limit:i=20,scope:o,scanLimit:s,filePattern:a,focusFiles:c}=t,l=at(e).vueProfiles({scope:o,minBehaviorTokens:Math.max(3,r),scanLimit:s}).map(d=>({file:d.file,tokens:d.behaviorTokens,profile:d})),u=Gt(l,d=>d.tokens);return Vt({profiles:l,limit:i,filePattern:a,focusFiles:c,candidateIndex:u,profile:{name:"vue-composable-candidates"},compare:(d,m)=>Xq(d,m,n,r),sort:(d,m)=>m.similarity-d.similarity||d.fileA.localeCompare(m.fileA)||d.fileB.localeCompare(m.fileB)})}function Xq(e,t,n,r){let i=yt(e.tokens,t.tokens);if(i.size<r||!eG(i))return null;let o=Nc(e.tokens,t.tokens);if(o<n)return null;let s=J(i,"composable:"),a=J(i,"store:"),c=J(i,"reactivity:"),l=J(i,"lifecycle:"),u=J(i,"request:"),d=J(i,"function:"),m=J(i,"function-verb:"),f=J(i,"template-binding:"),p=J(i,"template-event:"),g=Qq({sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:p});return{fileA:e.file,fileB:t.file,similarity:o,tokenCountA:e.tokens.size,tokenCountB:t.tokens.size,sharedTokens:je(i),sharedComposables:s,sharedStores:a,sharedReactivity:c,sharedLifecycle:l,sharedRequests:u,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f,sharedTemplateEvents:p,evidenceClass:g.evidenceClass,actionTier:g.actionTier,evidenceClassReasons:g.reasons,recommendation:g.recommendation,uniqueToA:je(Ae(e.tokens,t.tokens)).slice(0,25),uniqueToB:je(Ae(t.tokens,e.tokens)).slice(0,25),reason:tG({sharedComposables:s,sharedStores:a,sharedRequests:u,sharedLifecycle:l,sharedFunctions:d,sharedFunctionVerbs:m,sharedBindings:f}),locA:e.profile.totalLines,locB:t.profile.totalLines}}function Qq(e){return Kn({genericWords:nG,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:Zq})}function Zq(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 eG(e){let t=0,n=0,r=0,i=0,o=0,s=0,a=0;for(let u of e)u.startsWith("composable:")?t+=1:u.startsWith("store:")?n+=1:u.startsWith("request:")?r+=1:u.startsWith("lifecycle:")?i+=1:u.startsWith("function:")?o+=1:u.startsWith("reactivity:")?s+=1:(u.startsWith("function-verb:")||u.startsWith("template-binding:")||u.startsWith("template-event:"))&&(a+=1);let c=t+n,l=c+r+i+o+a;return Jn([{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 tG(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 nG=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 Zm(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 at(e).vueProfiles({scope:a,scanLimit:c}).filter(d=>!l||d.file.includes(l)).map(d=>rG(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 rG(e,t){let n=Oc(e,iG(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=oG(e.file),a=sG(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:aG(a,s),reasons:r,loc:c}}function iG(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 oG(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).some(r=>cG.has(r))||/(?:view|page|route)\.vue$/i.test(e)||/(?:^|\/)(views|pages|routes)\//i.test(e)?"route-page":"component"}function sG(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 aG(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 cG=new Set(["landing","page","pages","route","routes","view","views"]);function lG(e,t={}){let{minSimilarity:n=.5,limit:r=15,scope:i,minChainLength:o=3,maxChainLength:s=8}=t,a=ae(e,i),c=yG(a,o,s);if(c.length===0)return[];let l=uG(c);return l.length<2?[]:hG(fG(l,n,r),r)}function uG(e){let t=dG(e),n=[];for(let r of e){let i=r.filter(o=>!t.has(o));i.length>=2&&n.push({original:r,filtered:i})}return n}function dG(e){let{nodeFreq:t,tailFreq:n}=mG(e),r=e.length*.9,i=e.length*.8,o=new Set;for(let[a,c]of t)c>r&&o.add(a);for(let[a,c]of n)c>i&&o.add(a);let s=["index.ts","index.js","cli.ts","main.ts","health.ts","health.js"];for(let a of t.keys()){let c=a.split("/").pop()??"";s.includes(c)&&o.add(a)}return o}function mG(e){let t=new Map,n=new Map;for(let r of e){let i=new Set;for(let o of r)i.has(o)||(t.set(o,(t.get(o)??0)+1),i.add(o));for(let o=Math.max(0,r.length-2);o<r.length;o++)n.set(r[o],(n.get(r[o])??0)+1)}return{nodeFreq:t,tailFreq:n}}function fG(e,t,n){let r=[];for(let i=0;i<e.length;i++){for(let o=i+1;o<e.length;o++){let s=pG(e[i],e[o],t);s&&r.push(s)}if(r.length>n*10)break}return r.sort((i,o)=>Math.abs(o.similarity-i.similarity)>.01?o.similarity-i.similarity:i.divergencePoints.length-o.divergencePoints.length),r}function pG(e,t,n){if(!gG(e.filtered,t.filtered))return null;let{distance:r,ops:i}=bG(e.filtered,t.filtered),o=Math.max(e.filtered.length,t.filtered.length);if(o===0)return null;let s=1-r/o;if(s<n||r===0)return null;let a=i.filter(l=>l.type==="substitute").map(l=>({index:l.indexA,nodeA:e.filtered[l.indexA],nodeB:t.filtered[l.indexB]}));return a.length===0||i.filter(l=>l.type==="match").length<2?null:{chainA:e.original,chainB:t.original,similarity:s,editDistance:r,divergencePoints:a,commonPrefix:SG(e.original,t.original),commonSuffix:xG(e.original,t.original)}}function gG(e,t){let n=new Set(e);return t.some(r=>n.has(r))}function hG(e,t){let n=[];for(let r of e)if(n.some(o=>BR(r.chainA,o.chainA)&&BR(r.chainB,o.chainB))||n.push(r),n.length>=t)break;return n}function yG(e,t,n){let r=[];for(let o of e.keys()){if(r.length>=500)break;$R(e,o,[o],new Set([o]),t,n,r,500)}return r}function $R(e,t,n,r,i,o,s,a){if(s.length>=a)return;if(n.length>=o){n.length>=i&&s.push([...n]);return}let c=e.get(t);if(!c||c.size===0){n.length>=i&&s.push([...n]);return}let l=!1;for(let u of c)if(!r.has(u)&&(r.add(u),n.push(u),$R(e,u,n,r,i,o,s,a),n.pop(),r.delete(u),l=!0,s.length>=a))return;!l&&n.length>=i&&s.push([...n])}function bG(e,t){let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array(r+1).fill(0));for(let c=0;c<=n;c++)i[c][0]=c;for(let c=0;c<=r;c++)i[0][c]=c;for(let c=1;c<=n;c++)for(let l=1;l<=r;l++)e[c-1]===t[l-1]?i[c][l]=i[c-1][l-1]:i[c][l]=1+Math.min(i[c-1][l],i[c][l-1],i[c-1][l-1]);let o=[],s=n,a=r;for(;s>0||a>0;)s>0&&a>0&&e[s-1]===t[a-1]?(o.unshift({type:"match",indexA:s-1,indexB:a-1}),s--,a--):s>0&&a>0&&i[s][a]===i[s-1][a-1]+1?(o.unshift({type:"substitute",indexA:s-1,indexB:a-1}),s--,a--):a>0&&i[s][a]===i[s][a-1]+1?(o.unshift({type:"insert",indexA:s,indexB:a-1}),a--):(o.unshift({type:"delete",indexA:s-1,indexB:a}),s--);return{distance:i[n][r],ops:o}}function SG(e,t){let n=[];for(let r=0;r<Math.min(e.length,t.length)&&e[r]===t[r];r++)n.push(e[r]);return n}function xG(e,t){let n=[],r=e.length-1,i=t.length-1;for(;r>=0&&i>=0&&e[r]===t[i];)n.unshift(e[r]),r--,i--;return n}function BR(e,t){if(e.length>t.length)return!1;let n=t.join("\u2192"),r=e.join("\u2192");return n.includes(r)}function bt(e){let t=CG(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=le(o,e.scanLimit);t={pipeline:e.profile?.name,loadedCandidates:r.length,filteredCandidates:i.length,scannedCandidates:s.length,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:s.length<i.length,resultLimitApplied:!1};let a=e.prepare?.(s)??void 0,c=[];for(let u of s){t.evaluatedCandidates+=1;let d=e.evaluate(u,a);d&&c.push(d)}t.matchedResults=c.length,e.orderResults&&c.sort(e.orderResults);let l=typeof e.limit=="number"?c.slice(0,e.limit):c;return t.emittedResults=l.length,t.resultLimitApplied=l.length<c.length,e.onProfile?.({...t}),l};return e.profile?E(`candidate-pipeline:${e.profile.name}`,n,()=>({...RG(e.profile?.metadata),...t})):n()}function CG(e){return{pipeline:e,loadedCandidates:0,filteredCandidates:0,scannedCandidates:0,evaluatedCandidates:0,matchedResults:0,emittedResults:0,scanLimitApplied:!1,resultLimitApplied:!1}}function RG(e){return typeof e=="function"?e():e??{}}function is(e,t={}){let{scope:n,minLoc:r=10,minCallees:i=6,limit:o=20,scanLimit:s}=t,a=new T(e);return bt({candidates:()=>a.productionCallableDefinitions({scope:n,minLoc:r,excludeTypesFiles:!0,requireFunctionLikeSymbol:!0,sortByLocDesc:!0}),scanLimit:s,profile:{name:"extract-candidates"},prepare:c=>a.calleeMap(c,{semantic:t.semantic!==!1}),evaluate:(c,l)=>vG(c,l.get(c.symbolId)??[],i),orderResults:(c,l)=>l.clusters.length-c.clusters.length||l.loc-c.loc,limit:o})}function vG(e,t,n){let r=new Set(t.map(l=>l.symbol));if(r.size<n)return null;let i=kG(r,t),o=PG(r,i);if(o.length<2)return null;let s=FG(o,i);if(s.length===0)return null;let a=I(e.symbol),c=IG(a,r.size,o.length,s);return{symbol:e.symbol,shortName:a,relativePath:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:O(e),totalCallees:r.size,extractionKind:c.extractionKind,actionTier:"signal",evidenceReasons:c.evidenceReasons,recommendation:c.recommendation,clusters:s}}function IG(e,t,n,r){let i=Math.max(...r.map(c=>c.callees.length)),o=Math.max(...r.map(c=>c.isolation)),s=[`${t} distinct callees across ${n} co-occurrence cluster(s)`,`${r.length} extractable cluster(s) passed size and isolation thresholds`,`largest extractable cluster has ${i} callees at ${Math.round(o*100)}% isolation`],a=wG(e,t,n);return a!==null?{extractionKind:"workflow-orchestration",evidenceReasons:[...s,a],recommendation:"Review the isolated helper group as a possible private or feature-local helper, but keep the orchestration sequence together when it preserves the workflow."}:i>=6?{extractionKind:"broad-helper-cluster",evidenceReasons:[...s,"one isolated helper group is broad enough to deserve a named review"],recommendation:"Review whether the broad helper cluster has a stable concept name before extracting it; avoid creating a bag-of-helpers abstraction."}:{extractionKind:"cohesive-helper-cluster",evidenceReasons:s,recommendation:"Review the isolated callee group as a possible same-file or feature-local helper; extract only if the new name preserves the current behavior."}}function wG(e,t,n){if(t>=10)return`callee breadth suggests orchestration: ${t} callees`;if(n>=4)return`multiple disconnected callee groups suggest orchestration: ${n} groups`;let r=EG(e);return DG.has(r)?`caller verb suggests orchestration: ${r}`:null}function EG(e){return e.split(":").pop()?.replace(/\(\)$/,"").replace(/[^A-Za-z0-9_]/g,"").replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\s-]+/).filter(Boolean)[0]?.toLowerCase()??""}var DG=new Set(["apply","build","check","collect","create","diff","execute","find","handle","load","prepare","process","render","resolve","run","select","sync","update","validate","verify","write"]);function kG(e,t){let n=new Map;for(let i of e)n.set(i,new Set);let r=new Map;for(let i of t){let o=r.get(i.chunkId);o||(o=new Set,r.set(i.chunkId,o)),o.add(i.symbol)}for(let i of r.values()){let o=[...i];for(let s=0;s<o.length;s++)for(let a=s+1;a<o.length;a++)n.get(o[s]).add(o[a]),n.get(o[a]).add(o[s])}return n}function PG(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let o=new Set,s=[i];for(;s.length>0;){let a=s.pop();if(!n.has(a)){n.add(a),o.add(a);for(let c of t.get(a)??[])n.has(c)||s.push(c)}}r.push(o)}return r}function FG(e,t){return e.filter(n=>n.size>=3).map(n=>TG(n,e,t)).filter(n=>n.isolation>.5).sort((n,r)=>r.isolation-n.isolation)}function TG(e,t,n){let r=new Set;for(let a of t)if(a!==e)for(let c of a)r.add(c);let i=0;for(let a of e)for(let c of n.get(a)??[])r.has(c)&&i++;let o=e.size*r.size,s=o>0?1-i/o:1;return{callees:[...e].map(I),isolation:s}}import{posix as Di}from"path";import{spawnSync as _G}from"child_process";import{createHash as LG}from"crypto";import{existsSync as MG}from"fs";import{dirname as HR,join as AG}from"path";import{fileURLToPath as NG}from"url";var GR=B("definition-consumer-file-usage",{clearGroups:["whole-project","source-file"]}),UR=ce({kind:"consumer-file-usage",invalidation:X("consumer-file-usage"),serialize:WG,deserialize:zG});function gn(e,t){return{forDefinitions(n,r){return OG(e,t,n,r)}}}function hn(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 Bc(e,t,n){return WR(e,t,n).partition}function OG(e,t,n,r){let i=VR(n.length),o=G()?Ne(e):null,s=o?jG(n,r,o):void 0,a=s?{workIdentity:s,workOutcome:"computed"}:{};return E("consumer-evidence.product",()=>{let c=E("consumer-evidence.provenance",()=>BG(e,t,n,r),()=>({...a,definitions:n.length,semantic:r.semantic,sourceFallback:r.sourceFallback!==!1})),l=new Map;i={...i,...c.counters};let u=$G(n,c.sources);return E("consumer-evidence.classify",()=>{let d=HG(e,n,c.sources,u);for(let m of n){let f=d.get(m.symbolId)??qG();i.realFiles+=f.partition.realConsumers.length,i.reexportOnlyFiles+=f.partition.barrelConsumers,i.importOnlyFiles+=f.partition.importOnlyConsumers,l.set(m.symbolId,{definition:m,files:f.files,...f.partition})}},()=>({...a,...u,realFiles:i.realFiles,reexportOnlyFiles:i.reexportOnlyFiles,importOnlyFiles:i.importOnlyFiles})),l},()=>({...a,...i}))}function jG(e,t,n){let r=LG("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 VR(e){return{definitions:e,indexedFiles:0,semanticFiles:0,fallbackFiles:0,totalFiles:0,realFiles:0,reexportOnlyFiles:0,importOnlyFiles:0}}function BG(e,t,n,r){let i=VR(n.length),o=new Map;return ef(o,i,"indexed",t.crossFileCallerMap(n,{semantic:!1})),r.semantic&&ef(o,i,"semantic",$n(e,n)),r.sourceFallback!==!1&&ef(o,i,"source-fallback",t.sourceFallbackCallerFiles(n)),i.totalFiles=[...o.values()].reduce((s,a)=>s+a.size,0),{sources:o,counters:i}}function $G(e,t){return{definitions:e.length,consumerFiles:[...t.values()].reduce((n,r)=>n+r.size,0),nativeAttempted:!1,nativeUsed:!1,nativeReason:"not-attempted"}}function ef(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 HG(e,t,n,r){let i=eV(e,t,n,r);return i||UG(e,t,n)}function UG(e,t,n){let r=new Map;for(let i of t){let o=n.get(i.symbolId)??new Map;r.set(i.symbolId,WR(e,i,[...o.keys()],o))}return r}function WR(e,t,n,r=new Map){let i=[],o=0,s=0,a=F(t.symbol),c=[];for(let l of n){let u;KG(e,l,t.relativePath,a)?(o++,u="reexport-only"):tf(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 qG(){return{partition:{realConsumers:[],barrelConsumers:0,importOnlyConsumers:0},files:[]}}function tf(e,t,n){if(!n)return!1;let r=N(t);if(!r)return!1;let i=GR.get(e,t,()=>zR(e,t,r));return i.importedLeaves.has(n)&&!i.usedLeaves.has(n)}function zR(e,t,n){let r=mt(e).forFile(t,{text:!0,ast:!0}),i=r.text;if(!i)return VG();let o=me(e,t,i),s=UR.read(e,t,o);if(s)return s;let a=GG(r.ast,n);return UR.write(e,t,o,a),a}function GG(e,t){let n=new Set,r=new Set;if(!e)return{importedLeaves:n,usedLeaves:r};let i=t==="rust"?new Set(["use_declaration"]):t==="python"?new Set(["import_statement","import_from_statement"]):new Set(["import_statement"]),o=(s,a)=>{let c=a||i.has(s.type);(s.type==="identifier"||s.type==="type_identifier"||s.type==="property_identifier"||s.type==="field_identifier")&&(c?n.add(s.text):r.add(s.text));for(let l of s.children)o(l,c)};return o(e.rootNode,!1),{importedLeaves:n,usedLeaves:r}}function VG(){return{importedLeaves:new Set,usedLeaves:new Set}}function WG(e){return JSON.stringify({importedLeaves:[...e.importedLeaves],usedLeaves:[...e.usedLeaves]})}function zG(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 KG(e,t,n,r){if(!r)return!1;let i=mt(e).forFile(t,{lines:!0,reexports:!0}),o=i.lines??[];if(o.length===0)return!1;let s=i.reexports??[];return KR(o,s,r)}function KR(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 JG="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY",YG="SCIP_QUERY_NATIVE_KERNELS_BIN",XG="SCIP_QUERY_NATIVE_CONSUMER_CLASSIFY_MIN_FILES",qR=1e3,QG=5e3,ZG=64*1024*1024,jc;function eV(e,t,n,r){let i=process.env[JG]?.toLowerCase();if(i!=="1"&&i!=="true")return r.nativeReason=i==="0"||i==="false"?"disabled":"opt-in-required",null;if(r.consumerFiles<aV())return r.nativeReason="below-threshold",null;let o=cV();if(!o)return r.nativeReason="binary-missing",null;r.nativeAttempted=!0;let s=tV(e,t,n),a=_G(o,["consumer-classify"],{input:JSON.stringify(s),encoding:"utf8",timeout:QG,maxBuffer:ZG});if(a.status!==0||a.error)return r.nativeReason=a.error?`spawn-error:${a.error.message}`:`exit-${a.status??"null"}`,null;try{let c=JSON.parse(a.stdout),l=rV(c,t);return l?(r.nativeUsed=!0,r.nativeReason="used",l):(r.nativeReason="invalid-response",null)}catch{return r.nativeReason="invalid-json",null}}function tV(e,t,n){let r=new Map,i=[];for(let a of t){let c=F(a.symbol),u=[...(n.get(a.symbolId)??new Map).entries()].map(([d,m])=>{let f=r.get(d)??new Set;return c&&f.add(c),r.set(d,f),{file:d,sources:[...m]}});i.push({symbol_id:a.symbolId,leaf:c,consumer_files:u})}let o={},s={};for(let[a,c]of r){let l=N(a);if(l){let d=GR.get(e,a,()=>zR(e,a,l));o[a]={imported_leaves:[...d.importedLeaves],used_leaves:[...d.usedLeaves]}}let u=nV(e,a,c);u.length>0&&(s[a]=u)}return{definitions:i,file_usages:o,reexport_only_leaves:s}}function nV(e,t,n){if(n.size===0)return[];let r=mt(e).forFile(t,{lines:!0,reexports:!0}),i=r.lines??[],o=r.reexports??[];return i.length===0||o.length===0?[]:[...n].filter(s=>KR(i,o,s))}function rV(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=iV(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 iV(e){if(!e||typeof e!="object")return null;let t=e;if(typeof t.symbol_id!="number"||!Array.isArray(t.real_consumers)||typeof t.barrel_consumers!="number"||typeof t.import_only_consumers!="number"||!Array.isArray(t.files)||!t.real_consumers.every(r=>typeof r=="string"))return null;let n=[];for(let r of t.files){if(!r||typeof r!="object")return null;let i=r;if(typeof i.file!="string"||!Array.isArray(i.sources)||!i.sources.every(oV)||!sV(i.classification))return null;n.push({file:i.file,sources:i.sources,classification:i.classification})}return{symbol_id:t.symbol_id,real_consumers:t.real_consumers,barrel_consumers:t.barrel_consumers,import_only_consumers:t.import_only_consumers,files:n}}function oV(e){return e==="indexed"||e==="semantic"||e==="source-fallback"}function sV(e){return e==="real"||e==="reexport-only"||e==="import-only"}function aV(){let e=process.env[XG];if(!e)return qR;let t=Number(e);return Number.isFinite(t)&&t>=0?t:qR}function cV(){if(jc!==void 0)return jc;let e=process.env[YG],t=process.platform==="win32"?"scip-query-kernels.exe":"scip-query-kernels";return jc=[...e?[e]:[],...lV().map(r=>AG(r,"target","release",t))].find(r=>MG(r))??null,jc}function lV(){let e=new Set,t=HR(NG(import.meta.url));for(let n=0;n<5;n++)e.add(t),t=HR(t);return[...e]}var uV=20,dV=1,mV=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"]]),fV=new Set(["components","contracts","hooks","lib","services","shared","stores","utils"]),pV=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 gV(e,t={}){let n=of(t.limit,uV),r=of(t.minConsumers,dV),i=new T(e),o=i.fileDependencyGraph(t.scope),s=AV(M(e,{includeIgnored:!1})),a=jV(e.config.locality?.architecturalBoundarySegments,t.architecturalBoundarySegments);return(t.target?hV(e,i,t.target):yV(e,t.scope,t.scanLimit)).map(u=>bV(e,i,o,u,t,s,a)).filter(u=>u.consumerFiles.length>=r||t.target).sort(MV).slice(0,n)}function hV(e,t,n){let r=CV(e,n);if(r)return[ZR(r)];let i=$(e,n);if(!i)return[];let o=t.definitionsForFile(i.relativePath).find(s=>s.symbolId===i.symbolId);return o?[RV(o)]:[{unit:{kind:"symbol",file:i.relativePath,shortName:I(i.symbol),symbol:i.symbol,startLine:i.startLine,endLine:i.endLine}}]}function yV(e,t,n){let r=M(e,{scope:t,includeIgnored:!1}),i=of(n,r.length);return r.slice(0,i).map(o=>ZR(o))}function bV(e,t,n,r,i,o,s){let a=r.definition?SV(e,t,r.definition,i.semantic):xV(n,r.unit.file),c=r.definition?a.length>0?"exact":"none":a.length>0?"file-level":"none",l=r.unit.file,u=Pt(Di.dirname(l)),d=IV(a),m=vV(u),f=af([...JR(u),...d?JR(d):[]]),p=wV(r.unit,u,d,a),g=EV(p,r.unit,u,d,a,o,s),y=TV(r.unit,c,d,a,u,g.whyNoSuggestedHome),h=_V(r.unit,u,d,a,g.suggestedHome,g.whyNoSuggestedHome);return{actionTier:"signal",sourceUnit:r.unit,candidatePath:l,currentDirectory:u,directoryAncestry:m,consumerFiles:a,consumerCoverage:c,nearestCommonOwner:d,boundaryMarkers:f,recommendedTier:p,suggestedHome:g.suggestedHome,destinationConfidence:g.confidence,whyNoSuggestedHome:g.whyNoSuggestedHome,counterevidence:y,reasons:h,recommendation:LV(p,g.suggestedHome,c)}}function SV(e,t,n,r){let i=hn(gn(e,t).forDefinitions([n],{semantic:r!==!1,sourceFallback:!0}));return iv(i.get(n.symbolId)??[])}function xV(e,t){let n=[];for(let[r,i]of e.entries())r!==t&&i.has(t)&&n.push(r);return iv(n)}function CV(e,t){let n=En(t),r=M(e,{includeIgnored:!1}),i=r.find(s=>s===n);if(i)return i;let o=r.find(s=>s.endsWith(`/${n}`));return o||(r.find(s=>s.includes(n))??null)}function RV(e){return{definition:e,unit:{kind:"symbol",file:e.relativePath,shortName:I(e.symbol),symbol:e.symbol,startLine:e.startLine,endLine:e.endLine}}}function ZR(e){return{unit:{kind:"file",file:e,shortName:Di.basename(e)}}}function vV(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:sf(i)})}return t}function JR(e){return e==="."?[]:ev(e).map(({marker:t,prefix:n})=>`${t}: ${n}`)}function sf(e){return af(ev(e).map(({marker:t})=>t))}function ev(e){let t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length;r+=1){let i=mV.get(t[r]);i&&n.push({marker:i,prefix:t.slice(0,r+1).join("/")})}return n}function IV(e){if(e.length===0)return null;let t=e.map(r=>Pt(Di.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 wV(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":XR(n,"package")?"package-level-shared":XR(n,"app")?"app-level-shared":QR(n,["feature","domain","module"])||QR(t,["feature","domain","module"])?"feature-local-shared":"sibling-folder":"no-exact-consumers"}function EV(e,t,n,r,i,o,s){let a=DV(e,r);if(a)return Yn(a);let c=NV(t.file),l=kV(e,n,c,i,s);if(l)return l;let u=r;if(Pt(n)===Pt(u))return Yn(`${n} is already the nearest common owner for its consumers.`);let d=PV(u,n,c,s);return d||FV(u,n,c,o,s)}function DV(e,t){return t?e==="no-exact-consumers"||e==="repository-level-review"?"The inferred owner is too broad or unsupported for an exact destination.":null:"No consumer owner could be inferred from the current index."}function kV(e,t,n,r,i){if(e==="same-file"){let o=r[0]??null;return o?nf(o):Yn("No same-file consumer path was available.")}if(e==="sibling-folder"&&r.length===1){let o=Pt(Di.dirname(r[0])),s=rv(t,n,o,i);return s?Yn(s):nf(o)}return null}function PV(e,t,n,r){return $V(e)?tv(e,t,n,r,`Nearest shared owner ${e} is outside source root ${n}.`):null}function FV(e,t,n,r,i){if(e===".")return Yn("The nearest common owner is the repository root.");let o=`${e}/shared`,s=tv(o,t,n,i,`Proposed home ${o} is outside source root ${n}.`);return s.confidence==="withheld"||r.has(o)?s:Yn(`${o} does not exist in the indexed project.`)}function tv(e,t,n,r,i){if(!nv(e,n))return Yn(i);let o=rv(t,n,e,r);return o?Yn(o):nf(e)}function nf(e){return{suggestedHome:e,confidence:"exact",whyNoSuggestedHome:null}}function Yn(e){return{suggestedHome:null,confidence:"withheld",whyNoSuggestedHome:e}}function TV(e,t,n,r,i,o){let s=["Report-only signal; review ownership before moving files."];return t==="none"&&s.push("No consumers were found in the current index."),t==="file-level"&&s.push("File-level import evidence can hide which exported unit is actually used."),(n==="."||n==="src")&&s.push("Nearest common owner is broad, so this is not enough evidence for automatic placement."),r.length===1&&s.push("Only one consumer was found; inlining or same-folder placement may be better than shared extraction."),e.kind==="file"&&s.push("File targets describe module locality, not symbol-level usage."),n&&i.startsWith(`${n}/`)&&s.push("Candidate already lives under the nearest common owner."),o&&s.push(`No exact suggested home: ${o}`),s}function _V(e,t,n,r,i,o){let s=[];return s.push(`${e.shortName} currently lives in ${t}.`),n?s.push(`${r.length} consumer file(s) share ${n} as their nearest common owner.`):s.push("No consumer owner could be inferred from the current index."),i?s.push(`Suggested home is ${i}.`):o&&s.push(`No exact suggested home: ${o}`),s}function LV(e,t,n){return e==="no-exact-consumers"?"Review references before moving; no consumers were found.":e==="repository-level-review"?"Keep this as a broad locality signal; the inferred owner is too general for automatic relocation.":t?`Review whether ${n==="exact"?"symbol usage":"module import"} supports moving or extracting toward ${t}.`:"Review ownership manually before changing structure."}function MV(e,t){return YR(t)-YR(e)||e.candidatePath.localeCompare(t.candidatePath)}function YR(e){let t=e.consumerFiles.length*10;return e.consumerCoverage==="exact"&&(t+=5),e.suggestedHome&&(t+=3),e.recommendedTier==="repository-level-review"&&(t*=.1),e.recommendedTier==="no-exact-consumers"&&(t*=.05),t}function AV(e){let t=new Set(["."]);for(let n of e){let r=Pt(Di.dirname(n));for(;!t.has(r)&&(t.add(r),r!==".");)r=Pt(Di.dirname(r))}return t}function NV(e){let t=rf(e),n=t.indexOf("src");return n>=0?t.slice(0,n+1).join("/"):t.length<=1?".":t[0]}function nv(e,t){let n=Pt(e),r=Pt(t);return r==="."||n===r||n.startsWith(`${r}/`)}function OV(e,t,n){let r=rf(e),i=rf(t);return(nv(e,t)?r.slice(i.length):r).some(s=>n.has(s.toLowerCase()))}function rv(e,t,n,r){return Pt(e)===Pt(n)||!OV(e,t,r)?null:`${e} is a named architectural boundary; an exact move to ${n} needs human design.`}function jV(...e){let t=new Set(pV);for(let n of e)for(let r of n??[]){let i=BV(r);i&&t.add(i)}return t}function BV(e){let t=e.trim().toLowerCase();return t===""?null:t}function XR(e,t){return sf(e).includes(t)}function QR(e,t){let n=sf(e);return t.some(r=>n.includes(r))}function $V(e){let t=e.split("/").filter(Boolean),n=t[t.length-1];return n?fV.has(n):!1}function Pt(e){let t=En(e);return t===""?".":t}function rf(e){let t=En(e);return t==="."?[]:t.split("/").filter(Boolean)}function of(e,t){return!Number.isFinite(e)||e===void 0||e<1?t:Math.floor(e)}function iv(e){return af([...e]).sort((t,n)=>t.localeCompare(n))}function af(e){return[...new Set(e)]}function cf(e,t,n={}){let{maxDepth:r=5,scope:i}=n,o=$(e,t);if(!o)return[];let s=[],a=new Set([o.symbolId]),c=new Set,l=[o];for(let u=1;u<=r&&l.length!==0;u++){let d=[],m=_m(e,l,{limit:500,semanticEvidence:U});for(let f of l)for(let p of HV(e,f,i,m.get(f.symbolId)??[])){let g=`${p.file}|${p.shortName}`;if(p.symbolId!==null){if(a.has(p.symbolId))continue;a.add(p.symbolId)}else if(c.has(g))continue;c.add(g),s.push({symbol:p.symbol,shortName:p.shortName,file:p.file,depth:u}),p.symbolId!==null&&p.symbolMatch&&d.push(p.symbolMatch)}l=d}return s.sort((u,d)=>u.depth-d.depth||u.file.localeCompare(d.file)),s}function HV(e,t,n,r){let i=r.filter(u=>!e.isIgnored(u.file)).filter(u=>!n||u.file.includes(n)),o=new Set(i.map(u=>u.file)),s=[];for(let u of UV(e,t,n)){if(o.has(u))continue;let d=Q(e,u),m=d.length>0?At(d,d[0].startLine):null;s.push({symbol:m?.symbol??u,file:u})}let a=[...i,...s],c=[],l=new Set;for(let u of a){let d=no(e,u.symbol);if(!d){let f=`${u.file}|${u.symbol}`;if(l.has(f))continue;l.add(f),c.push({symbolId:null,symbol:u.symbol,shortName:I(u.symbol),file:u.file,symbolMatch:null});continue}if(d.symbolId===t.symbolId||e.isIgnored(d.relativePath)||!qV(d))continue;let m=`${d.symbolId}|${d.relativePath}`;l.has(m)||(l.add(m),c.push({symbolId:d.symbolId,symbol:d.symbol,shortName:I(d.symbol),file:d.relativePath,symbolMatch:d}))}return c}function UV(e,t,n){let r=n?"AND consumer_d.relative_path LIKE ?":"",i=[t.symbolId,t.documentId];return n&&i.push(`%${n}%`),new Set(e.all(`SELECT DISTINCT consumer_d.relative_path
|
|
739
|
+
FROM mentions m
|
|
740
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
741
|
+
JOIN documents consumer_d ON consumer_d.id = c.document_id
|
|
742
|
+
WHERE m.symbol_id = ?
|
|
743
|
+
AND m.role != 1
|
|
744
|
+
AND c.document_id != ?
|
|
745
|
+
${e.pathExclusionsFor("consumer_d")}
|
|
746
|
+
${r}`,...i).map(o=>o.relative_path).filter(o=>!e.isIgnored(o)))}function qV(e){if(e.symbol.startsWith("scip-clojure ")||N(e.relativePath)==="clojure")return!0;let t=pe(e.symbol);return t==="method"||t==="type"||e.symbol.endsWith("().")}function lf(e,t,n={}){let r=Ge(e,t);if(!r)return null;let i=GV(e,r);if(!i||e.isIgnored(i.relative_path))return null;let o=[],s=0,a=VV(e,i.relative_path),c=n.semantic===!1?new Map:$n(e,a);for(let l of a){let u=WV(e,i,l,c.get(l.symbolId)??new Set);s+=u,o.push({symbol:l.symbol,shortName:I(l.symbol),startLine:l.startLine,endLine:l.endLine,externalConsumers:u,riskLevel:zV(u)})}return{file:i.relative_path,symbols:o,totalExternalConsumers:s}}function GV(e,t){return e.get(`SELECT id, relative_path FROM documents
|
|
747
|
+
WHERE relative_path = ?
|
|
748
|
+
${e.pathExclusionsFor("documents")}
|
|
749
|
+
LIMIT 1`,t)??null}function VV(e,t){return new T(e).definitionsForFile(t).sort((n,r)=>n.startLine-r.startLine||n.endLine-r.endLine)}function WV(e,t,n,r){let i=e.all(`SELECT DISTINCT consumer_d.relative_path
|
|
750
|
+
FROM mentions m
|
|
751
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
752
|
+
JOIN documents consumer_d ON consumer_d.id = c.document_id
|
|
753
|
+
WHERE m.symbol_id = ?
|
|
754
|
+
AND m.role != 1
|
|
755
|
+
AND c.document_id != ?`,n.symbolId,t.id);return new Set([...i.map(o=>o.relative_path),...[...r].filter(o=>o!==t.relative_path)]).size}function zV(e){return e>10?"high":e>0?"medium":"low"}function KV(e,t={}){let{scope:n,minLoc:r=1,maxDepth:i=5,scanLimit:o}=t,s=new T(e),a=JV(e,n,r,o),c=new uf;for(let g of a)c.add(g);let l=[],u=[];a.length>0&&l.push(ov(e,0,a,c));let d=a.map(g=>g.definition).filter(g=>g!==null),m=new Set(a.map(g=>g.symbol));for(let g=1;g<=i&&d.length>0;g++){let y=s.calleeMap(d,{semantic:!1}),h=new Set;for(let b of d)for(let S of y.get(b.symbolId)??[])m.has(S.symbol)||h.add(S.symbol);let C=[];for(let b of h){m.add(b);let S=sv(e,b);if(!S||e.isIgnored(S.relativePath)||Le(e,S.relativePath)||ge(e,S.symbol,S.relativePath)||s.fileKind(S.relativePath)==="test"||s.hasSuppressionComment(S))continue;let x=XV(e,S,c);x.removable?C.push(YV(S,"cascade")):x.blockingFiles.length>0&&u.push({shortName:I(S.symbol),file:S.relativePath,blockingFiles:x.blockingFiles.slice(0,3)})}if(C.length===0)break;for(let b of C)c.add(b);l.push(ov(e,g,C,c)),d=C.map(b=>b.definition).filter(b=>b!==null)}let f=l.reduce((g,y)=>g+y.loc,0),p=l.reduce((g,y)=>g+y.entries.length,0);return{batches:l,totalSymbols:p,totalLoc:f,blocked:u}}function JV(e,t,n,r){let i=Dr(e,{scope:t,minLoc:n,skipBarrels:!0,deadCodeOnly:!0,scanLimit:r,semantic:!1}),o=[];for(let s of i.symbols)s.kind==="dead-code"&&(Le(e,s.relativePath)||ge(e,s.symbol,s.relativePath)||o.push({symbol:s.symbol,shortName:s.shortName,file:s.relativePath,startLine:s.startLine,endLine:s.endLine,loc:s.loc,evidence:"graph-fact",definition:sv(e,s.symbol)}));return o}function YV(e,t){return{symbol:e.symbol,shortName:I(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:e.endLine-e.startLine+1,evidence:t,definition:e}}function sv(e,t){let n=e.get(`SELECT d.relative_path
|
|
756
|
+
FROM global_symbols gs
|
|
757
|
+
JOIN defn_enclosing_ranges der ON der.symbol_id = gs.id
|
|
758
|
+
JOIN documents d ON d.id = der.document_id
|
|
759
|
+
WHERE gs.symbol = ?
|
|
760
|
+
LIMIT 1`,t);return n?Q(e,n.relative_path).find(r=>r.symbol===t)??null:null}function XV(e,t,n){let r=oo(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 ov(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=Q(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 uf=class{ranges=new Map;add(t){let n=this.ranges.get(t.file)??[];n.push({start:t.startLine,end:t.endLine}),this.ranges.set(t.file,n)}contains(t,n){let r=this.ranges.get(t);return r?r.some(i=>n>=i.start&&n<=i.end):!1}};import{createHash as LJ}from"crypto";import{existsSync as rl}from"fs";import{execFileSync as QV}from"child_process";var dv=2e3,$c=50,ZV=64,eW=8,tW=3,nW=2160*60*60,rW=/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i,iW=3,oW=/#\d+|\b[A-Z][A-Z0-9]+-\d+\b/g,sW=/^([a-z][a-z0-9-]+)(?:\([^)]+\))?!?:/i;function aW(e){let t=Z(e,{clearGroups:["whole-project"]});return(n,r,i)=>{let o=i??df(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 Hc(e){let t=Z(e,{clearGroups:["whole-project"]});return(n,r,i,o)=>{let s=o??df(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 cW=Hc("git-commit-history");function Xe(e,t={}){let n=t.historyMode??"bounded",r=t.head;return{capability:i=>lW(e,i,r),commitHistory:()=>os(e,n,r),fileChurn:()=>mW(e,n,r),changeAmplification:()=>fW(e,n,r),trackedFiles:()=>gW(e,r),fileAddRecords:()=>yW(e,n,r),coChangePairs:(i={})=>IW(e,i,n,r),coChangePairsForFiles:(i,o={})=>fv(e,i,o,n,r),directionalCoChangePairsForFiles:(i,o={})=>wW(e,i,o,n,r)}}function os(e,t="bounded",n){return cW(e,ki(t),(r,i)=>uW(r,i,t),n)}function lW(e,t,n){let r=n??df(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 df(e){try{return Wt(e,["rev-parse","HEAD"]).trim()||null}catch{return null}}function Wt(e,t){return QV("git",["-C",e,...t],{encoding:"utf-8",maxBuffer:64*1024*1024,stdio:["ignore","pipe","ignore"],timeout:3e4,killSignal:"SIGKILL"})}function uW(e,t,n){let r;try{r=Wt(e,["log","--no-merges","--name-only",...Uc(n),"--pretty=format:%x01%H%x00%ct%x00%s"])}catch{return null}return{head:t,...gf(r,$c)}}function dW(e){return rW.test(e.subject)}function mW(e,t,n){let r=os(e,t,n);if(!r)return null;let i=new Map;for(let o of r.commits){let s=dW(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 fW(e,t,n){let r=os(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:av(i,.5),p90FilesPerCommit:av(i,.9),commitsAnalyzed:i.length}}function av(e,t){let n=Math.min(e.length-1,Math.floor(e.length*t));return e[n]}var pW=aW("git-tracked-files");function gW(e,t){return pW(e,n=>{try{let r=Wt(n,["ls-files"]);return new Set(r.split(`
|
|
761
|
+
`).map(i=>i.trim()).filter(i=>i!==""))}catch{return null}},t)}var hW=Hc("git-file-adds"),cv="__git__/file-adds",lv=ce({kind:"git-file-adds",invalidation:X("git-file-adds"),serialize:SW,deserialize:xW});function mf(e){return Xe(e).fileAddRecords()}function yW(e,t,n){let r=ki(t);return hW(e,r,(i,o)=>bW(e,i,o,t),n)}function bW(e,t,n,r){let i=lv.read(e,uv(r),n);if(i)return i;let o=CW(t,r);return o&&lv.write(e,uv(r),n,o),o}function SW(e){return JSON.stringify([...e.entries()])}function xW(e){if(!e)return null;try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=new Map;for(let r of t){if(!Array.isArray(r)||r.length!==2||typeof r[0]!="string")return null;let i=r[1];if(!i||typeof i.commitsAgo!="number"||!Number.isFinite(i.commitsAgo)||typeof i.addedAt!="number"||!Number.isFinite(i.addedAt))return null;n.set(r[0],{commitsAgo:i.commitsAgo,addedAt:i.addedAt})}return n}catch{return null}}function CW(e,t){let n;try{n=Wt(e,["log","--no-merges","--find-renames","--name-status",...Uc(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(`
|
|
762
|
+
`),c=a>=0?s.slice(0,a):s,[,l]=c.split("\0"),u=Number(l)||0;if(!(a<0))for(let d of s.slice(a+1).split(`
|
|
763
|
+
`)){let m=RW(d);if(!m)continue;if(m.status==="R"&&m.from&&m.to){let p=i.get(m.to)??new Set([m.to]);i.set(m.from,p);continue}if(m.status!=="A"||!m.to)continue;let f={commitsAgo:o,addedAt:u};r.set(m.to,f);for(let p of i.get(m.to)??[])r.set(p,f)}}return r}function RW(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 mv=Hc("git-co-change-pairs"),vW=Hc("git-directional-co-change-pairs");function IW(e,t,n,r){let i=`all\0${ki(n)}\0${ff(t)}`,o=mv(e,i,()=>{let s=os(e,n,r);return s?pf(s,t):null},r);return o&&[...o]}function fv(e,t,n,r,i){if(t.size===0)return[];let o=`files\0${ki(r)}\0${pv(t)}\0${ff(n)}`,s=mv(e,o,()=>{let a=os(e,r,i);return a?pf(a,n,t):null},i);return s&&[...s]}function wW(e,t,n,r,i){if(t.size===0)return[];let o=n.maxFilesPerCommit??$c;if(t.size>ZV)return fv(e,t,n,r,i);let s=`directional\0${ki(r)}\0${pv(t)}\0${ff({...n,maxFilesPerCommit:o})}`,a=vW(e,s,(c,l)=>{let u=EW(c,l,t,o,r);return u?pf(u,n,t):null},i);return a&&[...a]}function ff(e){let t=e.minTogether??4,n=e.minConfidence??.6,r=e.maxFilesPerCommit??$c;return`${t}\0${n}\0${r}`}function pv(e){return[...e].sort().join("\0")}function pf(e,t,n){let{minTogether:r=4,minConfidence:i=.6,maxFilesPerCommit:o=$c}=t,s=new Map,a=new Map,c=e.newestAnalyzedAt??0;for(let d of e.commits){let m=[...new Set(d.files)].sort();if(m.length>o)continue;e.newestAnalyzedAt===void 0&&d.timestamp>c&&(c=d.timestamp);let f=PW(m),p=n===void 0||m.some(g=>n.has(g));for(let g of m)s.set(g,(s.get(g)??0)+1);if(p)for(let g=0;g<m.length;g++)for(let y=g+1;y<m.length;y++){if(n&&!n.has(m[g])&&!n.has(m[y]))continue;let h=`${m[g]}\0${m[y]}`,C=a.get(h)??{together:0,focusedTogether:0,broadTogether:0,lastTogetherAt:0,timestamps:[],subjects:[]};C.together+=1,f?C.broadTogether+=1:C.focusedTogether+=1,d.timestamp>C.lastTogetherAt&&(C.lastTogetherAt=d.timestamp),C.timestamps.push(d.timestamp),C.subjects.push(d.subject),a.set(h,C)}}let l=[],u=c-nW;for(let[d,m]of a){let f=m.together;if(f<r)continue;let[p,g]=d.split("\0"),y=s.get(p)??f,h=s.get(g)??f,C=Math.max(f/y,f/h);if(C<i)continue;let b=m.broadTogether/f,S=m.timestamps.filter(x=>x>=u).length;l.push({fileA:p,fileB:g,together:f,confidence:C,changesA:y,changesB:h,focusedTogether:m.focusedTogether,broadTogether:m.broadTogether,broadCommitRatio:b,lastTogetherAt:m.lastTogetherAt,recentTogether:S,commitScope:TW(m.broadTogether,f),recency:S>0?"recent":"stale",subjectContext:_W(m.subjects)})}return l.sort((d,m)=>m.together-d.together||m.confidence-d.confidence||d.fileA.localeCompare(m.fileA)),l}function EW(e,t,n,r,i){let o;try{o=DW(e,i)}catch{return null}if(o.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:0};let s;try{s=Wt(e,["log","--no-merges","--format=%H",...Uc(i),"--",...[...n].sort()])}catch{return null}let a=new Set(o.map(m=>m.hash)),c=s.split(`
|
|
764
|
+
`).map(m=>m.trim()).filter(m=>m!==""&&a.has(m)),l=kW(e,o,r);if(c.length===0)return{head:t,commits:[],skippedBulkCommits:0,newestAnalyzedAt:l};let u;try{u=Wt(e,["show","--no-walk=unsorted","--name-only","--pretty=format:%x01%H%x00%ct%x00%s",...c])}catch{return null}let d=gf(u,r);return{head:t,...d,newestAnalyzedAt:l}}function DW(e,t){return Wt(e,["log","--no-merges","--format=%H%x00%ct",...Uc(t)]).split(`
|
|
765
|
+
`).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 Uc(e){return e==="full"?[]:["-n",String(gv())]}function gv(){return _n(process.env.SCIP_QUERY_GIT_HISTORY_MAX_COMMITS)??dv}function ki(e){return e==="full"?"full":`bounded:${gv()}`}function uv(e){let t=ki(e);return t===`bounded:${dv}`?cv:`${cv}:${t}`}function kW(e,t,n){for(let i=0;i<t.length;i+=20){let o=t.slice(i,i+20),s;try{s=Wt(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=gf(s,n);if(a.commits.length>0)return a.commits[0].timestamp}return 0}function gf(e,t){let n=[],r=0;for(let i of e.split("")){if(i.trim()==="")continue;let o=i.indexOf(`
|
|
766
|
+
`),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(`
|
|
767
|
+
`).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 PW(e){return e.length>=eW?!0:FW(e).size>=tW}function FW(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 TW(e,t){return e===0?"focused":e/t>=.5?"broad-sweep":"mixed"}function _W(e){let t=new Set,n=[],r=[];for(let i of e){!r.includes(i)&&r.length<iW&&r.push(i);for(let o of LW(i))t.add(o);for(let o of i.match(oW)??[])n.includes(o)||n.push(o)}return{subjectLabels:[...t].sort(),issueRefs:n,sampleSubjects:r,externalIssueLabelStatus:"unavailable"}}function LW(e){let t=new Set,n=sW.exec(e)?.[1]?.toLowerCase();return n&&t.add(MW(n)),/\b(?:feat|feature)\b/i.test(e)&&t.add("feature"),/\b(?:fix(?:es|ed)?|bug|regression|hotfix)\b/i.test(e)&&t.add("fix"),/\b(?:docs?|documentation|guide|readme)\b/i.test(e)&&t.add("docs"),/\brefactor(?:ing|ed)?\b/i.test(e)&&t.add("refactor"),/\btests?\b/i.test(e)&&t.add("test"),/\b(?:release|version|v\d+\.\d+)\b/i.test(e)&&t.add("release"),/\bchore\b/i.test(e)&&t.add("chore"),/\bbuild\b/i.test(e)&&t.add("build"),/\bci\b/i.test(e)&&t.add("ci"),/\bperf(?:ormance)?\b/i.test(e)&&t.add("perf"),[...t]}function MW(e){return e==="feat"?"feature":e}import{existsSync as AW}from"fs";import{join as NW}from"path";function yf(e){return hf.test(e)}var hf=/(?:^|\/)(?: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 ss(e,t,n={}){let{minTogether:r=4,minConfidence:i=.6,limit:o=30,maxFilesPerCommit:s=20}=n,a=Xe(e,{historyMode:n.historyMode,...n.head?{head:n.head}:{}}),c=a.commitHistory(),l=t!==void 0,u=a.coChangePairs({minTogether:l?Math.min(r,2):r,minConfidence:l?0:i,maxFilesPerCommit:s});if(!c||!u)return{available:!1,commitsAnalyzed:0,findings:[]};let d=typeof n.scanLimit=="number"?u.slice(0,n.scanLimit):u,m=ae(e),f=xv(e),p=xf(e,m,f),g=n.includeLinked===!0||l,y=[];for(let h of d){if(hf.test(h.fileA)||hf.test(h.fileB)||!hv(e,h.fileA)||!hv(e,h.fileB)||l&&!h.fileA.includes(t)&&!h.fileB.includes(t)||!l&&(W(h.fileA)==="test"||W(h.fileB)==="test"||$W(h.fileA,h.fileB)||jW(h.fileA,h.fileB)))continue;let C=p(h.fileA,h.fileB);if(!g&&C)continue;let b=bf(h.fileA,h.fileB),S=Sf(h,b,C);if(y.push({...h,structurallyLinked:C,partnerClass:b.partnerClass,partnerClassReasons:b.reasons,...S?{declaredCouplingSuggestion:S}:{}}),y.length>=o)break}return{available:!0,commitsAnalyzed:c.commits.length,findings:y}}function hv(e,t){return AW(NW(e.config.projectRoot,t))}function bf(e,t){let n=bv(e),r=bv(t),i=[],o=c=>{i.includes(c)||i.push(c)},s=(c,l)=>n.tags.has(c)&&r.tags.has(l)||n.tags.has(l)&&r.tags.has(c);if(s("doc","code"))return o("one side is documentation and the other is executable source"),{partnerClass:"doc-code",reasons:i};if(n.tags.has("test")||r.tags.has("test"))return o("one side is classified as a test file"),{partnerClass:"test-code",reasons:i};if(s("schema","script"))return o("schema or contract file changes with a script or generated-code path"),{partnerClass:"schema-script",reasons:i};if(s("model","view"))return o("model or state path changes with a view or component path"),{partnerClass:"model-view",reasons:i};if(s("config","code"))return o("configuration file changes with executable source"),{partnerClass:"config-code",reasons:i};let a=XW(n.tokens,r.tokens).filter(c=>!JW.has(c));return Sv(e,t)||a.length>=2?(o(Sv(e,t)?"both files live in the same directory":`files share feature tokens: ${a.slice(0,4).join(", ")}`),{partnerClass:"same-feature",reasons:i}):(o("no specific relationship pattern matched"),{partnerClass:"unknown",reasons:i})}function Sf(e,t,n){if(n||e.together<4||e.confidence<.75||e.commitScope==="broad-sweep"||e.recency==="stale"||!KW.has(t.partnerClass))return;let r=[e.fileA,e.fileB].sort();return{name:`co-change ${t.partnerClass}: ${QW(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 xf(e,t=ae(e),n=xv(e)){return(r,i)=>HW(t,n,r,i)}var OW=/(?:^|\/)(?:locales|i18n)\//i;function yv(e){return OW.test(e)}function jW(e,t){return yv(e)&&yv(t)?!0:BW(e,t)}function BW(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 $W(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 xv(e){return(e.config.declaredCouplings??[]).filter(t=>Array.isArray(t.files)&&t.files.length>=2).map(t=>new Set(t.files))}function HW(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 UW=/(?:^|\/)(?:readme|docs?|guides?|adr|architecture|design)(?:\/|$)|\.(?:md|mdx|rst|adoc|txt)$/i,qW=/(?:^|\/)(?:\.[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,GW=/(?:^|\/)(?:schemas?|contracts?|migrations?|models?|types?)(?:\/|$)|(?:^|\/)[^/]*(?:schema|contract|migration|model|types?)[^/]*|(?:\.schema)?\.(?:graphql|gql|proto|prisma)$/i,VW=/(?:^|\/)(?:scripts?|bin|tools?|tasks?|generators?|codegen|migrations?|seeds?)(?:\/|$)|(?:^|\/)[^/]*(?:generate|codegen|migrate|seed|script)[^/]*\.[cm]?[jt]s$/i,WW=/(?:^|\/)(?:models?|entities|domain|state|stores?|reducers?)(?:\/|$)|(?:^|\/)[^/]*(?:model|entity|state|store|reducer|viewmodel)[^/]*\.[^.]+$/i,zW=/(?:^|\/)(?:views?|pages?|components?|screens?|routes?|templates?)(?:\/|$)|(?:^|\/)[^/]*(?:view|page|component|screen|template)[^/]*\.[^.]+$|\.(?:vue|svelte|tsx|jsx)$/i,KW=new Set(["doc-code","config-code","schema-script","model-view","test-code"]),JW=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 bv(e){let t=e.replace(/\\/g,"/"),n=new Set;return UW.test(t)&&n.add("doc"),qW.test(t)&&n.add("config"),GW.test(t)&&n.add("schema"),VW.test(t)&&n.add("script"),WW.test(t)&&n.add("model"),zW.test(t)&&n.add("view"),W(t)==="test"&&n.add("test"),!n.has("doc")&&!n.has("config")&&n.add("code"),{tags:n,tokens:YW(t)}}function Sv(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 YW(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 XW(e,t){let n=new Set(t);return[...new Set(e.filter(r=>n.has(r)))].sort()}function QW(e){return e.map(t=>t.split("/").pop()?.replace(/\.[^.]+$/,"")||t).join(" + ")}import{execFileSync as Pr}from"child_process";import{existsSync as ZW,readFileSync as ez}from"fs";import{basename as Cv}from"path";function qc(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 as="Unable to compute git diff.";function Pi(e,t={}){let n=t.plan??Xn(e,t);return n.note?tz(n.note,n.changedFileLines):n.changedFiles.length===0?nz(n.changedFileLines):Gc(n.changedFiles,[wv(e,n.changedFiles,n.changedFiles,n.changedRanges)])}function Xn(e,t={}){let{base:n="HEAD"}=t;try{let r=rz(e.config.projectRoot,n),i=r.changedFileLines,o=lz(e,i),s=uz(e,r.changedRanges);return{changedFileLines:i,changedFiles:o,changedRanges:s,renamedFiles:sz(e.config.projectRoot,n,o,r),note:i.length===0?"No changed files found.":void 0}}catch{return{changedFileLines:[],changedFiles:[],changedRanges:[],renamedFiles:[],note:as}}}function wv(e,t,n,r=[]){let i=new T(e),o=new Set(n),s=qc(r),a=[],c=new Map,l=t.flatMap(S=>i.definitionsForFile(S)).filter(Iz),u=l.filter(S=>mz(S,s)),d=pz(e,l,u,s),m=yz([...u,...d.definitions]).sort((S,x)=>S.relativePath.localeCompare(x.relativePath)||S.startLine-x.startLine),f=m.map(S=>S.symbolId),p=Cz(e,f),g=Rz(e,f,n),y=m.filter(S=>(p.get(S.symbolId)??0)===0),h=Iv(()=>$n(e,y)),C=y.filter(S=>(h.get(S.symbolId)?.size??0)===0),b=Iv(()=>Ko(e,C));for(let S of m)xz(e,S,o,a,c,h.get(S.symbolId)??new Set,b.get(S.symbolId)??new Set,p.get(S.symbolId)??0,g.get(S.symbolId)??new Set);return{changedSymbols:a,consumerEntries:[...c.entries()].map(([S,x])=>({file:S,symbols:[...x].sort()})),attributionNotes:d.notes}}function Gc(e,t){let n=new Map,r=t.flatMap(s=>s.changedSymbols),i=t.flatMap(s=>s.attributionNotes??[]);for(let s of t)for(let a of s.consumerEntries){let c=n.get(a.file);c||(c=new Set,n.set(a.file,c));for(let l of a.symbols)c.add(l)}let o=vz(n);return{changedFiles:[...e],changedSymbols:r,affectedConsumers:o,attributionNotes:i,summary:{totalChangedFiles:e.length,totalChangedSymbols:r.length,totalAffectedFiles:o.length}}}function tz(e,t=[]){return{changedFiles:t,changedSymbols:[],affectedConsumers:[],attributionNotes:[],summary:{totalChangedFiles:t.length,totalChangedSymbols:0,totalAffectedFiles:0,note:e}}}function nz(e){return{changedFiles:e,changedSymbols:[],affectedConsumers:[],attributionNotes:[],summary:{totalChangedFiles:e.length,totalChangedSymbols:0,totalAffectedFiles:0,note:"Changed files are not present in the current SCIP index."}}}function rz(e,t){let n=Pr("git",["diff","--name-status","--find-renames",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:67108864}),r=Pr("git",["diff","--name-status","--find-renames","--cached",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),i=Pr("git",["ls-files","--others","--exclude-standard"],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),o=Pr("git",["diff","--unified=0",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),s=Pr("git",["diff","--unified=0","--cached",t],{encoding:"utf-8",cwd:e,timeout:3e4,maxBuffer:64*1024*1024}),a=az([n,r]);return{changedFileLines:[...new Set([...a.changedFiles,...Ev(i)])],changedRanges:kv([...vv(o),...vv(s)]),renamedFiles:a.renamedFiles,deletedFiles:a.deletedFiles}}function vf(e,t,n){try{return Pr("git",["show",`${t}:./${n}`],{encoding:"utf-8",cwd:e,timeout:1e4,stdio:["ignore","pipe","ignore"]})}catch{return null}}function cs(e,t,n=[]){let r=iz(e,t,n);return i=>(r.has(i)||r.set(i,vf(e,t,i)),r.get(i)??null)}function ls(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 iz(e,t,n){let r=[...new Set(n)],i=new Map;if(r.length===0)return i;try{let o=r.map(a=>`${t}:./${a}
|
|
768
|
+
`).join(""),s=Pr("git",["cat-file","--batch"],{cwd:e,input:o,maxBuffer:256*1024*1024,timeout:1e4,stdio:["pipe","pipe","ignore"]});return oz(s,r)}catch{for(let o of r)i.set(o,vf(e,t,o));return i}}function oz(e,t){let n=new Map,r=0;for(let i of t){let o=e.indexOf(10,r);if(o<0)throw new Error("git cat-file batch output ended before object header");let s=e.subarray(r,o).toString("utf-8");if(r=o+1,s.endsWith(" missing")){n.set(i,null);continue}let a=/^[0-9a-f]+ ([^ ]+) (\d+)$/.exec(s);if(!a)throw new Error(`unexpected git cat-file batch header: ${s}`);let[,c,l]=a,u=Number(l);if(!Number.isFinite(u)||u<0)throw new Error(`unexpected git cat-file batch size: ${s}`);if(r+u>e.length)throw new Error("git cat-file batch output ended before blob payload");let d=e.subarray(r,r+u);n.set(i,c==="blob"?d.toString("utf-8"):null),r+=u,e[r]===10&&(r+=1)}return n}function sz(e,t,n,r){if(n.length===0)return[];let i=new Map,o=new Set;for(let a of r.renamedFiles)n.includes(a.to)&&(i.set(a.to,a),o.add(a.from));let s=r.deletedFiles;if(s.length===0)return[...i.values()].sort((a,c)=>a.to.localeCompare(c.to));for(let a of n){if(i.has(a)||!ZW(`${e}/${a}`))continue;let c=s.filter(d=>!o.has(d)).filter(d=>Cv(d)===Cv(a));if(c.length===0)continue;let l=ez(`${e}/${a}`,"utf-8"),u=c.map(d=>({from:d,to:a,similarity:cz(vf(e,t,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 az(e){let t=new Set,n=new Map,r=new Set;for(let i of e.flatMap(o=>Ev(o))){let[o,s,a]=i.split(" ");if(!(!o||!s)){if(o.startsWith("R")&&a){t.add(a),n.set(a,{from:s,to:a,similarity:Number(o.slice(1))/100});continue}t.add(s),o.startsWith("D")&&r.add(s)}}return{changedFiles:[...t],renamedFiles:[...n.values()],deletedFiles:[...r]}}function cz(e,t){let n=new Set(Rv(e)),r=new Set(Rv(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 Rv(e){return e.match(/[A-Za-z_$][\w$]*|[{}()[\].,]/g)??[]}function Ev(e){return e.split(`
|
|
769
|
+
`).map(t=>t.trim()).filter(t=>t.length>0)}function lz(e,t){let n=Dv(e),r=[];for(let i of t){let o=n(i);o&&!e.isIgnored(o)&&r.push(o)}return r}function uz(e,t){let n=Dv(e),r=[];for(let i of t){let o=n(i.file);o&&!e.isIgnored(o)&&r.push({...i,file:o})}return kv(r)}function Dv(e){let t=e.all(`SELECT relative_path FROM documents
|
|
770
|
+
ORDER BY id`).map(r=>r.relative_path),n=new Map(t.map(r=>[r,r]));return r=>{let i=r.replace(/\\/g,"/"),o=n.get(i);return o||(t.find(s=>s.endsWith(i))??null)}}function vv(e){let t=[],n=null;for(let r of e.split(`
|
|
771
|
+
`)){if(r.startsWith("+++ ")){n=dz(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 dz(e){return e==="/dev/null"?null:e.startsWith("a/")||e.startsWith("b/")?e.slice(2):e}function kv(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 mz(e,t){let n=t.get(e.relativePath);return!n||n.length===0?!0:n.some(r=>If(e.startLine,e.endLine,r.startLine,r.endLine))}function fz(e,t,n){let r=new Map,i=[],o=Pv(e),s=bz(n);for(let a of t){let c=o.get(a.file)??[];if(c.some(d=>If(d.startLine,d.endLine,a.startLine,a.endLine)))continue;let l=s.get(a.file)??[],u=Sz(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(Cf(a,"ast-widened"));continue}}if(l.length===0){let d=[...c].filter(m=>m.startLine<=a.startLine).sort((m,f)=>f.startLine-m.startLine||m.endLine-f.endLine)[0];if(d){r.set(d.symbolId,d),i.push(Cf(a,"nearest-preceding"));continue}}i.push(Cf(a,"unattributed"))}return{definitions:[...r.values()],notes:i}}function pz(e,t,n,r){let i=Pv(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=>If(m.startLine,m.endLine,d.startLine,d.endLine))||o.push(d);o.some(d=>d.file===c)&&s.push(...gz(e,c))}return fz(t,o,s)}function gz(e,t){let n=Y(e,t);return n?n.rootNode.namedChildren.filter(hz).map(r=>({file:t,startLine:r.startPosition.row,endLine:r.endPosition.row})).filter(r=>r.endLine>=r.startLine):[]}function hz(e){return e.endPosition.row<e.startPosition.row?!1:!new Set(["import_statement","comment"]).has(e.type)}function yz(e){let t=new Map;for(let n of e)t.set(n.symbolId,n);return[...t.values()]}function Pv(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 bz(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 Sz(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 Cf(e,t){return{file:e.file,startLine:e.startLine,endLine:e.endLine,method:t}}function If(e,t,n,r){return e<=r&&n<=t}function xz(e,t,n,r,i,o,s,a,c){let l=Math.max(a,o.size,s.size);if(!wz(t,l))return;let u=I(t.symbol);r.push({symbol:t.symbol,shortName:u,file:t.relativePath,startLine:t.startLine,endLine:t.endLine,fanIn:l});for(let d of c)Rf(e,n,i,d,u);for(let d of o)Rf(e,n,i,d,u);for(let d of s)Rf(e,n,i,d,u)}function Iv(e){try{return e()}catch(t){return console.error(`warning: diff-impact enrichment scan failed, continuing without it: ${t instanceof Error?t.message:t}`),new Map}}function Cz(e,t){if(t.length===0)return new Map;let n=e.all(`SELECT m.symbol_id, COUNT(DISTINCT c.document_id) AS fan_in
|
|
772
|
+
FROM mentions m
|
|
773
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
774
|
+
WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
|
|
775
|
+
AND m.role != 1
|
|
776
|
+
GROUP BY m.symbol_id`,...t);return new Map(n.map(r=>[r.symbol_id,r.fan_in]))}function Rz(e,t,n){if(t.length===0||n.length===0)return new Map;let r=e.all(`SELECT DISTINCT m.symbol_id, ref_d.relative_path
|
|
777
|
+
FROM mentions m
|
|
778
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
779
|
+
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
780
|
+
WHERE m.symbol_id IN (${t.map(()=>"?").join(",")})
|
|
781
|
+
AND m.role != 1
|
|
782
|
+
AND ref_d.relative_path NOT IN (${n.map(()=>"?").join(",")})
|
|
783
|
+
${e.pathExclusionsFor("ref_d")}`,...t,...n),i=new Map;for(let o of r){let s=i.get(o.symbol_id);s||(s=new Set,i.set(o.symbol_id,s)),s.add(o.relative_path)}return i}function Rf(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 vz(e){return[...e.entries()].map(([t,n])=>({file:t,consumedSymbols:n.size})).sort((t,n)=>n.consumedSymbols-t.consumedSymbols)}function Iz(e){return!(In(e.symbol)||e.parentTypeName!==null&&!fe(e.symbol))}function wz(e,t){return fe(e.symbol)||e.isTypeLike?!0:e.parentTypeName===null&&t>0}function wf(e){let[t,n]=Fi(e,":"),r=t||"unknown",i=(o={})=>{let s=o.actionTier??Ez(r);return{sourceAnalyzer:r,actionTier:s,rootCauseKey:o.rootCauseKey??(n||e),label:o.label??`${r} finding`,relatedFiles:o.relatedFiles??[],why:o.why??[],remediation:o.remediation??Dz(s,r),file:o.file}};if(!n)return i({rootCauseKey:e,why:["Baseline identity did not include analyzer payload."]});if(["dead","isolated","extract","wrapper","passthrough","stale"].includes(r)){let[o,s]=Fi(n,":");return i({file:o,relatedFiles:o?[o]:[],rootCauseKey:s?`${o}:${s}`:n,label:`${r} finding`,why:s?[`Baseline subject: ${s}.`]:[]})}if(r==="cycle"){let o=n.split(">").filter(Boolean);return i({relatedFiles:o,rootCauseKey:n,label:"cycle finding",why:o.length>0?[`Cycle path: ${o.join(" > ")}.`]:[]})}if(r==="similar"){let o=n.split("|").filter(Boolean);return i({relatedFiles:[],rootCauseKey:n,label:"similarity finding",why:o.length>0?[`Similar symbols: ${o.join(" | ")}.`]:[]})}if(r==="architecture"){let[o,s]=Fi(n,":");if(o==="forbidden-edge"){let[a,c]=Fi(s,":"),l=Vc(a),u=Vc(c);return i({actionTier:"direct",rootCauseKey:n,label:"architecture boundary violation",why:[`Declared boundary rule rejects ${l} -> ${u}.`],remediation:`Move the dependency behind an allowed boundary, or deliberately update the ${l} dependency rule and baseline.`})}if(o==="cycle"){let a=s.split("|").filter(Boolean).map(Vc);return i({actionTier:"direct",rootCauseKey:n,label:"forbidden architecture cycle",why:[`requireAcyclic rejects the connected boundary group: ${a.join(", ")}.`],remediation:"Break the boundary cycle, or deliberately revise the acyclicity rule and baseline."})}if(o==="missing-policy-row"){let a=Vc(s);return i({actionTier:"direct",rootCauseKey:n,label:"incomplete architecture policy",why:[`requireCompletePolicy rejects the missing outgoing dependency row for ${a}.`],remediation:`Declare the allowed outgoing dependencies for ${a}, including an empty row when it must depend on nothing.`})}}if(r==="drift"){let[o,s]=Fi(n,":"),[a,c]=Fi(s,":");return i({actionTier:o==="unused-import"?"direct":"signal",file:a,relatedFiles:[...new Set([a,c].filter(Boolean))],rootCauseKey:n,label:`${o||"drift"} finding`,why:[...o?[`Drift kind: ${o}.`]:[],...c?[`Related dependency: ${c}.`]:[]]})}return i({why:["Baseline analyzer prefix is not recognized by this diff-gate version."]})}function Ez(e){switch(e){case"dead":case"isolated":case"cycle":case"passthrough":case"architecture":return"direct";case"similar":case"extract":case"wrapper":case"stale":return"signal";default:return"signal"}}function Dz(e,t){return e==="direct"?`Fix the new ${t} baseline finding, or knowingly accept it via health --write-baseline.`:`Review the new ${t} baseline signal; fix it if it reflects real debt, or knowingly accept it via health --write-baseline.`}function Fi(e,t){let n=e.indexOf(t);return n<0?[e,""]:[e.slice(0,n),e.slice(n+t.length)]}function Vc(e){try{return decodeURIComponent(e)}catch{return e}}import{existsSync as Lz,readFileSync as _v}from"fs";function Kc(e,t){let n=kz(e,t)??Pz(e,t)??Fz(e,t)??Tz(e,t);return _z(e,n,t)}function kz(e,t){let n=-1,r=null;for(let i=0;i<=t;i+=1){let o=Ef(e[i]??"");o&&(r===null?(r=o,n=i):o===r&&(r=null,n=-1))}if(r===null||n<0)return null;for(let i=t+1;i<e.length;i+=1)if(Ef(e[i]??"")===r)return{start:n,end:i+1};return{start:n,end:e.length}}function Ef(e){let t=e.match(/^\s*(```+|~~~+)/);return t?t[1].startsWith("`")?"`":"~":null}function Pz(e,t){if(!Wc(e[t]??""))return null;let n=t;for(;n>0&&Wc(e[n-1]??"");)n-=1;let r=t+1;for(;r<e.length&&Wc(e[r]??"");)r+=1;return{start:n,end:r}}function Wc(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&t.includes("|")}function Fz(e,t){let n=t;for(;n>=0;){let o=e[n]??"";if(zc(o)!==null)break;if(Df(o)!==null)return null;n-=1}if(n<0)return null;let r=zc(e[n]??"");if(r===null)return null;let i=n+1;for(;i<e.length;){let o=e[i]??"",s=zc(o);if(s!==null){if(s<=r)break;i+=1;continue}if(Df(o)!==null)break;i+=1}return{start:n,end:i}}function zc(e){let t=e.match(/^(\s*)(?:[-*+]\s+|\d+[.)]\s+)/);return t?t[1].length:null}function Tz(e,t){let n=e[t]??"";if(Tv(n)||n.trim().length===0)return{start:t,end:t+1};let r=t;for(;r>0&&Fv(e[r-1]??"");)r-=1;let i=t+1;for(;i<e.length&&Fv(e[i]??"");)i+=1;return{start:r,end:i}}function Fv(e){return Df(e)===null}function Df(e){return e.trim().length===0?"blank":Tv(e)?"heading":Ef(e)?"fence":Wc(e)?"table":zc(e)!==null?"list":null}function Tv(e){return/^#{1,6}\s+/.test(e.trim())}function _z(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(`
|
|
784
|
+
`).trim();return o.length<=2e3?o:`${o.slice(0,2e3).trimEnd()}...`}function Fr(e,t){return t.filter(n=>e.includes(n))}var Mz=/<!--\s*scip-query:\s*snapshot\s*-->/i;function Jc(e,t){if((e.config.docs?.snapshotPaths??[]).some(i=>Wn(i,t)))return!0;let r=P(e,t);return r.length>0&&Mz.test(r)}var yn={classifyCitation:Nz,citationContexts:Oz,citationKindLabel:Bz,citationRemediation:$z,referenceTargets:Hz,hasLineAnchoredCitation:Az};function Az(e){return e.some(t=>(t.lineReferences?.length??0)>0)}function Nz(e){let t=e.join(`
|
|
785
|
+
`).toLowerCase(),n=[],r=Fr(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=Fr(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=Fr(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 Oz(e,t,n){let r;try{r=_v(`${e.config.projectRoot}/${t}`,"utf-8").split(/\r?\n/)}catch{return[]}let i=n.flatMap(jz),o=[];for(let s=0;s<r.length;s+=1){let a=r[s]??"";i.some(c=>a.includes(c))&&o.push(Kc(r,s))}return o}function jz(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 Bz(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 $z(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 Hz(e,t,n){let r=qc(n),i=new Set;for(let o of t)Uz(e,o,r.get(o)??[])&&i.add(o);return i}function Uz(e,t,n){if(!qz.test(t))return!0;let r=`${e.config.projectRoot}/${t}`;if(!Lz(r))return!0;if(n.length===0)return!1;let i=_v(r,"utf-8").split(/\r?\n/),o=Gz(i);for(let s of n)for(let a=s.startLine;a<=s.endLine;a+=1)if((i[a]??"").trim()!==""&&!o.has(a))return!0;return!1}var qz=/\.(?:[cm]?[jt]sx?)$/i;function Gz(e){let t=new Set,n=!1;for(let r=0;r<e.length;r+=1){let i=e[r].trim();!n&&Vz(i)&&(n=!0),n&&(t.add(r),i.endsWith(";")&&(n=!1))}return t}function Vz(e){return/^import(?:\s|$)/.test(e)||/^export(?:\s+type)?\s+(?:\*|\{)/.test(e)}import{existsSync as Mv,readFileSync as Pf,statSync as Wz}from"fs";import{join as Ti}from"path";var Lv=ce({kind:"doc-path-evidence",invalidation:X("doc-path-evidence"),serialize:aK,deserialize:cK}),us=/\.(?:md|mdx|rst|txt)$/i;function zz(e){return/(?:^|\/)(?:docs\/plans|plans|adrs?|rfcs?|decisions|changelogs?|archive|reports?)\//i.test(e)||/(?:^|\/)CHANGELOG\.(?:md|mdx|rst|txt)$/i.test(e)}var Kz=3,Jz=/([A-Za-z0-9_@-]+(?:\/[A-Za-z0-9_.@-]+)+\.[A-Za-z0-9]{1,6})(?::([1-9][0-9]*))?\b/g;function Yz(e,t={}){let{doc:n,limit:r=20,minCoupling:i=Kz,includeSnapshotExcluded:o=!1}=t,s=eK(e,t.historyMode??"bounded");if(!s)return{available:!1,commitsAnalyzed:0,docsScanned:0,findings:[]};let a=[];for(let c of s.docFiles){if(n!==void 0&&!c.includes(n)||n===void 0&&!Nv(e,c)||n!==void 0&&!Mv(Ti(e.config.projectRoot,c)))continue;let l=Jc(e,c);if(l&&!o)continue;let{value:u,estimated:d}=Xz(e,c,s.changeTimes.get(c)),m=Qz(e,c),f=new Map,{resolved:p,broken:g,citations:y}=rK(e,c,s.tracked,s.trackedBySuffix,s.everSeenInHistory),h=new Map(y.map(b=>[b.file,b]));for(let b of p){if(b===c||us.test(b))continue;let S=(s.changeTimes.get(b)??[]).filter(v=>v>u).length;if(S===0)continue;let x=h.get(b);f.set(b,{file:b,evidence:"reference",coChanges:0,changesSinceDocUpdate:S,...kf("reference",m,x?.contexts),citationContexts:x?.contexts,citedLines:x?.lineReferences})}for(let[b,S]of s.coupling.get(c)??[]){if(S<i||!s.tracked.has(b))continue;let x=(s.changeTimes.get(b)??[]).filter(R=>R>u).length;if(x===0)continue;let v=f.get(b);v?(v.evidence="both",v.coChanges=S,Object.assign(v,kf("both",m,v.citationContexts))):f.set(b,{file:b,evidence:"co-change",coChanges:S,changesSinceDocUpdate:x,...kf("co-change",m)})}if(f.size===0&&g.length===0)continue;let C=[...f.values()].sort((b,S)=>S.changesSinceDocUpdate-b.changesSinceDocUpdate);a.push({doc:c,docLastChangedAt:u,staleness:C.reduce((b,S)=>b+S.changesSinceDocUpdate,0)+g.length*10,subjects:C.slice(0,8),brokenReferences:g,...l?{snapshotExcluded:!0}:{},...d?{docLastChangedAtEstimated:!0}:{}})}return a.sort((c,l)=>l.staleness-c.staleness),{available:!0,commitsAnalyzed:s.historyCommitCount,docsScanned:s.docFiles.length,findings:a.slice(0,r)}}function Xz(e,t,n){if(n&&n.length>0)return{value:Math.max(...n),estimated:!1};try{return{value:Math.floor(Wz(Ti(e.config.projectRoot,t)).mtimeMs/1e3),estimated:!0}}catch{return{value:0,estimated:!1}}}function Qz(e,t){let n;try{n=Pf(Ti(e.config.projectRoot,t),"utf8").slice(0,6e3)}catch{return{docIntent:"unknown",reasons:["doc text unavailable"]}}let r=`${t}
|
|
786
|
+
${n}`.toLowerCase(),i=Fr(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=Fr(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 kf(e,t,n=[]){let r=e==="co-change"||n.length===0?null:yn.classifyCitation(n);return{actionTier:Zz(e,t.docIntent,r?.actionTier),docIntent:t.docIntent,docIntentReasons:t.reasons,...r?{citationKind:r.citationKind,citationKindReasons:r.reasons}:{}}}function Zz(e,t,n){return t==="historical-note"?"support":n||(e==="co-change"?"signal":"direct")}function eK(e,t){let n=Xe(e,{historyMode:t}),r=n.commitHistory();if(!r)return null;let i=n.trackedFiles()??new Set,o=new Map,s=new Map,a=new Set;for(let c of r.commits){let l=[...new Set(c.files)],u=l.filter(m=>us.test(m)),d=l.filter(m=>!us.test(m));for(let m of l){a.add(m);let f=o.get(m)??[];f.push(c.timestamp),o.set(m,f)}for(let m of u){let f=s.get(m);f||(f=new Map,s.set(m,f));for(let p of d)f.set(p,(f.get(p)??0)+1)}}return{changeTimes:o,coupling:s,docFiles:[...i].filter(c=>us.test(c)),everSeenInHistory:a,historyCommitCount:r.commits.length,tracked:i,trackedBySuffix:Ov(i)}}function Av(e,t){if(t.size===0)return[];let n=G(),r=0,i=0,o=0,s=0,a=0,c=0;return E("doc-reference.docs-citing-files",()=>{let l=Xe(e).trackedFiles()??new Set;r=l.size;let u=Ov(l),d=tK(t,u),m=[];for(let f of l){if(!Nv(e,f))continue;n&&(i+=1);let p;try{p=Pf(Ti(e.config.projectRoot,f),"utf-8")}catch{n&&(o+=1);continue}if(!oK(p,d)){n&&(s+=1);continue}let g=jv(e,f,p);if(!g)continue;n&&(a+=1);let y=nK(g.candidates,t,d,l,u);if(y.size===0)continue;let h=[...new Set([...y.values()].flatMap(x=>[...x]))],C=iK(g.contextsByCandidate,h),b=[...y].map(([x,v])=>({file:x,contexts:Yc([...v].flatMap(R=>C.get(R)??[])).slice(0,3),lineReferences:Xc([...v].flatMap(R=>g.lineReferencesByCandidate.get(R)??[]))})).filter(x=>x.contexts.length>0),S=[...y.keys()];if(S.length>0){n&&(c+=1);let x=S.sort();m.push({doc:f,cited:x,citations:b,citedClaims:Yc(b.flatMap(v=>v.contexts)).slice(0,3)})}}return m},()=>({targets:t.size,trackedFiles:r,livingDocs:i,unreadableDocs:o,candidateMisses:s,evidenceDocs:a,citedDocs:c}))}function Nv(e,t){return us.test(t)&&!zz(t)&&Mv(Ti(e.config.projectRoot,t))}function Ov(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 tK(e,t){let n=new Set(e);for(let r of e){let i=r.split("/");for(let o of[2,3]){if(i.length<o)continue;let s=i.slice(-o).join("/"),a=t.get(s);a?.length===1&&a[0]===r&&n.add(s)}}return n}function nK(e,t,n,r,i){let o=new Map;for(let s of e){if(!n.has(s))continue;let a;if(t.has(s))a=s;else if(r.has(s))a=s;else{let l=i.get(s);l?.length===1&&(a=l[0])}if(!a||!t.has(a))continue;let c=o.get(a)??new Set;c.add(s),o.set(a,c)}return o}function rK(e,t,n,r,i){let o=new Set,s=new Set,a=jv(e,t);if(!a)return{resolved:o,broken:[],citations:[]};let c=a.candidates,l=a.contextsByCandidate,u=a.lineReferencesByCandidate,d=new Map,m=new Map,f=(p,g)=>{let y=l.get(g);if(y&&y.length>0){let C=d.get(p)??[];C.push(...y),d.set(p,Yc(C).slice(0,3))}let h=u.get(g);h&&h.length>0&&m.set(p,Xc([...m.get(p)??[],...h]))};for(let p of c){if(n.has(p)){o.add(p),f(p,p);continue}let g=r.get(p);if(g&&g.length===1){o.add(g[0]),f(g[0],p);continue}g&&g.length>1||i.has(p)&&s.add(p)}return{resolved:o,broken:[...s],citations:[...d].map(([p,g])=>({file:p,contexts:g,lineReferences:m.get(p)}))}}function iK(e,t){let n=new Map;for(let r of t){let i=e.get(r);i&&i.length>0&&n.set(r,[...i])}return n}function jv(e,t,n){let r=n;if(r===void 0)try{r=Pf(Ti(e.config.projectRoot,t),"utf-8")}catch{return null}let i=me(e,t,r),o=Lv.read(e,t,i);if(o)return o;let s=sK(r);return Lv.write(e,t,i,s),s}function oK(e,t){for(let n of t)if(e.includes(n))return!0;return!1}function sK(e){let t=e.split(/\r?\n/),n=new Set,r=new Map,i=new Map;for(let o=0;o<t.length;o+=1){let s=t[o]??"";for(let a of s.matchAll(Jz)){let c=(a[1]??"").replace(/^\.?\//,"");if(c.length===0)continue;n.add(c);let l=a[2]?Number(a[2]):null;l!==null&&Number.isSafeInteger(l)&&i.set(c,Xc([...i.get(c)??[],l]));let u=Kc(t,o);if(u.length===0)continue;let d=r.get(c)??[];d.push(u),r.set(c,Yc(d).slice(0,3))}}return{candidates:[...n],contextsByCandidate:r,lineReferencesByCandidate:i}}function aK(e){let t={candidates:e.candidates,contextsByCandidate:[...e.contextsByCandidate.entries()],lineReferencesByCandidate:[...e.lineReferencesByCandidate.entries()]};return JSON.stringify(t)}function cK(e){try{let t=JSON.parse(e);if(!Mt(t))return null;let n=He(t.candidates),r=uK(t.contextsByCandidate),i=lK(t.lineReferencesByCandidate);return!n||!r?null:{candidates:n,contextsByCandidate:new Map(r),lineReferencesByCandidate:new Map(i??[])}}catch{return null}}function lK(e){if(e===void 0)return[];if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!Array.isArray(n)||n.length!==2||typeof n[0]!="string"||!Array.isArray(n[1]))return null;let r=[];for(let i of n[1]){if(typeof i!="number"||!Number.isSafeInteger(i))return null;r.push(i)}t.push([n[0],Xc(r)])}return t}function uK(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=He(n[1]);if(!r)return null;t.push([n[0],r])}return t}function Yc(e){let t=[];for(let n of new Set(e))t.some(r=>dK(r,n))||t.push(n);return t}function Xc(e){return[...new Set(e)].sort((t,n)=>t-n)}function dK(e,t){if(e===t)return!0;let n=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),r=t.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0),i=Math.min(n.length,r.length);if(i===0)return!1;if(i<3)return e.includes(t)||t.includes(e);let o=new Set(r),s=n.filter(a=>o.has(a)).length;return s>=3&&s/i>=.6}import{createHash as mK}from"crypto";var $v=3;function ds(e,t={}){let{scope:n,maxLoc:r=15,minLoc:i=$v,limit:o,scanLimit:s}=t,a=mf(e),c=qv(e,{scope:n,maxLoc:r,scanLimit:s}).map(u=>Gv(e,u,a,i)).filter(u=>u!==null),l=Uv(c);return o?l.slice(0,o):l}function Ff(e,t,n={}){let{scope:r,maxLoc:i=15,minLoc:o=$v,scanLimit:s}=n,a=mf(e),c=qv(e,{scope:r,maxLoc:i,scanLimit:s}).map(u=>Gv(e,u,a,o)).filter(u=>u!==null),l=c.find(u=>u.symbol===t);return l?c.filter(u=>u.symbol!==l.symbol&&u.normalizedBody===l.normalizedBody&&u.file!==l.file).sort(Vv).map(({normalizedBody:u,...d})=>d):[]}function Hv(e){let t=zt(e);return ct(t).replace(/\s+/g,"")}function Uv(e){let t=new Map;for(let r of e){if(r.normalizedBody.length<8)continue;let i=pK(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(Vv).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=Bv(i)-Bv(r);return s!==0?s:r.canonical.file.localeCompare(i.canonical.file)}),n}function qv(e,t){let n=De(e,{scope:t.scope}).filter(r=>r.isFunctionLike&&!e.isIgnored(r.relativePath)).filter(r=>!_s(e,r.relativePath,r.startLine,"similar")).filter(r=>O(r)<=t.maxLoc);return n.sort((r,i)=>O(i)-O(r)||r.relativePath.localeCompare(i.relativePath)),le(n,t.scanLimit)}function Gv(e,t,n,r){let i=bn(e,t);if(!i||fK(i)<r)return null;let o=Tf(e,t);return o?{symbol:t.symbol,shortName:I(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:O(t),ageCommits:n?.get(t.relativePath)?.commitsAgo??null,normalizedBody:o}:null}function Tf(e,t){let n=bn(e,t);return n&&Hv(n)||null}function bn(e,t){let n=Ee(e,t.relativePath);return n.length===0?null:n.slice(t.startLine,t.endLine+1).join(`
|
|
787
|
+
`)}function zt(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(t>=0&&n>t)return e.slice(t+1,n);let r=e.indexOf("=>");return r>=0?e.slice(r+2).replace(/;+\s*$/,""):e}function fK(e){return zt(e).split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0).length}function pK(e){return mK("sha256").update(e).digest("hex").slice(0,16)}function Vv(e,t){let n=e.ageCommits??-1;return(t.ageCommits??-1)-n||e.file.localeCompare(t.file)||e.startLine-t.startLine}function Bv(e){return e.functions.reduce((t,n)=>t+n.loc,0)}var gK=new Set(qt());function hK(e,t={}){let{includeHomonyms:n=!1,limit:r}=t,i=_i(e,t).filter(o=>o.relationship==="divergent"||n&&o.relationship==="homonym");return r?i.slice(0,r):i}function _i(e,t={}){let{scope:n,minSimilarity:r=.3,scanLimit:i}=t,o=SK(e,{scope:n,scanLimit:i});return Kv(o,{minSimilarity:r,isDelegatePair:HK(e)}).filter(s=>!s.members.some(a=>_s(e,a.file,a.startLine,"twin")))}function Kv(e,t={}){let n=t.minSimilarity??.3,r=t.isDelegatePair,i=e.filter(l=>!tI(l.leaf)&&!FK(l.leaf)&&W(l.file)!=="test"&&!Fe(l.symbol)&&!Yv(l.symbol)&&!Xv(l.symbol,l.leaf)),{recordsByLeaf:o,recordOrder:s}=E("twin-drift.group-by-leaf",()=>yK(i),()=>({records:i.length})),a=E("twin-drift.cluster-leaf-names",()=>Jv([...o.keys()]),()=>({leaves:o.size}));return E("twin-drift.compare-clusters",()=>{let l=[];for(let u of a){let d=bK(u,o,s);if(d.length<2||new Set(d.map(C=>C.file)).size<2)continue;let m=null,f=!1,p=!1,g=new Set;for(let C=0;C<d.length;C+=1)for(let b=C+1;b<d.length;b+=1){let S=d[C],x=d[b];if(S.file===x.file||!MK(S,x)||r?.(S,x,d)||r?.(x,S,d))continue;if(f=!0,g.add(S.symbol),g.add(x.symbol),S.normalizedBody===x.normalizedBody){p=!0;continue}let v=EK(S.tokens,x.tokens);(!m||v>m.similarity)&&(m={a:S,b:x,similarity:v})}if(!f)continue;let y=d.filter(C=>g.has(C.symbol)).sort((C,b)=>C.file.localeCompare(b.file)||C.startLine-b.startLine).map(wK);if(!m){l.push({leaf:zv(u),relationship:p?"identical":"homonym",maxDivergence:0,members:y});continue}let h=m.similarity>=n?"divergent":"homonym";l.push({leaf:zv(u),relationship:h,maxDivergence:Math.round((1-m.similarity)*1e3)/1e3,members:y,...h==="divergent"?{firstDivergentTokens:DK(m.a.tokens,m.b.tokens)}:{}})}return l},()=>({clusters:a.length,records:i.length})).sort((l,u)=>u.members.length-l.members.length||u.maxDivergence-l.maxDivergence||l.leaf.localeCompare(u.leaf))}function yK(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 bK(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 SK(e,t){let n=E("twin-drift.load-definitions",()=>De(e,{scope:t.scope}).filter(o=>xK(o)&&!e.isIgnored(o.relativePath)).filter(o=>!xi(o.relativePath)));E("twin-drift.sort-definitions",()=>n.sort((o,s)=>o.relativePath.localeCompare(s.relativePath)||o.startLine-s.startLine),()=>({definitions:n.length}));let r=le(n,t.scanLimit),i=E("twin-drift.select-candidates",()=>CK(r),()=>({scanned:r.length}));return E("twin-drift.build-records",()=>{let o=[];for(let s of i){let a=RK(e,s);a&&o.push(a)}return o},()=>({candidates:i.length,scanned:r.length}))}function xK(e){return e.isFunctionLike?e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&gK.has(e.kind):!0:!1}function CK(e){let t=e.filter(o=>o.leaf&&!tI(o.leaf)&&!Fe(o.symbol)&&!Yv(o.symbol)&&!Xv(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=Jv([...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=>W(a.relativePath)==="test"))for(let a of s)i.add(a)}return e.filter(o=>i.has(o))}function RK(e,t){if(!t.leaf)return null;let n=bn(e,t);if(!n||!fe(t.symbol)&&!vK(n,t.leaf))return null;let r=ct(zt(n)),i=r.replace(/\s+/g,"");if(!i||i.length<8)return null;let o=r.match(IK)??[];return o.length===0?null:{leaf:t.leaf,symbol:t.symbol,shortName:I(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:O(t),normalizedBody:i,tokens:o,isThinForwarder:Zv(r)}}function vK(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\b(?:const|let|var)\\s+${n}(?:\\s*:[^=]+)?\\s*=\\s*(?:async\\s*)?(?:\\([^)]*\\)|[A-Za-z_$][\\w$]*)\\s*=>`,"s").test(e)}var IK=/[A-Za-z_$][A-Za-z0-9_$]*|\d+(?:\.\d+)?|[^\sA-Za-z0-9_$]/g;function wK(e){return{symbol:e.symbol,shortName:e.shortName,file:e.file,startLine:e.startLine,endLine:e.endLine,loc:e.loc}}function EK(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 DK(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 Jv(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)kK(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 kK(e,t){return e===t||e.toLowerCase()===t.toLowerCase()?!0:e.length<8||t.length<8||Math.abs(e.length-t.length)>2||PK(e.toLowerCase(),t.toLowerCase())/Math.max(e.length,t.length)<.8?!1:AK(e.toLowerCase(),t.toLowerCase(),2)}function PK(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r+=1;return r}function FK(e){return/^[A-Z][A-Z0-9_]*$/.test(e)||/^__[^_].*__$/.test(e)||TK.has(e.toLowerCase())}var TK=new Set(["main","row"]),_K=new Set(["app","component","components","feature","features","impl","index","lib","route","routes","shared","src","tsx","typescript","ui"]);function Yv(e){return e.startsWith("rust-analyzer ")&&/\/(?:tests?|benches?)\//.test(e)}var LK=new Set(["default","new","reset"]);function Xv(e,t){return e.startsWith("rust-analyzer ")&&LK.has(t.toLowerCase())}function MK(e,t){if(e.leaf.toLowerCase()!==t.leaf.toLowerCase()||e.leaf.length>4)return!0;let n=Wv(e);return[...Wv(t)].some(r=>n.has(r))}function Wv(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&&!_K.has(n)))}function AK(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 Qv(e){return Zv(ct(zt(e)))}function Zv(e){let t=e.trim();if(!t||NK.test(t))return!1;let n=BK(t);return n.length===0||n.length>2?!1:jK(n[n.length-1])}var NK=/\b(?:if|else|for|while|switch|try|catch|do)\b/,OK=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^[\]]*\])*\((?:[^()]|\([^()]*\))*\)$/;function jK(e){let t=e.trim().replace(/^return\s+/,"").replace(/^await\s+/,"").replace(/;\s*$/,"").trim();return OK.test(t)}function BK(e){let t=[],n=0,r="";for(let i of e){if(i==="("||i==="["||i==="{"?n+=1:(i===")"||i==="]"||i==="}")&&(n=Math.max(0,n-1)),i===";"&&n===0){t.push(r),r="";continue}r+=i}return r.trim()&&t.push(r),t.map(i=>i.trim()).filter(i=>i.length>0)}var $K=3;function HK(e){let t=new Map;return(n,r,i)=>{if(!n.isThinForwarder)return!1;let o=`${n.symbol}\0${r.symbol}`,s=t.get(o);if(s!==void 0)return s;let a=eI(e,n,r,i,$K,new Set);return t.set(o,a),a}}function eI(e,t,n,r,i,o){if(i<=0||o.has(t.symbol)||(o.add(t.symbol),(wn(e,t.file)??[]).filter(c=>c.line>=t.startLine&&c.line<=t.endLine&&c.calleeLeaf===n.leaf).length===0))return!1;let a=new Set(te(e,t.file).filter(c=>c.sourcePath&&(c.kind!=="namespace"||c.usedMembers.includes(n.leaf))).map(c=>c.sourcePath));if([...a].some(c=>Qe(c,n.file)))return!0;for(let c of r)if(!(c.symbol===t.symbol||c.symbol===n.symbol||!c.isThinForwarder)&&[...a].some(l=>Qe(l,c.file))&&eI(e,c,n,r,i-1,o))return!0;return!1}function tI(e){return e.startsWith("<")&&e.endsWith(">")}function zv(e){return[...e].sort()[0]}import{readFileSync as UK,readdirSync as qK}from"fs";import{basename as GK,join as _f}from"path";function VK(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 Lf(e,t){let n=WK(e,t.file,t.keys);if(!n.ok)return{name:t.name,file:t.file,status:"unavailable",missing:[],extra:[],unavailableReason:n.reason};let r=QK(e.config.projectRoot,t.mustEqual),i=VK(n.keys,r,{allowExtra:t.allowExtra??!1}),o=i.missing.length>0||i.extra.length>0?"violated":"ok";return{name:t.name,file:t.file,status:o,missing:i.missing,extra:i.extra}}function rI(e,t){return t.map(n=>Lf(e,n))}function iI(e,t){if(t.has(e.file))return!0;let n=e.mustEqual;switch(n.type){case"top-level-dirs":return[...t].some(r=>r===n.path||r.startsWith(`${n.path}/`));case"file-glob":return[...t].some(r=>Wn(n.pattern,r));case"registered-commands":return t.has("docs/COMMAND_REFERENCE.md");case"builtin-skills":return[...t].some(r=>r.startsWith("skills/"))}}function oI(e){if(e.status==="unavailable")return`[coverage-contract] ${e.name}: DISCLOSED \u2014 could not evaluate (${e.unavailableReason})`;let t=[];return e.missing.length>0&&t.push(`missing ${e.missing.join(", ")}`),e.extra.length>0&&t.push(`extra ${e.extra.join(", ")}`),`[coverage-contract] ${e.name}: ${t.join("; ")}`}function WK(e,t,n){return n.type==="markdown-list"?XK(e,t,n.marker):zK(e,t,n)}function zK(e,t,n){if(!P(e,t))return{ok:!1,reason:`file not found: ${t}`};let i=N(t);if(!i)return{ok:!1,reason:`unsupported file type for ${n.type} extraction: ${t}`};let o=Y(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"?KK(o,n.identifier):YK(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 sI(e){let t=e.childForFieldName("value");return t?t.type==="as_expression"||t.type==="satisfies_expression"?t.namedChild(0):t:null}function KK(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=sI(n);if(i?.type==="object")return JK(i)}return null}function JK(e){let t=new Set;for(let n of e.namedChildren)if(n.type==="pair"){let r=n.childForFieldName("key");r&&t.add(aI(r.text))}else n.type==="shorthand_property_identifier"&&t.add(n.text);return[...t].sort()}function YK(e,t){for(let n of e.rootNode.descendantsOfType("variable_declarator")){if(n.childForFieldName("name")?.text!==t)continue;let i=sI(n);if(i?.type!=="array")continue;let o=new Set;for(let s of i.namedChildren)s.type==="string"&&o.add(aI(s.text));return[...o].sort()}return null}function aI(e){return e.length>=2&&(e[0]==="'"&&e.endsWith("'")||e[0]==='"'&&e.endsWith('"'))?e.slice(1,-1):e}function XK(e,t,n){let r=P(e,t);if(!r)return{ok:!1,reason:`file not found: ${t}`};let i=cI(r,n);return i===null?{ok:!1,reason:`no <!-- BEGIN GENERATED ${n} --> ... <!-- END GENERATED ${n} --> block in ${t}`}:{ok:!0,keys:lI(i)}}function cI(e,t){let n=H(t),i=new RegExp(`<!--\\s*BEGIN GENERATED ${n}\\s*-->([\\s\\S]*?)<!--\\s*END GENERATED ${n}\\s*-->`).exec(e);return i?i[1]:null}function lI(e){let t=new Set;for(let n of e.matchAll(/`([a-z][a-z0-9-]*)`/g))t.add(n[1]);for(let n of e.matchAll(/\[([a-z][a-z0-9-]*)\]\([^)]*\)/g))t.add(n[1]);return[...t].sort()}function QK(e,t){switch(t.type){case"top-level-dirs":return nI(_f(e,t.path));case"file-glob":return[...new Set(_c(e,t.pattern).map(n=>GK(n)))].sort();case"registered-commands":return ZK(e);case"builtin-skills":return nI(_f(e,"skills"))}}function nI(e){let t;try{t=qK(e,{withFileTypes:!0})}catch{return[]}return t.filter(n=>n.isDirectory()&&!n.name.startsWith(".")).map(n=>n.name).sort()}function ZK(e){let t;try{t=UK(_f(e,"docs/COMMAND_REFERENCE.md"),"utf-8")}catch{return[]}let n=cI(t,"COMMAND REFERENCE");return n?lI(n):[]}var he={dead:{minLoc:3,skipBarrels:!0,deadCodeOnly:!0},isolated:{minLoc:3},similar:{minSimilarity:.6,limit:50,minCallees:4},duplicateBodies:{maxLoc:15,limit:50},extract:{minLoc:15,minCallees:5,limit:50},wrappers:{maxLoc:15,limit:50},passthroughs:{maxLoc:15,limit:50},stale:{minLoc:3,limit:50},drift:{},twinDrift:{minSimilarity:.3}};import{existsSync as e2,readFileSync as t2}from"fs";import{isAbsolute as n2,join as r2}from"path";var i2=".scipquery-baseline.json";function Mf(e){if(e.startsWith("similar:")){let t=e.slice(8).split("|");return t.length!==2?e:`similar:${t.map(I).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(I).sort().join("|")}`}return e}function Li(e,t){return t&&n2(t)?t:r2(e.config.projectRoot,t??i2)}function Qc(e,t,n={}){let r=Li(e,n.path);if(!e2(r))throw new Error(`No baseline found at ${r}. Create one with: scip-query health --write-baseline`);let o=(JSON.parse(t2(r,"utf-8")).findings??[]).map(Mf),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 ms from"path";function ps(e,t){let{scope:n,minDeviation:r=5,limit:i=50}=t??{},o=t?.semantic!==!1,s=t?.includePatternDeviations===!0,c=new T(e).fileDependencyGraph(n),l=kr(e,{scope:n}),u=l2([...o2(e,c,{scope:n,semantic:o}),...a2(l.forbiddenEdges),...s?c2(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 o2(e,t,n){let r=m2(e,n.scope),i=[],o=new Set;for(let[a,c]of t){if(fs(a))continue;let l=r.get(a)??new Set;for(let u of c)fs(u)||l.has(u)||s2(e,a,u,n)||(i.push({file:a,dep:u}),o.add(a))}o.size>0&&g2(e,r,{paths:[...o]});let s=[];for(let{file:a,dep:c}of i)(r.get(a)??new Set).has(c)||s.push({file:a,kind:"unused-import",description:`Depends on ${c} but references none of its symbols`,dep:c,actionTier:"direct",evidenceReasons:[`dependency edge exists from ${a} to ${c}`,"no semantic, source, type-only, side-effect, or Vue-template usage survived the conservative skip gates"],recommendation:"Remove the unused import or dependency edge after running the project checks."});return s}function s2(e,t,n,r){return b2(e,t,n)||S2(e,t,n)||h2(n)||C2(e,t,n)||x2(n)?!0:r.semantic&&y2(e,t,n)}function a2(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 c2(e,t){let n=[];for(let[r,i]of u2(e)){let o=i.filter(a=>!fs(a));if(o.length<t)continue;let s=d2(e,o);for(let a of o)for(let c of e.get(a)??[])fs(c)||(s.get(c)??0)===1&&ms.dirname(c)!==r&&ms.dirname(c)!==ms.dirname(r)&&n.push({file:a,kind:"pattern-deviation",description:`Only file in ${r}/ that depends on ${c}`,dep:c,actionTier:"signal",evidenceReasons:[`${o.length} sibling file(s) in ${r}/ were compared`,`${a} is the only non-skipped sibling depending on ${c}`],recommendation:"Review sibling ownership before changing this import; unique dependency shape can be intentional specialization."})}return n}function l2(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 u2(e){let t=new Map;for(let n of e.keys()){let r=ms.dirname(n),i=t.get(r);i||(i=[],t.set(r,i)),i.push(n)}return t}function d2(e,t){let n=new Map;for(let r of t)for(let i of e.get(r)??[])fs(i)||n.set(i,(n.get(i)??0)+1);return n}function m2(e,t){let n=new Map;return f2(e,n,t),n}function f2(e,t,n){for(let r of p2(e,n))uI(e,t,r.from_file,r.to_file)}function p2(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
|
|
788
|
+
FROM mentions m
|
|
789
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
790
|
+
JOIN documents d1 ON c.document_id = d1.id
|
|
791
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
792
|
+
JOIN (
|
|
793
|
+
SELECT m2.symbol_id, c2.document_id
|
|
794
|
+
FROM mentions m2
|
|
795
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
796
|
+
WHERE m2.role = 1
|
|
797
|
+
GROUP BY m2.symbol_id
|
|
798
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
799
|
+
JOIN documents d2 ON sym_def.document_id = d2.id
|
|
800
|
+
WHERE d1.id != d2.id
|
|
801
|
+
AND m.role != 1
|
|
802
|
+
${e.pathExclusionsFor("d1","d2")}
|
|
803
|
+
${n}`,...r)}function g2(e,t,n={}){new T(e).scanSourceReferences({paths:n.paths??M(e,{includeIgnored:!1}),includeRustAttributeNames:!0,identifierResolution:"permissive"},i=>{i.target.relativePath!==i.sourceFile&&(e.isIgnored(i.target.relativePath)||uI(e,t,i.sourceFile,i.target.relativePath))})}function uI(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 h2(e){return e.includes("types")||e.endsWith(".d.ts")}function y2(e,t,n){let r=Fo(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.isUsed)}function b2(e,t,n){let r=te(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.some(i=>i.used)}function S2(e,t,n){let r=te(e,t).filter(i=>i.sourcePath===n);return r.length>0&&r.every(i=>i.isTypeOnly===!0)}function x2(e){return e.endsWith(".vue")}function C2(e,t,n){let r=te(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 fs(e){let t=W(e);return!!(t==="entry"||t==="barrel"||t==="test"||t==="worker"||R2(ms.basename(e)))}function R2(e){return!!(e==="index.ts"||e==="index.js"||e==="cli.ts"||e==="main.ts"||e==="main.rs"||e.includes("worker.")||e.includes("postinstall.")||e==="health.ts"||e==="health.js")}import{basename as dI,extname as mI}from"path";function Zc(e,t,n,r,i,o){let s=new Set;I2(e,t,n,r)&&s.add(i);for(let a of o)a.value&&v2(s,a.label,a.value);return[...s].slice(0,6)}function v2(e,t,n){let r=w2(n);t.endsWith("name")&&E2(r)&&e.add(`${t} has type-guard boundary shape`);for(let i of r){let o=D2.get(i);o&&e.add(`${t} has ${o} term: ${i}`)}}function I2(e,t,n,r){if(n<=0)return!1;let i=Ee(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(Ui(s)===r)return!0;if(!s.startsWith("//")&&!s.startsWith("*")&&!s.startsWith("/*")&&!s.startsWith("@")&&!s.startsWith("#"))return!1}}return!1}function w2(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 E2(e){return e.some(t=>k2.has(t))&&e.some(t=>P2.has(t))}var D2=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"]]),k2=new Set(["can","has","is","should"]),P2=new Set(["access","api","auth","collision","expired","input","keyboard","overlap","permission","permissions","policy","projectile","response","route","routes","scope"]);function gs(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new T(e);return bt({candidates:()=>O2(e,s,n,r),orderCandidates:kc,scanLimit:o,profile:{name:"passthrough-candidates"},prepare:a=>s.calleeMap(a,{semantic:t?.semantic!==!1}),evaluate:(a,c)=>F2(e,a,c.get(a.symbolId)??[]),orderResults:(a,c)=>a.loc-c.loc||a.file.localeCompare(c.file),limit:i})}function F2(e,t,n){let r=N2(n);if(r.size!==1||!zl(e,t.relativePath,t.startLine,t.endLine))return null;let[,i]=[...r.entries()][0],o=T2(e,t,i),s=L2(e,t),a=o.length>0||s.length>0?"signal":"direct";return{symbol:t.symbol,shortName:I(t.symbol),file:t.relativePath,startLine:t.startLine,endLine:t.endLine,loc:O(t),forwardsTo:i.symbol,forwardsToShort:I(i.symbol),forwardsToFile:i.file,actionTier:a,boundaryEvidence:o,publicFacadeEvidence:s,recommendation:_2(a,o,s)}}function T2(e,t,n){return Zc(e,t.relativePath,t.startLine,"passthrough","explicit ignore-passthrough comment",[{label:"passthrough name",value:I(t.symbol)},{label:"callee name",value:I(n.symbol)},{label:"passthrough module",value:dI(t.relativePath,mI(t.relativePath))},{label:"callee module",value:dI(n.file,mI(n.file))}])}function _2(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(A2);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 L2(e,t){return hs(e,t)?wr(e,t.relativePath)?["exported passthrough is declared on the package public surface"]:ge(e,t.symbol,t.relativePath)?["exported passthrough matches configured or framework public entry surface"]:[]:[]}function hs(e,t){let n=Ee(e,t.relativePath);if(n.length===0)return!1;let r=F(t.symbol);if(!r)return!1;let i=n.slice(Math.max(0,t.startLine-2),t.startLine+1).join(`
|
|
804
|
+
`),o=H(r);return new RegExp(`^\\s*export\\s+(?:default\\s+)?(?:(?:async\\s+)?function\\s+${o}\\b|(?:const|let|var)\\s+${o}\\b)`,"m").test(i)?!0:M2(n,r)}function M2(e,t){if(!t)return!1;let n=new RegExp(`^\\s*export\\s*\\{[^}\\n]*\\b${H(t)}\\b`);return e.some(r=>n.test(r))}function A2(e){return e.includes("public surface")}function N2(e){let t=e.some(r=>oe(r.symbol))?e.filter(r=>oe(r.symbol)):e,n=new Map;for(let r of t)n.has(r.symbol)||n.set(r.symbol,r);return n}function O2(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:3,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRustTraitImplMembers:!0}).filter(i=>!Wi(e,i))}function ys(e,t){let{scope:n,minLoc:r=3,maxLoc:i=80,limit:o=30,includeLowConfidence:s=!1,scanLimit:a}=t??{},c=t?.semantic!==!1,l=new T(e),u=l.scopedDefinitions(n),d=J2(l,n),m={high:0,medium:1,low:2};return bt({candidates:()=>j2(e,l,u,{minLoc:r,maxLoc:i}),orderCandidates:(f,p)=>O(p)-O(f)||f.relativePath.localeCompare(p.relativePath),scanLimit:a,profile:{name:"stale-abstractions"},prepare:f=>{let p=$2(f),g=B2(e,l,f,p,{semantic:c}),y=f.filter(h=>{let C=el(e,h,g,p);return C.realConsumers.length<=1&&!C.transitivelyReachable&&fI(h,C.realConsumers.length,d)});return{consumerFileMap:g,singletonBackedClassIds:q2(e,l,u,y,{semantic:c}),candidateIndex:p}},evaluate:(f,p)=>{if(p.singletonBackedClassIds.has(f.symbolId))return null;let g=el(e,f,p.consumerFileMap,p.candidateIndex);if(g.transitivelyReachable||g.realConsumers.length>1||g.realConsumers.length===0&&g.barrelConsumers>0||!fI(g.definition,g.realConsumers.length,d))return null;let y=H2(e,g);return!s&&y.confidence==="low"?null:y},orderResults:(f,p)=>m[f.confidence]-m[p.confidence]||p.loc-f.loc||f.file.localeCompare(p.file)||f.startLine-p.startLine,limit:o})}function j2(e,t,n,r){return n.filter(i=>i.isTypeLike&&O(i)>=r.minLoc).filter(i=>O(i)<=r.maxLoc).filter(i=>!e.isIgnored(i.relativePath)).filter(i=>!i.relativePath.endsWith(".d.ts")).filter(i=>W(i.relativePath)!=="test").filter(i=>!ge(e,i.symbol,i.relativePath)).filter(i=>!Y2(i.symbol)).filter(i=>!t.hasSuppressionComment(i))}function Af(e,t,n,r){return hn(gn(e,t).forDefinitions(n,{semantic:r.semantic,sourceFallback:r.sourceFallback}))}function B2(e,t,n,r,i){let o=Af(e,t,n,{semantic:!1,sourceFallback:!1}),s=n.filter(l=>{let u=el(e,l,o,r);return u.realConsumers.length<=1&&!(u.realConsumers.length>0&&Nf(l.relativePath))}),a=i.semantic&&s.length>0?pn(o,Af(e,t,s,{semantic:!0,sourceFallback:!1})):o,c=s.filter(l=>el(e,l,a,r).realConsumers.length<=1);return pn(a,Af(e,t,c,{semantic:!1,sourceFallback:!0}))}function $2(e){let t=new Map;for(let n of e){let r=t.get(n.relativePath);r||(r=new Map,t.set(n.relativePath,r));let i=F(n.symbol);i&&r.set(i,n)}return t}function el(e,t,n,r){let o=[...n.get(t.symbolId)??new Set].filter(u=>u!==t.relativePath&&!e.isIgnored(u)),{realConsumers:s,barrelConsumers:a,importOnlyConsumers:c}=Bc(e,t,o),l=X2(e,t,n,r);return{definition:t,realConsumers:s,barrelConsumers:a+c,transitivelyReachable:l}}function H2(e,t){let n=gI(e,t.definition.relativePath,t.definition.startLine),r=Nf(t.definition.relativePath)?!0:Q2(e,t.definition),{confidence:i,reason:o}=Z2(t.realConsumers.length,n,r),s=U2(t.realConsumers.length,n,r);return{symbol:t.definition.symbol,shortName:I(t.definition.symbol),file:t.definition.relativePath,startLine:t.definition.startLine,endLine:t.definition.endLine,loc:O(t.definition),consumers:t.realConsumers.length,barrelConsumers:t.barrelConsumers,kind:n,definerUsesType:r,confidence:i,reason:o,actionTier:s.actionTier,stalenessKind:s.stalenessKind,recommendation:s.recommendation}}function U2(e,t,n){return e===0?{actionTier:"direct",stalenessKind:"unused-abstraction",recommendation:"Delete the abstraction or wire the missing consumer after checking public/package surfaces."}:t==="class"?{actionTier:"signal",stalenessKind:"one-to-one-class-encapsulation",recommendation:"Treat as weak signal: a one-consumer class may be intentional encapsulation, so inline only after reviewing ownership and state boundaries."}:n?{actionTier:"signal",stalenessKind:"single-consumer-abstraction",recommendation:"Review whether this single-consumer abstraction earns its name or should be folded into the owning feature."}:{actionTier:"signal",stalenessKind:"misplaced-single-consumer-type",recommendation:"Review moving or co-locating the type with its only real consumer; keep it here only if this file owns the public contract."}}function q2(e,t,n,r,i){let o=V2(e,G2(n),r),s=o.map(l=>l.singleton);if(o.length===0)return new Set;let a=hn(gn(e,t).forDefinitions(s,{semantic:i.semantic,sourceFallback:!0})),c=new Set;for(let{singleton:l,classId:u}of o)z2(e,l,a)&&c.add(u);return c}function G2(e){let t=new Map;for(let n of e){let r=F(n.symbol);r&&t.set(pI(n.relativePath,r),n)}return t}function V2(e,t,n){let r=[];for(let i of n){let o=W2(e,t,i);o&&r.push({singleton:o,classId:i.symbolId})}return r}function W2(e,t,n){if(gI(e,n.relativePath,n.startLine)!=="class")return null;let r=F(n.symbol);if(!r)return null;let i=K2(e,n.relativePath,r);return i?t.get(pI(n.relativePath,i))??null:null}function z2(e,t,n){let r=F(t.symbol),i=n.get(t.symbolId);return!r||!i?!1:[...i].some(o=>o!==t.relativePath&&!e.isIgnored(o)&&!tf(e,o,r))}function pI(e,t){return`${e}\0${t}`}function K2(e,t,n){let r=P(e,t);if(!r)return null;let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\bexport\\s+const\\s+([A-Za-z_$][\\w$]*)\\s*=\\s*new\\s+${i}\\s*\\(`);return r.match(o)?.[1]??null}function J2(e,t){return new Set(e.scopedDefinitions(t).filter(n=>n.isFunctionLike).map(n=>n.relativePath))}function Y2(e){let t=Re(e);if("kind"in t)return!1;let n=t.descriptors;if(n.length<2)return!1;let r=n[n.length-1],i=n[n.length-2];return r?.suffix==="type"&&i?.suffix==="type"}function Nf(e){let n=(e.split("/").pop()??"").replace(/\.[^.]+$/,"");return!!(n==="types"||n.endsWith("-types")||n==="models"||n==="schema"||n==="common"||n==="protocol"||n==="proto"||n==="dto"||n==="mod"||n==="contracts"||/(^|\/)types(\/|\.)/.test(e)||/(^|\/)models?(\/|\.)/.test(e)||/(^|\/)proto(?:col)?(\/|\.)/.test(e)||/(^|\/)schema(\/|\.)/.test(e)||/(^|\/)contracts?(\/|\.)/.test(e))}function fI(e,t,n){return!(Nf(e.relativePath)&&t>0||t===0&&n.has(e.relativePath))}function X2(e,t,n,r){let i=Jl(e,t.relativePath),o=F(t.symbol);if(!o)return!1;let s=r.get(t.relativePath);if(!s)return!1;let a=[...i.get(o)??[]],c=new Set;for(;a.length>0;){let l=a.pop();if(c.has(l))continue;c.add(l);let u=s.get(l);if(!u)continue;let d=n.get(u.symbolId);if(d){for(let m of d)if(m!==t.relativePath&&!e.isIgnored(m))return!0}for(let m of i.get(l)??[])a.push(m)}return!1}function gI(e,t,n){let r=P(e,t);if(!r)return"other";let i=r.split(`
|
|
805
|
+
`),o=Math.max(0,n-2),s=Math.min(i.length-1,n+2);for(let a=o;a<=s;a++){let l=(i[a]??"").replace(/^\s*\/\/.*$/g,"");if(/\b(?:export\s+)?(?:abstract\s+)?class\s+\w/.test(l))return"class";if(/\b(?:export\s+)?interface\s+\w/.test(l))return"interface";if(/\b(?:export\s+)?type\s+\w/.test(l))return"type";if(/\b(?:export\s+)?(?:const\s+)?enum\s+\w/.test(l))return"enum"}return"other"}function Q2(e,t){let n=P(e,t.relativePath);if(!n)return!1;let r=F(t.symbol);if(!r)return!1;let i=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`\\b${i}\\b`),s=n.split(`
|
|
806
|
+
`);for(let a=0;a<s.length;a++)if(!(a>=t.startLine&&a<=t.endLine)&&o.test(s[a]??""))return!0;return!1}function Z2(e,t,n){return e===0?{confidence:"high",reason:"unused \u2014 no consumers and defining file has no real usage"}:e===1&&t==="class"?{confidence:"low",reason:"1 consumer + class kind \u2014 likely 1:1 encapsulation, not over-abstraction"}:e===1&&!n?{confidence:"high",reason:"1 consumer + defining file never uses it \u2014 type belongs with its consumer"}:{confidence:"medium",reason:"1 consumer \u2014 single-use abstraction"}}import{basename as Mi,extname as tl}from"path";function bs(e,t){let{scope:n,maxLoc:r=15,limit:i=30,scanLimit:o}=t??{},s=new T(e),a=oJ(s.fileDependencyGraph(n));return bt({candidates:()=>nJ(e,s,n,r),orderCandidates:kc,scanLimit:o,profile:{name:"wrapper-candidates"},prepare:c=>({callerFileMap:eJ(e,s,c,{semantic:t?.semantic!==!1}),reverseFanIn:a}),evaluate:(c,l)=>tJ(e,s,c,l),orderResults:(c,l)=>l.callerFanIn-c.callerFanIn||l.loc-c.loc,limit:i})}function eJ(e,t,n,r){let i=gn(e,t),o=hn(i.forDefinitions(n,{semantic:!1,sourceFallback:!1})),s=[];r.semantic&&E("wrapper.semantic-candidates",()=>{s=n.filter(m=>Of(e,t,m,o).length<=1)},()=>({symbols:n.length,semanticCandidates:s.length}));let a=s.length===0?new Map:hn(i.forDefinitions(s,{semantic:!0,sourceFallback:!1})),c=a.size===0?o:pn(o,a),l=new Map(n.map(m=>[m.symbolId,m])),u=new Map;for(let m of n){let f=Of(e,t,m,c);if(f.length>1||(u.set(m.symbolId,m),f.length!==1))continue;let p=f[0],g=hI(e,m.symbolId,p);if(!g)continue;let y=yI(t,e,p,m.symbol,g);y?.isFunctionLike&&l.has(y.symbolId)&&u.set(y.symbolId,l.get(y.symbolId))}let d=[...u.values()];return d.length===0?c:pn(c,hn(i.forDefinitions(d,{semantic:!1,sourceFallback:!0})))}function tJ(e,t,n,r){let i=Of(e,t,n,r.callerFileMap);if(i.length!==1)return null;let o=i[0],s=hI(e,n.symbolId,o);if(!s)return null;let a=yI(t,e,o,n.symbol,s);if(a&&Or(a.symbol))return null;let{fanIn:c,source:l}=rJ(r.callerFileMap,r.reverseFanIn,o,a);if(l==="function"?c<=3:c<=5)return null;let u=aJ(e,n,o,a);return{symbol:n.symbol,shortName:I(n.symbol),file:n.relativePath,startLine:n.startLine,endLine:n.endLine,loc:O(n),singleCaller:a?.symbol??"",singleCallerShort:a?.isFunctionLike?I(a.symbol):Mi(o),callerFanIn:c,actionTier:u.length>0?"signal":"direct",boundaryEvidence:u}}function nJ(e,t,n,r){return t.productionCallableDefinitions({scope:n,minLoc:2,maxLoc:r,requireFunctionLikeSymbol:!0,excludeRootedSymbols:!0,excludeRustTraitImplMembers:!0}).filter(i=>!Wi(e,i))}function Of(e,t,n,r){let i=Mi(n.relativePath,tl(n.relativePath)),o=[...r.get(n.symbolId)??[]].filter(s=>s!==n.relativePath).filter(s=>Mi(s,tl(s))!==i).filter(s=>{let a=t.fileKind(s);return a!=="barrel"&&a!=="entry"&&a!=="test"});return Bc(e,n,o).realConsumers}function hI(e,t,n){return e.get(`SELECT c.start_line, c.end_line
|
|
807
|
+
FROM mentions m
|
|
808
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
809
|
+
JOIN documents d ON c.document_id = d.id
|
|
810
|
+
WHERE m.symbol_id = ? AND m.role != 1 AND d.relative_path = ?
|
|
811
|
+
LIMIT 1`,t,n)}function yI(e,t,n,r,i){let o=e.definitionsForFile(n),s=iJ(t,n,r,i.start_line,i.end_line);return At(o,s)}function rJ(e,t,n,r){if(r?.isFunctionLike){let i=[...e.get(r.symbolId)??[]].filter(o=>o!==r.relativePath);if(i.length>0)return{fanIn:i.length,source:"function"}}return{fanIn:sJ(t,n),source:"file"}}function iJ(e,t,n,r,i){let o=F(n);if(!o)return r;let s=an(e,t).get(o);if(!s||s.length===0)return r;for(let a of s)if(a>=r&&a<=i)return a;return r}function oJ(e){let t=new Map;for(let[n,r]of e){t.has(n)||t.set(n,t.get(n)??0);for(let i of r)t.set(i,(t.get(i)??0)+1)}return t}function sJ(e,t){let n=e.get(t)??0;if(n>0)return n;let r=Mi(t,tl(t)),i=0;for(let[o,s]of e)o!==t&&Mi(o,tl(o))===r&&s>i&&(i=s);return i}function aJ(e,t,n,r){return Zc(e,t.relativePath,t.startLine,"wrapper","explicit ignore-wrapper comment",[{label:"wrapper name",value:I(t.symbol)},{label:"caller name",value:r?.symbol?I(r.symbol):Mi(n)},{label:"wrapper path",value:t.relativePath},{label:"caller path",value:n}])}var cJ=25e3,lJ=2500,uJ=2500;function dJ(e){let t=Er(e);return t.symbols>=cJ||t.documents>=lJ?uJ:void 0}function jf(e,t={}){let{scope:n}=t,r=dJ(e),i=[],o=Dr(e,{scope:n,...he.dead,scanLimit:r});for(let s of o.symbols)Le(e,s.relativePath)||ge(e,s.symbol,s.relativePath)||s.kind==="dead-code"&&i.push(`dead:${s.relativePath}:${s.shortName}`);for(let s of Qo(e,{scope:n,...he.isolated,scanLimit:r}))Le(e,s.relativePath)||ge(e,s.symbol,s.relativePath)||i.push(`isolated:${s.relativePath}:${s.shortName}`);for(let s of Yo(e,{scope:n}))s.kind==="real"&&i.push(`cycle:${mJ(s.path)}`);for(let s of Zo(e,{scope:n,...he.similar,scanLimit:r}))i.push(`similar:${[s.symbolA,s.symbolB].sort().join("|")}`);for(let s of ds(e,{scope:n,...he.duplicateBodies,scanLimit:r}))i.push(`duplicate-bodies:${s.hash}:${s.functions.map(a=>a.symbol).sort().join("|")}`);for(let s of is(e,{scope:n,...he.extract,scanLimit:r}))i.push(`extract:${s.relativePath}:${s.shortName}`);for(let s of bs(e,{scope:n,...he.wrappers,scanLimit:r}))i.push(`wrapper:${s.file}:${s.shortName}`);for(let s of gs(e,{scope:n,...he.passthroughs,scanLimit:r}))i.push(`passthrough:${s.file}:${s.shortName}`);for(let s of ys(e,{scope:n,...he.stale,scanLimit:r}))i.push(`stale:${s.file}:${s.shortName}`);for(let s of ps(e,{scope:n,...he.drift,includePatternDeviations:!1,limit:Number.POSITIVE_INFINITY}).results)s.kind!=="architecture-violation"&&i.push(`drift:${s.kind}:${s.file}:${s.dep}`);return i.push(...Lc(kr(e,{scope:n}))),[...new Set(i.map(Mf))].sort()}function mJ(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 fJ(e,t={}){let n=jf(e,{scope:t.scope}),r=Li(e,t.path);return rt(r,{version:1,findings:n},{spacing:2,trailingNewline:!0}),{path:r,findingCount:n.length}}function Bf(e,t={}){return Qc(e,jf(e,{scope:t.scope}),{path:t.path})}function bI(e,t={}){let n=Lc(kr(e,{scope:t.scope}));return Qc(e,n,{path:t.path,accept:r=>r.startsWith(kt)})}var pJ=5;function Hf(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??Xn(e,{base:n}),d={available:u.note!==as,base:n,changedFiles:u.changedFiles,helpersChecked:0,skipped:[],findings:[]};if(!d.available||u.changedFiles.length===0)return d;let m=new T(e),f=new Set(u.changedFiles),p=new Map(u.renamedFiles.map(R=>[R.to,R.from])),g=t.baseContentAt??cs(e.config.projectRoot,n,ls(u)),y=xJ(m,f,p,g);if(y.length===0)return d;let h=y.slice(0,s);y.length>s&&(d.note=`helper scoring capped at ${s} of ${y.length} new symbols`);let C=m.calleeMap(h,{semantic:l}),b=h.map(R=>({def:R,callees:Ac((C.get(R.symbolId)??[]).map(D=>D.symbol))})),S=Ei(e),x,v=()=>(x??=S.calleeIndex({minCallees:Math.min(3,i),scanLimit:c,semantic:l}),x);for(let{def:R,callees:D}of b){let w=I(R.symbol);if(D.size<i){d.skipped.push({helperShortName:w,helperFile:R.relativePath,reason:`fewer than ${i} meaningful callees \u2014 too small to score`});continue}let k=v(),L=SJ(D,k);if(L===0){d.skipped.push({helperShortName:w,helperFile:R.relativePath,reason:"helper callee pattern is all project-wide infrastructure \u2014 too generic to score"});continue}let ne=CJ(e,R.symbolId);if(ne.length===0){d.skipped.push({helperShortName:w,helperFile:R.relativePath,reason:"no references yet \u2014 covered by the new-dead check"});continue}d.helpersChecked+=1;let ee=gJ({candidateIndex:k,changed:f,helperCallees:D,helperFile:R.relativePath,helperSymbol:R.symbol,minContainment:r,minSiteCoverage:o,migratedFiles:ne});ee.length!==0&&(ee.sort((_,ue)=>SI(ue.migrationScope)-SI(_.migrationScope)||ue.containment-_.containment||ue.siteCoverage-_.siteCoverage||_.file.localeCompare(ue.file)),d.findings.push({helperSymbol:R.symbol,helperShortName:w,helperFile:R.relativePath,helperShape:"specific-callee-cluster",helperCalleeCount:D.size,specificHelperCalleeCount:L,migratedFiles:ne.sort(),leftovers:ee.slice(0,pJ)}))}return d.findings.sort((R,D)=>(D.leftovers[0]?.containment??0)-(R.leftovers[0]?.containment??0)||R.helperFile.localeCompare(D.helperFile)),d.findings=d.findings.slice(0,a),d}function gJ(e){let t=[],n=hJ(e.helperSymbol,e.helperFile,e.migratedFiles),r=new Set;for(let i of e.helperCallees)for(let o of e.candidateIndex.candidateIndexesByCallee.get(i)??[])r.add(o);for(let i of r){let o=e.candidateIndex.corpus[i];if(o.symbol===e.helperSymbol||e.changed.has(o.file)||o.callees.has(e.helperSymbol))continue;let s=fR(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=yJ(n,o.symbol,o.file);t.push({symbol:o.symbol,shortName:I(o.symbol),file:o.file,...l,containment:s,siteCoverage:c,uniqueSiteCalleeCount:Math.max(0,o.callees.size-a.length),sharedCallees:a.map(I).sort()})}return t}function SI(e){return e==="same-scope"?2:e==="unknown"?1:0}function hJ(e,t,n){let r=new Set([...$f(t),...Uf(F(e))]);for(let i of n)for(let o of $f(i))r.add(o);return r}function yJ(e,t,n){let r=new Set([...$f(n),...Uf(F(t))]);if(e.size===0||r.size===0)return{migrationScope:"unknown",migrationScopeReasons:["insufficient path/name tokens to infer migration scope"]};let i=[...r].filter(o=>e.has(o)).sort();return i.length>0?{migrationScope:"same-scope",migrationScopeReasons:[`shares migration-scope token(s): ${i.slice(0,5).join(", ")}`]}:{migrationScope:"possible-subtype",migrationScopeReasons:["no path/name tokens shared with the helper or already migrated files"]}}var bJ=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 $f(e){return Uf(e.replace(/\.[^.]+$/,""))}function Uf(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1&&!bJ.has(t))}function SJ(e,t){let n=0;for(let r of e)(t.docFreq.get(r)??0)<=t.ubiquityThreshold&&(n+=1);return n}function xJ(e,t,n,r){return e.productionCallableDefinitions({files:[...t],requireFunctionLikeSymbol:!0}).filter(i=>{if(!t.has(i.relativePath))return!1;let o=n.get(i.relativePath)??i.relativePath,s=r(o);return s===null||!new RegExp(`\\b${H(i.leaf)}\\b`).test(s)})}function CJ(e,t){return e.all(`SELECT DISTINCT ref_d.relative_path
|
|
812
|
+
FROM mentions m
|
|
813
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
814
|
+
JOIN documents ref_d ON c.document_id = ref_d.id
|
|
815
|
+
WHERE m.symbol_id = ?
|
|
816
|
+
AND m.role != 1
|
|
817
|
+
${e.pathExclusionsFor("ref_d")}`,t).map(r=>r.relative_path)}function qf(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new T(e);return bt({candidates:()=>o.productionCallableDefinitions({scope:n,files:t.files,minLoc:2,excludeRootedSymbols:!0,requireFunctionLikeSymbol:!0}),filterCandidate:s=>RJ(s.relativePath),scanLimit:i,profile:{name:"unused-params"},evaluate:s=>{let a=z(e,s.relativePath)?.callables.find(u=>u.startLine===s.startLine&&u.endLine===s.endLine);if(!a||a.params.length===0||a.params.some(u=>!u.simple)||a.paramsEndLine>=a.endLine)return null;let c=an(e,s.relativePath),l=[];for(let u=a.params.length-1;u>=0;u--){let d=a.params[u];if(d.name===""||d.name.startsWith("_")||vJ(c.get(d.name),a.paramsEndLine,a.endLine))break;l.unshift(d.name)}return l.length===0?null:{symbol:s.symbol,shortName:I(s.symbol),file:s.relativePath,startLine:s.startLine,endLine:s.endLine,paramCount:a.paramCount,unusedTrailing:l}},orderResults:(s,a)=>a.unusedTrailing.length-s.unusedTrailing.length||s.file.localeCompare(a.file)||s.startLine-a.startLine,limit:r})}function RJ(e){let t=N(e);return t==="typescript"||t==="tsx"||t==="javascript"}function vJ(e,t,n){return e?e.some(r=>r>t&&r<=n):!1}import{existsSync as IJ,readdirSync as wJ,readFileSync as EJ}from"fs";import{createHash as DJ}from"crypto";import{join as zf}from"path";function Vf(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(Gf(l));break;case"unsupported-future":i+=1,s.push(Gf(l));break;case"malformed":o+=1,s.push(Gf(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 Uhe(e,t){if(!t.complete)return`${e} coverage is incomplete: accepted ${t.accepted} of ${t.total} record(s); omitted ${t.omitted} (${t.unsupportedOlder} unsupported older, ${t.unsupportedFuture} unsupported future, ${t.malformed} malformed).`}function Gf(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 CI=zf(".scipquery","suppressions"),xI="scip-query-suppression",Wf=1;function kJ(e){return zf(e,CI)}function PJ(e){if(e.id&&e.id.trim()!=="")return`${e.id.trim()}.json`;let t=`${e.check??""}\0${e.file??""}`;return`CHECK-${DJ("sha256").update(t).digest("hex").slice(0,12).toUpperCase()}.json`}function FJ(e){return PJ(e).slice(0,-5)}function TJ(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return{state:"malformed",error:"not a suppression object"};let n=e;if(n.schemaVersion===void 0&&(n.kind!==void 0||n.suppressionIdentity!==void 0||n.writer!==void 0))return{state:"malformed",error:"suppression envelope metadata requires schemaVersion"};if(n.schemaVersion!==void 0){if(!Number.isSafeInteger(n.schemaVersion))return{state:"malformed",error:"schemaVersion must be a positive safe integer"};if(n.schemaVersion!==Wf)return{state:n.schemaVersion>Wf?"unsupported-future":"unsupported-older",error:`unsupported schemaVersion ${String(n.schemaVersion)}`};if(n.kind!==void 0&&n.kind!==xI)return{state:"malformed",error:`kind must be ${xI}`}}if(typeof n.reason!="string"||n.reason.trim()==="")return{state:"malformed",error:"missing reason"};if(!n.id&&!n.check)return{state:"malformed",error:"needs an id or a check"};let r=_J(n);if(n.schemaVersion===void 0)return{state:"legacy",suppression:r,record:n,schemaVersion:0};let i=FJ(r);return n.suppressionIdentity!==i||t!==void 0&&n.suppressionIdentity!==t?{state:"malformed",error:"suppressionIdentity does not match the suppression target or filename"}:!n.writer||n.writer.tool!=="scip-query"||typeof n.writer.version!="string"||n.writer.version.trim()===""?{state:"malformed",error:"missing valid writer metadata"}:typeof n.createdAt!="string"||!Number.isFinite(Date.parse(n.createdAt))?{state:"malformed",error:"missing valid createdAt timestamp"}:n.updatedAt!==void 0&&(typeof n.updatedAt!="string"||!Number.isFinite(Date.parse(n.updatedAt)))?{state:"malformed",error:"invalid updatedAt timestamp"}:{state:"current",suppression:r,record:n,schemaVersion:Wf}}function RI(e){let t=kJ(e);if(!IJ(t))return{suppressions:[],compatibility:Vf([]),warnings:[]};let n=[],r=[];for(let o of wJ(t).sort()){if(!o.endsWith(".json"))continue;let s=zf(t,o),a=`${CI}/${o}`,c;try{c=JSON.parse(EJ(s,"utf-8"))}catch{r.push({path:a,state:"malformed",reason:"malformed JSON"});continue}let l=TJ(c,o.slice(0,-5));if("error"in l){r.push({path:a,state:l.state,reason:l.error});continue}r.push({path:a,state:l.state}),n.push(l.suppression)}let i=Vf(r);return{suppressions:n,compatibility:i,warnings:i.issues.map(o=>`${o.path}: ${o.reason} \u2014 ignored`)}}function _J(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}:{}}}var MJ=["echo","incomplete-migration","co-change-partner","twin-partner","coverage-contract","architecture","doc-reference","unused-params","new-dead","baseline"];function AJ(e,t={}){let n=t.base??"HEAD",{minTogether:r=6,minConfidence:i=.6,maxEchoChecks:o=Number.POSITIVE_INFINITY,maxHelpers:s=Number.POSITIVE_INFINITY,minSimilarity:a=.8,includeBaseline:c=!1,scanLimit:l}=t,u=t.semantic!==!1,d=t.historyMode??"bounded",m=new Set(t.skip??[]),f=RI(e.config.projectRoot),p=Xn(e,{base:n}),g=Pi(e,{base:n,plan:p}),y=g.changedFiles,h=new Set(y),C=new Set(p.changedFileLines),b=new Set([...h,...C]),S=cs(e.config.projectRoot,n,ls(p,y)),x=uY(e.config.projectRoot,n,p,S),v={base:n,changedFiles:y,changedSymbols:g.changedSymbols.length,checksRun:[],skipped:[],suppressed:[],findings:[],attributionNotes:g.attributionNotes,rootCauseGroups:[],recordCompatibility:{suppressions:f.compatibility},note:g.summary.note};if(y.length===0)return v;let R=(D,w)=>{if(m.has(D)){v.skipped.push({check:D,reason:"skipped via --skip"});return}let k=v.findings.length,L=v.skipped.length,ne=v.checksRun.length;E(`diff-gate.check.${D}`,w,()=>({check:D,changedFiles:y.length,changedSymbols:g.changedSymbols.length,findingsAdded:v.findings.length-k,skippedAdded:v.skipped.length-L,checksRunAdded:v.checksRun.length-ne}))};return R("echo",()=>HJ(e,g.changedSymbols,h,x,o,a,l,u,v)),R("incomplete-migration",()=>zJ(e,n,p,s,l,u,S,v)),R("co-change-partner",()=>KJ(e,b,r,i,d,v)),R("twin-partner",()=>JJ(e,g.changedSymbols,h,l,v)),R("coverage-contract",()=>YJ(e,b,v)),R("architecture",()=>fY(e,v)),R("doc-reference",()=>tY(e,h,C,p.changedRanges,p.renamedFiles,v)),R("unused-params",()=>oY(e,y,v)),R("new-dead",()=>sY(e,g.changedSymbols,x,v)),c&&R("baseline",()=>mY(e,v)),BJ(v,[...e.config.suppressions??[],...f.suppressions]),v.rootCauseGroups=jJ(v.findings),v}function NJ(e){return e.checksRun.length===0&&e.note===as}function OJ(e){return e.filter(t=>!t.advisory)}function jJ(e){let t=new Map;for(let n of e){let r=n.groupKey??`${n.check}:${n.id}`,i=t.get(r);i||(i={groupKey:r,check:n.check,severity:n.severity,actionTier:n.actionTier,sourceAnalyzer:n.sourceAnalyzer,rootCauseKey:n.rootCauseKey,count:0,findingIds:[],files:new Set,relatedFiles:new Set,message:n.message,remediation:n.remediation},t.set(r,i)),i.count+=1,i.findingIds.push(n.id),i.severity=kI(i.severity,n.severity),i.actionTier=PI(i.actionTier,n.actionTier),n.file&&i.files.add(n.file);for(let o of n.relatedFiles??[])i.relatedFiles.add(o)}return[...t.values()].map(n=>({...n,files:[...n.files].sort(),relatedFiles:[...n.relatedFiles].sort()})).sort((n,r)=>r.count-n.count||nl(r.severity)-nl(n.severity)||n.groupKey.localeCompare(r.groupKey))}function kI(e,t){return nl(t)>nl(e)?t:e}function nl(e){return e==="error"?2:e==="warning"?1:0}function PI(e,t){return e?t&&vI(t)>vI(e)?t:e:t}function vI(e){return e==="direct"?2:e==="signal"?1:0}function BJ(e,t){if(t.length===0||e.findings.length===0)return;let n=[];for(let r of e.findings){let i=t.find(o=>$J(o,r));i?e.suppressed.push({finding:r,suppression:i}):n.push(r)}e.findings=n}function $J(e,t){return!e.reason||e.reason.trim()===""||e.expiresAt&&Date.parse(e.expiresAt)<=Date.now()||e.id&&e.id!==t.id&&!t.legacySuppressionIds?.includes(e.id)||e.check&&e.check!==t.check||e.file&&e.file!==t.file?!1:!!(e.id||e.check)}function Kt(e,t){e.findings.push({...t,suppressionHint:`scip-query: ignore ${t.check} ${t.id} -- <reason>`})}function HJ(e,t,n,r,i,o,s,a,c){c.checksRun.push("echo");for(let l of t.slice(0,i)){if(!fe(l.symbol)||r(l))continue;let u=Ff(e,l.symbol,{maxLoc:15,scanLimit:s}).filter(h=>!n.has(h.file)).slice(0,5).map(h=>({otherFile:h.file,otherShort:h.shortName,otherSymbol:h.symbol,similarity:1,similarityBasis:"exact-body",sharedEvidence:[`exact normalized body (${h.loc} LOC)`]}));if(u.length>0){let h=Pe("echo",l.symbol,l.file),C=Pe("echo",l.symbol,l.file,...u.map(S=>`${S.otherSymbol}|${S.otherFile}`).sort()),b=u[0];Kt(c,{id:h,legacySuppressionIds:C===h?void 0:[C],groupKey:h,actionTier:"direct",check:"echo",severity:"warning",evidence:"heuristic",confidence:1,file:l.file,symbol:l.symbol,relatedFiles:[...new Set(u.map(S=>S.otherFile))].sort(),sourceAnalyzer:"duplicate-bodies",rootCauseKey:`${l.symbol}:${b.otherSymbol}`,message:wI(l,u),why:EI(l,u),remediation:DI("direct",l.shortName,b.otherShort)});continue}let d=Mc(e,l.symbol,{minSimilarity:o,limit:5,scanLimit:s,semantic:a,sourceCandidateMode:"target-pruned"}),m=[];for(let h of d){let C=h.fileA===l.file?h.fileB:h.fileA,b=h.fileA===l.file?h.shortNameB:h.shortNameA,S=h.fileA===l.file?h.symbolB:h.symbolA;n.has(C)||m.push({otherFile:C,otherShort:b,otherSymbol:S,similarity:h.similarity,similarityBasis:h.similarityBasis??"callees",sharedEvidence:h.sharedCallees})}if(m.length===0)continue;let f=m[0],p=Pe("echo",l.symbol,l.file,...m.map(h=>`${h.otherSymbol}|${h.otherFile}`).sort()),g=Pe("echo",l.symbol,l.file),y=UJ(l,m);Kt(c,{id:g,legacySuppressionIds:p===g?void 0:[p],groupKey:g,actionTier:y,check:"echo",severity:"warning",evidence:"heuristic",confidence:f.similarity,file:l.file,symbol:l.symbol,relatedFiles:[...new Set(m.map(h=>h.otherFile))].sort(),message:wI(l,m),why:EI(l,m),remediation:DI(y,l.shortName,f.otherShort)})}t.length>i&&c.skipped.push({check:"echo",reason:`echo check capped at ${i} of ${t.length} changed symbols`})}function UJ(e,t){return t.some(r=>qJ(e.symbol,r))?"direct":"signal"}function qJ(e,t){if(t.similarityBasis==="exact-body")return!0;if(t.similarityBasis!=="source-tokens"||t.similarity<.98||t.sharedEvidence.length>8)return!1;let n=F(e),r=F(t.otherSymbol);return!n||!r?!1:n===r?!0:WJ(t.sharedEvidence)?!1:GJ(n,r)}function GJ(e,t){let n=II(e),r=II(t);if(n.length===0||r.length===0)return!1;let i=new Set(r),o=n.filter(s=>i.has(s)).length;return o>=2&&o/Math.min(n.length,r.length)>=.5}function II(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).map(t=>t.toLowerCase()).filter(t=>t.length>=2)}var VJ=new Set(["bytes","crypto","hex","num","random","secret","to","token"]);function WJ(e){return e.length>=3&&e.every(t=>VJ.has(t.toLowerCase()))}function wI(e,t){let n=t[0],r=Math.round(n.similarity*100);return t.length===1?`${e.shortName} (${e.file}) is ${r}% similar to established ${n.otherShort} (${n.otherFile})`:`${e.shortName} (${e.file}) resembles ${t.length} established symbol(s); strongest is ${r}% similar to ${n.otherShort} (${n.otherFile})`}function EI(e,t){let n=[`${e.shortName} was changed in this diff.`];for(let r of t.slice(0,3))n.push(`${r.otherShort} is outside this diff and scored ${Math.round(r.similarity*100)}% similar by ${r.similarityBasis} evidence.`),n.push(`Shared evidence: ${r.sharedEvidence.slice(0,5).join(", ")||"(none listed)"}.`);return t.length>3&&n.push(`${t.length-3} additional similar match(es) grouped into this finding.`),n}function DI(e,t,n){return e==="direct"?`Extract or reuse the shared behavior with ${n}, or keep the duplicate with a suppression reason.`:`Review whether ${t} is intentionally parallel to the established implementation(s); extract shared behavior only if the product semantics match.`}function zJ(e,t,n,r,i,o,s,a){let c=Hf(e,{base:t,maxHelpers:r,diffPlan:n,scanLimit:i,semantic:o,baseContentAt:s});if(!c.available){a.skipped.push({check:"incomplete-migration",reason:"no git history"});return}a.checksRun.push("incomplete-migration"),c.note&&a.skipped.push({check:"incomplete-migration",reason:c.note});for(let l of c.findings){let u=l.leftovers.map(h=>`${h.shortName} (${h.file}, ${Math.round(h.containment*100)}% helper / ${Math.round(h.siteCoverage*100)}% site, ${h.migrationScope})`).join(", "),d=l.leftovers.map(h=>`${h.shortName}: ${h.migrationScope} (${h.migrationScopeReasons[0]})`).join("; "),m=[...l.migratedFiles,...l.leftovers.map(h=>h.file)],f=l.leftovers.length===0?void 0:Math.max(...l.leftovers.map(h=>Math.min(h.containment,h.siteCoverage))),p=l.leftovers.some(h=>h.migrationScope==="possible-subtype"),g=Pe("incomplete-migration",l.helperSymbol,l.helperFile,m.join("|")),y=Pe("incomplete-migration",l.helperSymbol,l.helperFile);Kt(a,{id:y,legacySuppressionIds:g===y?void 0:[g],check:"incomplete-migration",severity:"warning",evidence:"heuristic",confidence:f,file:l.helperFile,symbol:l.helperSymbol,relatedFiles:m,message:`new helper ${l.helperShortName} (${l.helperFile}) is wired into ${l.migratedFiles.length} file(s), but ${l.leftovers.length} similar un-migrated site(s) remain: ${u}`,why:[`${l.helperShortName} is new in this diff and already referenced by ${l.migratedFiles.join(", ")}.`,`Helper shape: ${l.helperShape}; ${l.specificHelperCalleeCount}/${l.helperCalleeCount} helper callees are specific enough to score.`,`Unchanged site(s) still contain the helper's callee pattern: ${u}.`,`Migration scope hints: ${d}.`],remediation:p?`Migrate same-scope sites to ${l.helperShortName}; review possible subtype/variant sites before applying the helper.`:`Migrate the remaining sites to ${l.helperShortName}, or confirm they are intentionally different.`})}}function KJ(e,t,n,r,i,o){let s=Xe(e,{historyMode:i}).directionalCoChangePairsForFiles(t,{minTogether:n,minConfidence:0,maxFilesPerCommit:20});if(!s){o.skipped.push({check:"co-change-partner",reason:"no git history"});return}o.checksRun.push("co-change-partner");let a=new Set,c;for(let l of s){let u=t.has(l.fileA),d=t.has(l.fileB);if(u===d)continue;let m=u?l.fileA:l.fileB,f=u?l.fileB:l.fileA,p=u?l.changesA:l.changesB,g=p>0?l.together/p:0;if(g<r||yf(f)||yf(m)||!rl(`${e.config.projectRoot}/${f}`))continue;let y=`${m}|${f}`;if(a.has(y))continue;a.add(y);let h=Pe("co-change-partner",m,f,String(l.together)),C=Pe("co-change-partner",m,f),b=bf(m,f),S=Sf({fileA:m,fileB:f,together:l.together,confidence:g,commitScope:l.commitScope,recency:l.recency,subjectContext:l.subjectContext},b,(c??=xf(e))(m,f)),x=[m,f].sort().join("|");o.findings.push({id:C,legacySuppressionIds:h===C?void 0:[h],check:"co-change-partner",severity:"warning",evidence:"change-graph",actionTier:"signal",groupKey:`co-change-partner:${x}`,confidence:g,file:m,relatedFiles:[f],sourceAnalyzer:"co-change",rootCauseKey:x,partnerClass:b.partnerClass,partnerClassReasons:b.reasons,commitScope:l.commitScope,recency:l.recency,focusedTogether:l.focusedTogether,broadTogether:l.broadTogether,broadCommitRatio:l.broadCommitRatio,lastTogetherAt:l.lastTogetherAt,recentTogether:l.recentTogether,subjectContext:l.subjectContext,...S?{declaredCouplingSuggestion:S}:{},message:`${m} changed, but ${f} did not \u2014 they change together ${l.together}x (${Math.round(g*100)}% of the time)`,why:[`${m} is in this diff and ${f} is not.`,`Git history shows ${l.together} co-change(s), which is ${Math.round(g*100)}% of changes to the edited side.`,`History context: ${XJ(l)}.`,`Subject context: ${QJ(l.subjectContext)}.`,...ZJ(l),`Partner class: ${b.partnerClass} (${b.reasons.join("; ")}).`],remediation:S?`Update ${f} alongside this change, declare the coupling "${S.name}", or confirm the coupling no longer holds.`:`Update ${f} alongside this change, or confirm the coupling no longer holds.`})}}function JJ(e,t,n,r,i){i.checksRun.push("twin-partner");let o=_i(e,{scanLimit:r}).filter(c=>c.relationship==="divergent"||c.relationship==="identical");if(o.length===0)return;let s=new Map;for(let c of o)for(let l of c.members)s.set(l.symbol,c);let a=new Set;for(let c of t){if(!fe(c.symbol))continue;let l=s.get(c.symbol);if(!l)continue;let u=l.members.filter(p=>p.symbol!==c.symbol&&!n.has(p.file));if(u.length===0)continue;let d=[c.symbol,...u.map(p=>p.symbol)].sort().join("|");if(a.has(d))continue;a.add(d);let m=u[0],f=Pe("twin-partner",c.symbol,c.file,m.symbol);Kt(i,{id:f,groupKey:`twin-partner:${d}`,check:"twin-partner",severity:"warning",evidence:"heuristic",actionTier:"signal",advisory:!0,confidence:l.relationship==="identical"?1:Math.max(0,1-l.maxDivergence),file:c.file,symbol:c.symbol,relatedFiles:u.map(p=>p.file).sort(),sourceAnalyzer:"twin-drift",rootCauseKey:d,message:`${c.shortName} (${c.file}) changed but its same-name twin ${m.shortName} (${m.file}) did not \u2014 verify the change shouldn't apply to both, or consolidate them.`,why:[`${c.symbol} is in this diff.`,`${m.symbol} shares its (near-)name and is classified '${l.relationship}' with it, but ${m.file} is not in this diff.`,l.relationship==="divergent"?`The two bodies already diverge (~${Math.round(l.maxDivergence*100)}% token difference) \u2014 this diff may widen or narrow that drift.`:"The two bodies were byte-identical before this diff.","Advisory: twin-partner never fails the gate by itself \u2014 see the twin-partner entry in the diff-gate checks table."],remediation:`Update ${m.file} alongside this change, consolidate ${c.shortName}/${m.shortName} into one helper, or confirm the twin should diverge on purpose.`})}}function YJ(e,t,n){n.checksRun.push("coverage-contract");let r=e.config.coverageContracts??[];for(let i of r){if(!iI(i,t))continue;let o=Lf(e,i);if(o.status==="ok")continue;let s=Pe("coverage-contract",i.name,i.file);Kt(n,{id:s,groupKey:`coverage-contract:${i.name}`,check:"coverage-contract",severity:o.status==="unavailable"?"warning":"error",evidence:"graph-fact",actionTier:"direct",file:i.file,sourceAnalyzer:"coverage-contracts",rootCauseKey:i.name,message:oI(o),why:[`Contract "${i.name}" declares that ${i.file} (${i.keys.type}) must track ${i.mustEqual.type}.`,o.status==="unavailable"?`The declared side could not be evaluated: ${o.unavailableReason}.`:`Missing: ${o.missing.join(", ")||"none"}. Extra: ${o.extra.join(", ")||"none"}.`,"Either side of this contract changed in this diff."],remediation:o.status==="unavailable"?"Investigate why the declared key set could not be parsed (see the reason above) \u2014 do not treat this as a pass.":`Update ${i.file} so its ${i.keys.type==="object-literal-keys"||i.keys.type==="string-array"?i.keys.identifier:i.keys.marker} matches ${i.mustEqual.type}, or fix the ground-truth source if the declared set is right.`})}}function XJ(e){return`${e.commitScope}/${e.recency}; ${e.focusedTogether} focused, ${e.broadTogether} broad-sweep (${Math.round(e.broadCommitRatio*100)}% broad), ${e.recentTogether} recent, last ${eY(e.lastTogetherAt)}`}function QJ(e){let t=e.subjectLabels.length>0?e.subjectLabels.slice(0,5).join(", "):"none inferred",n=e.issueRefs.length>0?e.issueRefs.slice(0,5).join(", "):"none",r=e.sampleSubjects.length>0?e.sampleSubjects.slice(0,3).map(i=>`"${i}"`).join("; "):"none";return`labels ${t}; refs ${n}; samples ${r}; external issue/PR labels ${e.externalIssueLabelStatus}`}function ZJ(e){let t=[];return e.commitScope==="broad-sweep"&&t.push("Broad-sweep history is weaker than focused co-edits; confirm this is a real coordination contract."),e.recency==="stale"&&t.push("The pair has no co-change in the recent history window; confirm the coupling still holds."),t}function eY(e){return e<=0?"unknown":new Date(e*1e3).toISOString().slice(0,10)}var Kf=3;function tY(e,t,n,r,i,o){o.checksRun.push("doc-reference");let s=yn.referenceTargets(e,t,r);if(s.size===0)return;let a=new Set(i.map(l=>l.from)),c=[];for(let l of Av(e,s))n.has(l.doc)||Jc(e,l.doc)||c.push(nY(e,l,a));for(let l of rY(c))Kt(o,l)}function nY(e,t,n){let r=t.citedClaims.length>0?t.citedClaims:yn.citationContexts(e,t.doc,t.cited),i=yn.classifyCitation(r),o=yn.hasLineAnchoredCitation(t.citations),s=t.cited.some(d=>n.has(d)||!rl(`${e.config.projectRoot}/${d}`)),a=!(o||s),c=t.cited[0]??"",l=Pe("doc-reference",t.doc,t.cited.join("|")),u=Pe("doc-reference",t.doc,c);return{id:u,legacySuppressionIds:l===u?void 0:[l],check:"doc-reference",severity:"warning",evidence:"change-graph",actionTier:i.actionTier,groupKey:`doc-reference:${c}`,rootCauseKey:c,confidence:1,file:t.doc,relatedFiles:t.cited,citationKind:i.citationKind,citationKindReasons:i.reasons,citedClaims:r,...a?{advisory:!0}:{},message:`${t.doc} cites ${t.cited.join(", ")} as ${yn.citationKindLabel(i.citationKind)} \u2014 changed in this diff, doc untouched`,why:[`${t.cited.join(", ")} changed in this diff.`,`${t.doc} cites the changed file(s) but was not updated in the same diff.`,...i.reasons.map(d=>`Citation kind evidence: ${d}`),a?"Advisory: bare file-mention citation (no line anchor, cited file still present under the same path) \u2014 21.2 calibration found this citation shape low-precision; verify at your leisure.":o?"Blocking: citation includes a line anchor that may now point at the wrong lines.":"Blocking: the cited file was deleted or renamed in this diff \u2014 the citation almost certainly needs an update."],remediation:yn.citationRemediation(i.citationKind,t.doc)}}function rY(e){let t=new Map;for(let r of e){let i=r.rootCauseKey??"",o=t.get(i);o?o.push(r):t.set(i,[r])}let n=[];for(let[r,i]of t)i.length<=Kf?n.push(...i):n.push(iY(r,i));return n}function iY(e,t){let n=[...t].sort((u,d)=>(u.file??"").localeCompare(d.file??"")),r=n.slice(0,Kf).map(u=>({doc:u.file??"",citedClaims:u.citedClaims??[]})),i=n.length-r.length,o=n.every(u=>u.advisory===!0),s=n.reduce((u,d)=>kI(u,d.severity),"info"),a=n.reduce((u,d)=>PI(u,d.actionTier),void 0),c=n.map(u=>u.file??"").filter(u=>u.length>0),l=[...new Set(n.flatMap(u=>[u.id,...u.legacySuppressionIds??[]]))];return{id:Pe("doc-reference","hub-cluster",e),memberFindingIds:l,check:"doc-reference",severity:s,evidence:"change-graph",actionTier:a,groupKey:`doc-reference:${e}`,rootCauseKey:e,confidence:1,file:r[0]?.doc,relatedFiles:[e],citationCount:n.length,citationExemplars:r,suppressedCount:i,...o?{advisory:!0}:{},message:`${e} is cited by ${n.length} doc(s) changed in this diff, doc(s) untouched \u2014 showing ${r.length} example(s), ${i} more damped`,why:[`${e} changed in this diff.`,`${n.length} doc(s) cite it but were not updated in the same diff: ${c.join(", ")}.`,...r.map(u=>`Example \u2014 ${u.doc}: ${u.citedClaims[0]??"(no captured citation text)"}`),`${i} additional doc(s) also cite this file, past the per-hub-file cascade cap (${Kf}) \u2014 not silently dropped: counted in citationCount/suppressedCount and individually addressable via memberFindingIds.`,o?"Advisory: every citation in this cluster is a bare file-mention (no line anchor, cited file still present).":"Blocking: at least one citation in this cluster is line-anchored or cites a deleted/renamed file."],remediation:`Review the ${r.length} example doc(s) above; ${n.length} total doc(s) cite ${e} the same way \u2014 see citationExemplars and memberFindingIds in --json for the complete list.`}}function oY(e,t,n){n.checksRun.push("unused-params");for(let r of qf(e,{files:t,limit:50})){let i=Pe("unused-params",r.symbol,r.file,r.unusedTrailing.join("|")),o=Pe("unused-params",r.symbol,r.file);Kt(n,{id:o,legacySuppressionIds:i===o?void 0:[i],check:"unused-params",severity:"warning",evidence:"heuristic",confidence:.85,file:r.file,startLine:r.startLine,endLine:r.endLine,symbol:r.symbol,message:`${r.shortName} (${r.file}) has trailing unused parameter(s): ${r.unusedTrailing.join(", ")}`,why:[`${r.shortName} is in a changed file.`,`The trailing parameter(s) ${r.unusedTrailing.join(", ")} are not referenced in the function body.`],remediation:"Drop the unused trailing parameters and their call-site arguments."})}}function sY(e,t,n,r){r.checksRun.push("new-dead");let i=new T(e),o=qr(e.config.projectRoot),s=o.length>1;for(let a of t){if(n(a)||a.fanIn>0||i.fileKind(a.file)==="test"||Le(e,a.file)||ge(e,a.symbol,a.file)||lY(a.symbol))continue;let c=Pe("new-dead",a.symbol,a.file),l=s&&aY(o,a.file)&&cY(e,a.symbol);Kt(r,{id:c,check:"new-dead",severity:"warning",evidence:l?"heuristic":"graph-fact",confidence:l?.4:.9,file:a.file,symbol:a.symbol,message:l?`${a.shortName} (${a.file}) unconfirmed (cross-package ambiguous-name resolution gap): zero indexed consumers found, but this name is ambiguous project-wide and lives in a workspace package \u2014 verify manually before treating as dead`:`${a.shortName} (${a.file}) was changed but has zero indexed consumers`,why:l?[`${a.shortName} is a changed production symbol in a workspace package.`,"The index, semantic, and source-fallback layers all report zero consumers for this symbol.","Its leaf name is ambiguous project-wide (a same-named definition exists elsewhere), and cross-package consumers reached only through a re-exporting barrel are a known unresolvable shape for this tool \u2014 see docs/plans/2026-07-02-followups.md item 2."]:[`${a.shortName} is a changed production symbol.`,"The index reports zero consumers for this symbol.","The symbol is not in a detected entry surface or configured live root."],remediation:l?"Verify with a direct code search before deleting; this tool cannot confidently resolve this symbol.":"Wire it up, or remove it before it becomes permanent dead code."})}}function aY(e,t){return e.some(n=>t===n.relativeDir||t.startsWith(`${n.relativeDir}/`))}function cY(e,t){let n=F(t);return n?(cn(e).get(n)?.length??0)>1:!1}function lY(e){if(pe(e)!=="type")return!1;let t=F(e);return t.startsWith("_Assert")||t.startsWith("Assert")}function uY(e,t,n,r){let i=new Map(n.renamedFiles.map(s=>[s.to,s.from])),o=r??cs(e,t,ls(n));return s=>{let a=i.get(s.file)??s.file,c=F(s.symbol);if(!c)return!1;let l=o(a);return l!==null&&dY(l,c)}}function dY(e,t){return new RegExp(`\\b${H(t)}\\b`).test(e)}function mY(e,t){if(!rl(Li(e))){t.skipped.push({check:"baseline",reason:"no .scipquery-baseline.json \u2014 run health --write-baseline to enable"});return}t.checksRun.push("baseline");let n=Bf(e);for(let r of n.newFindings.filter(i=>!i.startsWith(kt))){let i=wf(r),o=Pe("baseline",r);Kt(t,{id:o,groupKey:`baseline:${i.sourceAnalyzer}:${i.rootCauseKey}`,check:"baseline",severity:"error",evidence:"baseline",actionTier:i.actionTier,confidence:1,file:i.file,relatedFiles:i.relatedFiles.length>0?i.relatedFiles:void 0,sourceAnalyzer:i.sourceAnalyzer,rootCauseKey:i.rootCauseKey,message:`new ${i.label} vs committed baseline: ${r}`,why:["A committed health baseline exists.","The current health result contains a finding not present in that baseline.",`Underlying analyzer: ${i.sourceAnalyzer}.`,`Inherited action tier: ${i.actionTier}.`,`Root cause key: ${i.rootCauseKey}.`,...i.why],remediation:i.remediation})}}function fY(e,t){if(!lR(e.config.architecture)){t.skipped.push({check:"architecture",reason:"no closed architecture dependency rows, requireCompletePolicy rule, or requireAcyclic rule configured"});return}if(!rl(Li(e))){t.skipped.push({check:"architecture",reason:"no .scipquery-baseline.json \u2014 run health --write-baseline to enable"});return}t.checksRun.push("architecture");let n=bI(e);for(let r of n.newFindings){let i=wf(r),o=Pe("architecture",r);Kt(t,{id:o,groupKey:`architecture:${i.rootCauseKey}`,check:"architecture",severity:"error",evidence:"baseline",actionTier:"direct",confidence:1,sourceAnalyzer:"architecture",rootCauseKey:i.rootCauseKey,message:`new ${i.label} vs committed baseline: ${r}`,why:["The project declares an enforceable architecture rule.","The current boundary graph contains a violation not present in the committed baseline.",...i.why],remediation:i.remediation})}}function Pe(e,...t){return`SQ${LJ("sha256").update([e,...t].join("\0")).digest("hex").slice(0,12).toUpperCase()}`}import{dirname as pY,relative as gY,resolve as hY}from"path";var yY=new Set(qt());function bY(e,t){return`tests/generated/twin-ab/${FI(e)}-vs-${FI(t)}.test.ts`}function FI(e){return(e.split(/[/#]/).pop()||e).replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"symbol"}function SY(e,t,n,r){let i=TI(e,t);if(!i.ok)return i;let o=TI(e,n);if(!o.ok)return o;let s=i.symbol.paramCount===null||o.symbol.paramCount===null?null:i.symbol.paramCount===o.symbol.paramCount,a=CY(i.symbol,o.symbol,e.config.projectRoot,r,s);return{ok:!0,a:i.symbol,b:o.symbol,signatureCompatible:s,testSource:a}}function TI(e,t){let r=to(e,t).match;if(!r)return{ok:!1,reason:`${t} does not resolve to an indexed symbol.`};let o=e.get("SELECT kind FROM global_symbols WHERE id = ?",r.symbolId)?.kind??null;if(!(o!==null?yY.has(o):oe(r.symbol)))return{ok:!1,reason:`${t} resolves to ${I(r.symbol)}${o!==null?` with SCIP kind ${zo(o)}`:""} \u2014 twin-ab compares call outputs, so both referents must be functions or methods.`};if(!hs(e,r))return{ok:!1,reason:`${t} (${I(r.symbol)} at ${r.relativePath}:${r.startLine+1}) is not exported \u2014 twin-ab needs an importable named binding for both twins.`};let a=e.get("SELECT documentation FROM global_symbols WHERE id = ?",r.symbolId),c=on(sn(a?.documentation??null));return{ok:!0,symbol:{ref:t,symbol:r.symbol,shortName:F(r.symbol)||I(r.symbol),file:r.relativePath,startLine:r.startLine,signature:c,paramCount:c?xY(c):null}}}function xY(e){let t=e.indexOf("(");if(t===-1)return null;let n=0,r=-1;for(let a=t;a<e.length;a+=1){let c=e[a];if(c==="(")n+=1;else if(c===")"&&(n-=1,n===0)){r=a;break}}if(r===-1)return null;let i=e.slice(t+1,r).trim();if(!i)return 0;let o=1,s=0;for(let a of i)a==="("||a==="["||a==="{"?s+=1:a===")"||a==="]"||a==="}"?s=Math.max(0,s-1):a===","&&s===0&&(o+=1);return o}function _I(e,t,n){let r=pY(t),i=hY(e,n),s=gY(r,i).replace(/\\/g,"/").replace(/\.tsx?$/,".js");return s.startsWith(".")?s:`./${s}`}function CY(e,t,n,r,i){let o=_I(n,r,e.file),s=_I(n,r,t.file),a=i===null?"Signature comparison: unknown (one or both signatures unavailable in the index) \u2014 check by hand.":i?"Signature comparison: param counts match.":"Signature comparison: param counts DIFFER \u2014 twins may not be directly comparable; check by hand.";return`/**
|
|
818
|
+
* Generated by 'scip-query twin-ab'. scip-audit integrity scenario.
|
|
819
|
+
* ("cross-examine same-concept twins"): where one concept is computed in
|
|
820
|
+
* more than one place, feed both the same input and require the same
|
|
821
|
+
* answer. Disagreement between twins means at least one is wrong \u2014
|
|
822
|
+
* determine which before consolidating.
|
|
823
|
+
*
|
|
824
|
+
* Twin A: ${e.shortName} (${e.file}:${e.startLine+1})
|
|
825
|
+
* ${e.signature??"(signature unavailable)"}
|
|
826
|
+
* Twin B: ${t.shortName} (${t.file}:${t.startLine+1})
|
|
827
|
+
* ${t.signature??"(signature unavailable)"}
|
|
828
|
+
* ${a}
|
|
829
|
+
*
|
|
830
|
+
* Fill in the TODO input table below with inputs both twins should agree
|
|
831
|
+
* on, then run this file with vitest.
|
|
832
|
+
*/
|
|
833
|
+
import { describe, expect, it } from 'vitest';
|
|
834
|
+
import { ${e.shortName} as twinA } from '${o}';
|
|
835
|
+
import { ${t.shortName} as twinB } from '${s}';
|
|
836
|
+
|
|
837
|
+
// TODO: fill in shared inputs both twins should agree on \u2014 one arg array per call.
|
|
838
|
+
const inputs: any[][] = [
|
|
839
|
+
// [/* arg1, arg2, ... */],
|
|
840
|
+
];
|
|
841
|
+
|
|
842
|
+
// Cast to a variadic signature so the input table can hold any arg shape \u2014
|
|
843
|
+
// the real twins have fixed, non-rest parameter lists, and TS rejects
|
|
844
|
+
// spreading a generic args array into those (TS2556) even when the array
|
|
845
|
+
// itself is 'any'; casting the callee's signature, not the args, satisfies
|
|
846
|
+
// the checker without weakening the twins' real exported types elsewhere.
|
|
847
|
+
const callA = twinA as (...callArgs: any[]) => any;
|
|
848
|
+
const callB = twinB as (...callArgs: any[]) => any;
|
|
849
|
+
|
|
850
|
+
describe.skipIf(inputs.length === 0)('twin-ab: ${e.shortName} vs ${t.shortName}', () => {
|
|
851
|
+
it.each(inputs)('agrees on input %#', (...args) => {
|
|
852
|
+
expect(callA(...args)).toEqual(callB(...args));
|
|
853
|
+
});
|
|
854
|
+
});
|
|
855
|
+
`}var LI={caller:3,"entry-surface":2,rooted:1},RY=/not\s*yet\s*implement|not\s*implement|unimplement|\bnyi\b|\btodo\b|\bstub\b|not\s*supported|coming\s*soon/i,vY=/^throw\s+new\s+[\w.]*Error\s*\(([\s\S]*)\)\s*;?$/,IY=/^return(\s+(null|undefined|false|0|''|""|``|\[\]|\{\}))?\s*;?$/,wY=/\/\/\s*TODO\b|\/\*\s*TODO\b/i,EY=/(?:=>|\))\s*(?::\s*[^{;=]+)?\s*\{\s*\}\s*;?\s*$/;function DY(e,t={}){let{scope:n,limit:r=30,scanLimit:i,semantic:o=!0}=t,s=new T(e),a=le(s.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),c=[];for(let f of a){let p=PY(e,f);p&&c.push(p)}if(c.length===0)return[];let l=LY(e,c,a),u=c.filter(f=>!l.has(f.def.symbol));if(u.length===0)return[];let d=gn(e,s).forDefinitions(u.map(f=>f.def),{semantic:o}),m=[];for(let f of u){let g=d.get(f.def.symbolId)?.realConsumers.length??0,y=kY(e,f.def,g);y&&m.push({symbol:f.def.symbol,shortName:I(f.def.symbol),file:f.def.relativePath,startLine:f.def.startLine,endLine:f.def.endLine,loc:O(f.def),stubKind:f.stubKind,reachability:y,callerFanIn:g,stubText:f.stubText})}return m.sort((f,p)=>LI[p.reachability]-LI[f.reachability]||p.callerFanIn-f.callerFanIn||f.file.localeCompare(p.file)||f.startLine-p.startLine),r?m.slice(0,r):m}function kY(e,t,n){return n>0?"caller":ge(e,t.symbol,t.relativePath)?"rooted":Le(e,t.relativePath)?"entry-surface":null}function PY(e,t){let n=bn(e,t);if(!n)return null;let r=zt(n),i=r.trim();if(i==="")return!_Y(n)||!hs(e,t)?null:{def:t,stubKind:"empty-body",stubText:"(empty body)"};let o=Yi(r),s=ct(r),a=FY(o,s);if(a.length!==1)return null;let c=a[0];return TY(c)?{def:t,stubKind:"throw-stub",stubText:c.trim()}:wY.test(r)&&IY.test(c.trim())?{def:t,stubKind:"todo-return-default",stubText:i}:null}function FY(e,t){let n=[],r=0,i="";for(let o=0;o<t.length;o+=1){let s=t[o];if(s==="("||s==="["||s==="{"?r+=1:(s===")"||s==="]"||s==="}")&&(r=Math.max(0,r-1)),s===";"&&r===0){n.push(i),i="";continue}i+=e[o]??""}return i.trim()&&n.push(i),n.map(o=>o.trim()).filter(o=>o.length>0)}function TY(e){let t=vY.exec(e.trim());return t?RY.test(t[1]??""):!1}function _Y(e){return EY.test(e.trimEnd())}function LY(e,t,n){let r=new Set,i=new Set(t.map(a=>a.def.parentTypeName).filter(a=>a!==null));if(i.size===0)return r;let o=AY(e,i),s=new Map;for(let a of n){if(!a.parentTypeName)continue;let c=s.get(a.leaf)??new Set;c.add(a.parentTypeName),s.set(a.leaf,c)}for(let a of t){let c=a.def.parentTypeName;if(!c)continue;let l=o.get(c);if(!l||l.size===0)continue;let u=s.get(a.def.leaf)??new Set;[...l].every(m=>u.has(m))&&r.add(a.def.symbol)}return r}var MY=/\bclass\s+([A-Za-z_$][\w$]*)\s+extends\s+([A-Za-z_$][\w$]*)/g;function AY(e,t){let n=new Map;for(let r of M(e,{includeIgnored:!1})){let i=P(e,r);if(i)for(let o of i.matchAll(MY)){let s=o[1],a=o[2];if(!s||!a||!t.has(a))continue;let c=n.get(a)??new Set;c.add(s),n.set(a,c)}}return n}var NY=/^(?:validate|verify|check|assert)(?:[A-Z].*)?$/,OY=/^(?:is|has)(?:[A-Z].*)?$/,jY=/[{,]\s*(?:ok|success|valid|isValid)\s*:\s*false\b/,Jf=/\breturn\b/g,BY=/\bfunction\b|=>|\)\s*(?::\s*[^{;=]+)?\s*\{/,$Y=/\.(?:addIssue|push)\s*\(/;function HY(e,t={}){let{scope:n,limit:r=30,scanLimit:i}=t,o=new T(e),s=le(o.productionCallableDefinitions({scope:n,minLoc:1,requireFunctionLikeSymbol:!0,excludeTypesFiles:!0}),i),a=[];for(let c of s){let l=qY(e,c);l&&a.push({symbol:c.symbol,shortName:I(c.symbol),file:c.relativePath,startLine:c.startLine,endLine:c.endLine,loc:O(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 UY(e){return NY.test(e)?"imperative":OY.test(e)?"predicate":null}function qY(e,t){let n=UY(t.leaf);if(!n||Ri(e,t))return null;let r=bn(e,t);if(!r||!BY.test(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(Qv(r)){let s=WY(e,t);return!s||NI(s.body,AI(s.snippet))||MI(s.body)?null:{nameKind:n,resolvedVia:"one-hop-delegate",delegateTarget:s.shortName}}let o=zt(r);return NI(o,AI(r))||MI(o)?null:{nameKind:n,resolvedVia:"direct"}}var GY=new Set(["if","for","while","switch","catch","function"]);function MI(e){let t=Yi(e);for(let n of t.matchAll(/\b([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)\s*\(/g))if(!GY.has(n[1]))return!0;return!1}function AI(e){let t=e.indexOf("=>");return t===-1?!1:!/^\s*\{/.test(e.slice(t+2))}function NI(e,t){let n=Yi(e);if(/\bthrow\b/.test(n)||/\.reject\s*\(/.test(n)||jY.test(n)||$Y.test(n))return!0;let r=VY(n);if(t&&r.length===0){let i=n.trim();return i!==""&&i!=="true"}for(let i of r)if(i!==""&&i!=="true")return!0;return!1}function VY(e){let t=[];Jf.lastIndex=0;let n;for(;n=Jf.exec(e);){let r=n.index+n[0].length,i=0,o=e.length;for(let s=r;s<e.length;s+=1){let a=e[s];if(a==="("||a==="["||a==="{")i+=1;else if(a===")"||a==="]"||a==="}"){if(i===0){o=s;break}i-=1}else if(a===";"&&i===0){o=s;break}}t.push(e.slice(r,o).trim()),Jf.lastIndex=o}return t}function WY(e,t){let n=ht(e,t,{callableOnly:!0,limit:3,semanticEvidence:U}),r=[...new Set(n.map(c=>c.symbol))].filter(c=>c!==t.symbol);if(r.length!==1)return null;let o=to(e,r[0]).match;if(!o)return null;let s=Q(e,o.relativePath).find(c=>c.symbolId===o.symbolId);if(!s)return null;let a=bn(e,s);return a?{body:zt(a),snippet:a,shortName:I(s.symbol)}:null}var zY=60;function KY(e,t={}){let{scope:n,limit:r=30,scanLimit:i,rotDays:o=zY}=t,s=le(ze(e,{extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs"]}).filter(u=>W(u)==="test").filter(u=>!n||u.includes(n)).filter(u=>!e.isIgnored(u)).sort(),i),a=[],c=[],l=[];for(let u of s){let d=P(e,u);if(!d)continue;let m=oh(d),f=XY(d);for(let g of t5(m,f))f.add(g);let p=JY(m);for(let g of p){if(g.skip){c.push(c5(e,u,g,o));continue}if(g.kind==="describe")continue;let y=jI(d,g.argsStart),h=m.slice(g.argsStart,g.callEnd),C=d.slice(g.argsStart,g.callEnd);BI(h,f)||a.push({file:u,startLine:Ss(d,g.callStart),endLine:Ss(d,g.callEnd),title:y,severity:/\bawait\b/.test(h)?"low":"high"});let b=o5(h,C);b&&l.push({file:u,startLine:Ss(d,g.callStart),endLine:Ss(d,g.callEnd),title:y,echoedValue:b})}}return{assertionFree:r?a.slice(0,r):a,skipped:r?c.slice(0,r):c,mockEcho:r?l.slice(0,r):l}}var Yf=/(?<!\.)\b(?:x(it|test|describe)|(it|test|describe)(?:\.\s*(skip|only|todo|each\s*\([^)]*\)))?)\s*\(/g;function JY(e){let t=[];Yf.lastIndex=0;let n;for(;n=Yf.exec(e);){let r=n[1],i=r??n[2];if(!i)continue;let o=n[3]?.split(/\s*\(/)[0],s=n.index,a=n.index+n[0].length-1,c=xs(e,a);Yf.lastIndex=a+1,o!=="each"&&t.push({kind:i,skip:r!==void 0||o==="skip"||o==="todo",skipKind:o==="todo"?"todo":"skip",callStart:s,argsStart:a+1,callEnd:c+1})}return t}function xs(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 Ss(e,t){let n=0;for(let r=0;r<t&&r<e.length;r+=1)e[r]===`
|
|
856
|
+
`&&(n+=1);return n}function jI(e,t){let n=e.slice(t,t+400),r=/^\s*(['"`])((?:\\.|(?!\1)[\s\S])*)\1/.exec(n);return r?r[2]:"(anonymous)"}var YY=new Set(["vitest","chai","jest","@jest/globals","assert","node:assert","node:assert/strict","assert/strict","uvu/assert","expect","chai-as-promised"]),OI=/import\s+(?:\*\s+as\s+(\w+)|\{([^}]*)\}|(\w+))\s+from\s+['"]([^'"]+)['"]/g;function XY(e){let t=new Set(["expect","assert"]);OI.lastIndex=0;let n;for(;n=OI.exec(e);){let[,r,i,o,s]=n;if(!(!s||!YY.has(s))&&(r&&t.add(r),o&&t.add(o),i))for(let a of i.split(",")){let c=a.trim().replace(/^type\s+/,"");if(!c)continue;let l=/^(\w+)\s+as\s+(\w+)$/.exec(c);t.add(l?l[2]:c)}}return t}function BI(e,t){if(/\.should\b/.test(e)||/\bawait\s+(?:[\w$.]+\.)?findBy[A-Z]\w*\s*\(/.test(e)||/\bawait\s+\w*waitFor(?:Text|Value|Condition|Result|Event)\s*\(/.test(e)||/\bthrow\b/.test(e))return!0;for(let n of t){let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");if(new RegExp(`\\b${r}\\s*(?:<[^<>]*>)?\\s*[.(]`).test(e))return!0}return!1}var QY=/\bfunction\s+(\w+)\s*\(/g,ZY=/\b(?:const|let)\s+(\w+)\s*=\s*(?:async\s*)?\(/g,e5=60;function t5(e,t){let n=new Set;for(let r of[QY,ZY]){r.lastIndex=0;let i;for(;i=r.exec(e);){let o=i[1],s=i.index+i[0].length-1,a=xs(e,s),c=e.indexOf("{",a+1);if(c===-1||c-a>e5)continue;let l=n5(e,c),u=e.slice(c+1,l);BI(u,t)&&n.add(o)}}return n}function n5(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 r5=/\bmock(?:ReturnValue|ResolvedValue)(?:Once)?\s*\(/g,Xf=/\bexpect\s*\(/g,i5=/^\s*\.\s*(?:toBe|toEqual|toStrictEqual)\s*\(/,$I=/^(?:-?\d+(?:\.\d+)?|(['"`]).+\1)$/;function o5(e,t){let n=s5(e,t,r5);if(n.length===0)return null;let r=a5(e,t);for(let i of r)if(n.includes(i))return i;return null}function s5(e,t,n){let r=[];n.lastIndex=0;let i;for(;i=n.exec(e);){let o=i.index+i[0].length-1,s=xs(e,o),a=t.slice(o+1,s).trim();$I.test(a)&&r.push(a),n.lastIndex=s+1}return r}function a5(e,t){let n=[];Xf.lastIndex=0;let r;for(;r=Xf.exec(e);){let i=r.index+r[0].length-1,o=xs(e,i),s=e.slice(o+1),a=i5.exec(s);if(Xf.lastIndex=o+1,!a)continue;let c=o+1+a[0].length-1,l=xs(e,c),u=t.slice(c+1,l).trim();$I.test(u)&&n.push(u)}return n}function c5(e,t,n,r){let i=P(e,t),o=jI(i,n.argsStart),s=Ss(i,n.callStart),a=l5(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 l5(e,t,n){let r=n+1;try{let i=Wt(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 u5=.7,HI=.62,UI=.45;function d5(e,t={}){let{windowCommits:n=100,limit:r=30,scope:i,scanLimit:o}=t,s=Xe(e,{historyMode:t.historyMode}).fileAddRecords();if(!s)return{available:!1,windowCommits:n,findings:[]};if(r<=0)return{available:!0,windowCommits:n,findings:[]};let a=x5(s,n);if(a.size===0)return{available:!0,windowCommits:n,findings:[]};let l=m5(e,{limit:r,minSimilarity:t.minSimilarity,scanLimit:o,scope:i,semantic:t.semantic,focusFiles:Number.isFinite(r)?void 0:a}).map(d=>C5(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(R5);return{available:!0,windowCommits:n,findings:u,rootCauseGroups:v5(u)}}function m5(e,t){let n=w5(t.limit),r=[...f5(e,{scope:t.scope,minSimilarity:t.minSimilarity??u5,limit:n,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles})],i=Xs(e,{scope:t.scope});return i.react&&r.push(...p5(e,{scope:t.scope,minSimilarity:t.minSimilarity??HI,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...g5(e,{scope:t.scope,minSimilarity:t.minSimilarity??UI,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),i.vue&&r.push(...b5(e,{scope:t.scope,minSimilarity:t.minSimilarity??HI,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles}),...S5(e,{scope:t.scope,minSimilarity:t.minSimilarity??UI,limit:n,scanLimit:t.scanLimit,focusFiles:t.focusFiles})),r}function f5(e,t){return Zo(e,{scope:t.scope,minSimilarity:t.minSimilarity,limit:t.limit,crossFileOnly:!0,scanLimit:t.scanLimit,semantic:t.semantic,focusFiles:t.focusFiles}).filter(n=>!Fe(n.symbolA)&&!Fe(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 p5(e,t){return ol(e,t,{query:es,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 ol(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:E5(...n.evidenceBuckets(r)),sharedCallees:[]}))}function g5(e,t){return ol(e,t,{query:ts,domain:"react-hook",basis:"react-behavior",symbolA:n=>n.componentA,symbolB:n=>n.componentB,acceptPair:y5,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 h5=new Set(["useCallback","useEffect","useLayoutEffect","useMemo","useMutation","useQueries","useQuery","useQueryClient","useReducer","useRef","useState"]);function y5(e){return e.sharedHooks.some(t=>!h5.has(t))||e.sharedState.length>0||e.sharedHandlers.length>0||e.sharedHandlerVerbs.length>=2}function b5(e,t){return ol(e,t,{query:ns,domain:"vue-component",basis:"vue-template",symbolA:n=>il(n.fileA),symbolB:n=>il(n.fileB),evidenceBuckets:n=>[["component",n.sharedComponents],["prop",n.sharedProps],["event",n.sharedEvents],["directive",n.sharedDirectives],["slot",n.sharedSlots],["identifier",n.sharedIdentifiers]]})}function S5(e,t){return ol(e,t,{query:rs,domain:"vue-composable",basis:"vue-behavior",symbolA:n=>il(n.fileA),symbolB:n=>il(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 x5(e,t){let n=new Set;for(let[r,i]of e)i.commitsAgo<=t&&n.add(r);return n}function C5(e,t,n){let r=t.get(e.fileA)?.commitsAgo??null,i=t.get(e.fileB)?.commitsAgo??null,o=r!==null&&r<=n,s=i!==null&&i<=n;if(!o&&!s)return null;if(o&&s){let a=(r??0)<=(i??0);return{kind:"twin",domain:e.domain,basis:e.basis,echoSymbol:a?e.symbolA:e.symbolB,echoFile:a?e.fileA:e.fileB,echoAgeCommits:(a?r:i)??0,establishedSymbol:a?e.symbolB:e.symbolA,establishedFile:a?e.fileB:e.fileA,establishedAgeCommits:a?i:r,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}return{kind:"echo",domain:e.domain,basis:e.basis,echoSymbol:o?e.symbolA:e.symbolB,echoFile:o?e.fileA:e.fileB,echoAgeCommits:(o?r:i)??0,establishedSymbol:o?e.symbolB:e.symbolA,establishedFile:o?e.fileB:e.fileA,establishedAgeCommits:o?i:r,similarity:e.similarity,sharedEvidence:e.sharedEvidence,sharedCallees:e.sharedCallees}}function R5(e){let t=qI(e);return{...e,rootCauseKey:t,groupKey:`recent-duplicate:${t}`}}function qI(e){if(e.kind==="echo")return["echo",e.domain,e.basis,e.establishedSymbol].join(":");let t=e.sharedEvidence.slice().sort().join("|"),n=[e.echoSymbol,e.establishedSymbol].sort().join("|");return["twin",e.domain,e.basis,t||n].join(":")}function v5(e){let t=new Map;for(let[n,r]of e.entries()){let i=r.rootCauseKey??qI(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:I5(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 I5(e){return e.kind==="echo"?"Review the established side once, then migrate or delete every echo in this group.":"Pick one owner for the new twins and consolidate the group before the copies diverge."}function w5(e){return Number.isFinite(e)?e*5:Number.POSITIVE_INFINITY}function E5(...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 il(e){return(e.split("/").pop()??e).replace(/\.[^.]+$/,"")}var D5=Z("suppression-inventory",{clearGroups:["whole-project"]});function sl(e){return D5.get(e,()=>k5(e))}function k5(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 ze(e)){let o=P(e,i);if(!(!o||!o.includes("scip-query")))for(let s of o.split(/\r?\n/)){let a=Ui(s);if(a===null)continue;r+=1,n.set(i,(n.get(i)??0)+1);let c=P5(a);t[c]+=1}}return{total:r,byCategory:t,byFile:n}}function P5(e){if(!e)return"uncategorized";let t=e.toLowerCase();return t==="dead-code"?"dead":t}import{readFileSync as F5}from"fs";import{join as T5}from"path";function Qf(e,t,n={}){let r=$(e,t);if(!r)return null;let i=new T(e),o=_5(e,r),s=r.endLine-r.startLine+1,c=i.calleeMap([r],{additive:!0,semantic:n.semantic}).get(r.symbolId)??[],l=new Set(c.map(u=>u.symbol));return{symbol:r.symbol,shortName:I(r.symbol),relativePath:r.relativePath,startLine:r.startLine,endLine:r.endLine,loc:s,branches:o.branches,estimateBasis:o.estimateBasis,cyclomaticEstimate:o.branches+1,calleeCount:l.size,fanIn:M5(e,r.symbolId),fanOut:A5(c,r.relativePath)}}function _5(e,t){let n=Y(e,t.relativePath);if(n){let r=zI(n.rootNode,t.startLine,t.endLine);if(r)return{branches:N5(r),estimateBasis:"ast"}}return{branches:JI(WI(e,t.relativePath,t.startLine,t.endLine),VI(e,t.relativePath)),estimateBasis:"regex-fallback"}}function GI(e,t){let n=new Map,r=new Map;for(let i of t){let o=r.get(i.relativePath)??[];o.push(i),r.set(i.relativePath,o)}for(let[i,o]of r){let s=Y(e,i),a=s===null?[]:o.filter(l=>s.rootNode.startPosition.row<=l.startLine&&s.rootNode.endPosition.row>=l.endLine),c=new Set(a.map(l=>l.symbolId));if(s&&a.length>0){for(let l of a)n.set(l.symbolId,{branches:0,estimateBasis:"ast"});O5(s.rootNode,a,n)}for(let l of o)c.has(l.symbolId)||n.set(l.symbolId,L5(e,l))}return n}function L5(e,t){return{branches:JI(WI(e,t.relativePath,t.startLine,t.endLine),VI(e,t.relativePath)),estimateBasis:"regex-fallback"}}function VI(e,t){return e.get("SELECT language FROM documents WHERE relative_path = ?",t)?.language??"unknown"}function WI(e,t,n,r){try{return F5(T5(e.config.projectRoot,t),"utf-8").split(`
|
|
857
|
+
`).slice(n,r+1).join(`
|
|
858
|
+
`)}catch{return""}}function M5(e,t){return e.get(`SELECT COUNT(DISTINCT c.document_id) AS c
|
|
859
|
+
FROM mentions m
|
|
860
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
861
|
+
JOIN (
|
|
862
|
+
SELECT m2.symbol_id, c2.document_id
|
|
863
|
+
FROM mentions m2
|
|
864
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
865
|
+
WHERE m2.role = 1
|
|
866
|
+
GROUP BY m2.symbol_id
|
|
867
|
+
) sym_def ON sym_def.symbol_id = m.symbol_id
|
|
868
|
+
WHERE m.symbol_id = ?
|
|
869
|
+
AND m.role != 1
|
|
870
|
+
AND sym_def.document_id != c.document_id`,t)?.c??0}function A5(e,t){return new Set(e.filter(n=>n.file!==t).map(n=>n.symbol)).size}function N5(e){let t=0;return Zf(e,n=>{t+=KI(n)}),t}function O5(e,t,n){let r=[...t].sort((i,o)=>i.startLine-o.startLine||o.endLine-i.endLine);Zf(e,i=>{let o=KI(i);if(o===0)return;let s=i.startPosition.row,a=i.endPosition.row;for(let c of r){if(c.startLine>s)break;if(c.endLine<a)continue;let l=n.get(c.symbolId);l&&(l.branches+=o)}})}function Zf(e,t){t(e);for(let n of e.namedChildren)Zf(n,t)}function zI(e,t,n){if(e.startPosition.row>t||e.endPosition.row<n)return null;for(let r of e.namedChildren){let i=zI(r,t,n);if(i)return i}return e}var j5=new Set(["if_statement","conditional_expression","ternary_expression","for_statement","for_in_statement","for_of_statement","while_statement","do_statement","switch_case","case_statement","catch_clause","except_clause","elif_clause","match_arm"]);function KI(e){return j5.has(e.type)?1:e.type==="binary_expression"&&e.parent?.type!=="binary_expression"&&(e.text.includes("&&")||e.text.includes("||"))?B5(e.text):0}function B5(e){return(e.match(/&&|\|\|/g)??[]).length}function JI(e,t){let n=ct(e),r=0,i=[/\bif\b/g,/\belse\s+if\b/g,/\belse\b/g,/\bfor\b/g,/\bwhile\b/g,/\bswitch\b/g,/\bcase\b/g,/\bcatch\b/g,/\?\s*[^?]/g,/&&/g,/\|\|/g];for(let o of i){let s=n.match(o);s&&(r+=s.length)}if(t==="python"){let o=[/\belif\b/g,/\bexcept\b/g,/\bfinally\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="rust"){let o=[/\bmatch\b/g,/=>/g,/\bloop\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="ruby"){let o=[/\belsif\b/g,/\bunless\b/g,/\brescue\b/g,/\bwhen\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}else if(t==="go"){let o=[/\bselect\b/g,/\bdefer\b/g];for(let s of o){let a=n.match(s);a&&(r+=a.length)}}return r}function ep(e,t,n={}){let r=$(e,t);if(!r)return null;let i=[{file:r.relativePath,line:r.startLine}],o=Nt(e,r,{semantic:n.semantic,semanticEvidence:U}).map(c=>({file:c.file,line:c.line,enclosingSymbol:c.enclosingSymbol??"(top-level)",enclosingShort:c.enclosingSymbol?I(c.enclosingSymbol):"(top-level)"})),{producers:s,consumers:a}=$5(e,r,o,{semantic:n.semantic!==!1});return{symbol:r.symbol,shortName:I(r.symbol),relativePath:r.relativePath,definitionSites:i.filter(c=>!e.isIgnored(c.file)),usageSites:o,producers:s.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:I(c.symbol),file:c.file})),consumers:a.filter(c=>!e.isIgnored(c.file)).map(c=>({symbol:c.symbol,shortName:c.symbol===c.file?"(top-level)":I(c.symbol),file:c.file}))}}function $5(e,t,n,r){let i=Ci(ht(e,t,{limit:30,semantic:r.semantic,semanticEvidence:U}).map(a=>({symbol:a.symbol,file:a.file}))),o=Ci(Dt(e,t,{limit:30,semantic:r.semantic,semanticEvidence:U})),s=o.length>0?o:Ci(n.map(a=>({symbol:a.enclosingSymbol==="(top-level)"?a.file:a.enclosingSymbol,file:a.file})));return{producers:i,consumers:s}}function al(e,t,n={}){let{direction:r="backward",maxDepth:i=3}=n,o=$(e,t);return o?r==="backward"?H5(e,o,i,{semantic:n.semantic!==!1}):U5(e,o,{semantic:n.semantic!==!1}):null}function H5(e,t,n,r){let i=[],o=new Set([t.symbol]),s=[t];for(let a=1;a<=n&&s.length!==0;a++){let c=[];for(let l of s){let u=ht(e,l,{semantic:r.semantic,semanticEvidence:U});for(let d of u){if(o.has(d.symbol))continue;o.add(d.symbol),i.push({symbol:d.symbol,shortName:I(d.symbol),file:d.file,relationship:a===1?"referenced within definition (callee)":`depth ${a} callee`});let m=no(e,d.symbol);m&&!e.isIgnored(m.relativePath)&&c.push(m)}}s=c}return{symbol:t.symbol,shortName:I(t.symbol),direction:"backward",connectedSymbols:i}}function U5(e,t,n){let r=new Set,i=[],o=new T(e);for(let s of Nt(e,t,{semantic:n.semantic,semanticEvidence:U})){if(i.length>=30)break;let a=s.enclosingSymbol??At(o.definitionsForFile(s.file),s.line)?.symbol??null;if(!a||a===t.symbol)continue;let c=no(e,a);!c||e.isIgnored(c.relativePath)||r.has(c.symbol)||(r.add(c.symbol),i.push({symbol:c.symbol,shortName:I(c.symbol),file:c.relativePath,relationship:`references target at ${s.file}:${s.line+1}`}))}return i.sort((s,a)=>s.file.localeCompare(a.file)),{symbol:t.symbol,shortName:I(t.symbol),direction:"forward",connectedSymbols:i}}function q5(e,t,n={}){let r=n.impactDepth??3,i=n.sliceDepth??3,o=n.semantic,s=!V5(t),a=s?Be("trace",t,()=>Am(e,t,{semantic:o}),R=>({definitions:R.definitions.length,references:R.referencedBy.length})):{definitions:[],referencedBy:[]},c=s?Be("call-graph",t,()=>Vm(e,t,{semantic:o}),R=>({callers:R?.callers.length??0,callees:R?.callees.length??0})):null,l=s?Be("complexity",t,()=>Qf(e,t,{semantic:o}),R=>({callees:R?.calleeCount??0})):null,u=s?Be("dataflow",t,()=>ep(e,t,{semantic:o}),R=>({references:R?.usageSites.length??0,producers:R?.producers.length??0,consumers:R?.consumers.length??0})):null,d=s?Be("backward-slice",t,()=>al(e,t,{direction:"backward",maxDepth:i,semantic:o}),R=>({maxDepth:i,connectedSymbols:R?.connectedSymbols.length??0})):null,m=s?Be("forward-slice",t,()=>al(e,t,{direction:"forward",maxDepth:i,semantic:o}),R=>({maxDepth:i,connectedSymbols:R?.connectedSymbols.length??0})):null,f=s?Be("affected",t,()=>cf(e,t,{maxDepth:r,scope:n.scope}),R=>({maxDepth:r,affectedSymbols:R.length})):[],p=Be("change-surface",t,()=>lf(e,t,{semantic:o}),R=>({symbols:R?.symbols.length??0,externalConsumers:R?.totalExternalConsumers??0})),g=Be("system",t,()=>jm(e,t),R=>({files:R.files.length,symbols:R.symbols.length})),y=g.files.length===1,h=Be("deps",t,()=>y?g.dependsOn.map(R=>({relativePath:R})):Nm(e,t),R=>({files:R.length,reusedSystem:y})),C=Be("rdeps",t,()=>y?g.dependedOnBy.map(R=>({relativePath:R})):Om(e,t),R=>({files:R.length,reusedSystem:y})),b=Be("surface",t,()=>Bm(e,t),R=>({consumers:R.length})),S={symbol:a.definitions.length>0||a.referencedBy.length>0||c!==null||l!==null||u!==null||d!==null||m!==null||f.length>0,file:p!==null||h.length>0||C.length>0,module:g.files.length>0||g.symbols.length>0||b.length>0},x=[];!S.symbol&&!S.file&&!S.module&&x.push("No symbol, file, or module matched target.");let v=p?.file??a.definitions[0]?.relativePath??null;return{target:t,matched:S,history:Be("history",v??t,()=>G5(e,v,n.gitHead)),trace:a,callGraph:c,complexity:l,dataflow:u,backwardSlice:d,forwardSlice:m,affected:f,changeSurface:p,deps:h,rdeps:C,system:g,surface:b,warnings:x}}function Be(e,t,n,r=()=>({})){let i;return E(`plan-context.${e}`,()=>(i=n(),i),()=>({target:t,...r(i)}))}function G5(e,t,n){let r={available:!1,file:t,churn:null,coChangePartners:[],suppressionsInFile:0};if(!t)return r;let i=Xe(e,n?{head:n}:{}),o=Be("history.churn",t,()=>i.fileChurn(),c=>({files:c?.size??0}));if(!o)return r;let s=Be("history.co-change",t,()=>ss(e,t,{limit:5,...n?{head:n}:{}}),c=>({commits:c.commitsAnalyzed,partners:c.findings.length})),a=Be("history.suppressions",t,()=>sl(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 V5(e){return e.includes("/")||e.includes("\\")||/\.[A-Za-z0-9]+(?::\d+(?:-\d+)?)?$/.test(e)}var W5=new Set(qt());function tp(e,t){let{scope:n,minLoc:r=10,limit:i=30,scanLimit:o}=t??{},s=new T(e);return bt({candidates:()=>s.productionCallableDefinitions({scope:n,minLoc:r,requireFunctionLikeSymbol:!0,includeSuppressed:!0,sortByLocDesc:typeof o=="number"&&o>0}),scanLimit:o,filterCandidate:z5,profile:{name:"complexity-hotspots"},prepare:a=>{let c=J5(e,a),l=t?.semantic!==!1,u=l?Ye(e):null;u?.materializeReferences(a,{prefetchCallees:!0});let d=s.crossFileCallerMap(a,{semantic:!1});return{callerMap:u?pn(d,u.callerMap(a)):d,calleeMap:s.calleeMap(a,{semantic:l}),languageByFile:c,clojureCallableIds:Y5(e,a,c),branchEstimates:GI(e,a)}},evaluate:(a,c)=>K5(a,c,r),orderResults:(a,c)=>c.score-a.score||c.loc-a.loc,limit:i})}function z5(e){return e.symbol.startsWith("rust-analyzer ")?typeof e.kind=="number"&&W5.has(e.kind):!0}function K5(e,t,n){if(t.languageByFile.get(e.relativePath)==="clojure"&&!t.clojureCallableIds.has(e.symbolId))return null;let r=e.endLine-e.startLine+1;if(r<n)return null;let i=t.callerMap.get(e.symbolId)?.size??0,o=t.calleeMap.get(e.symbolId)??[],s=new Set,a=new Set;for(let m of o){let f=`${m.symbol}|${m.file}`;s.add(f),m.file!==e.relativePath&&a.add(f)}let c=a.size,l=s.size,u=t.branchEstimates.get(e.symbolId)??{branches:0,estimateBasis:"regex-fallback"},d=u.branches+1;return{symbol:e.symbol,shortName:I(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:r,fanIn:i,fanOut:c,calleeCount:l,branches:u.branches,estimateBasis:u.estimateBasis,score:Math.round(r/50*(i/5)*Math.max(c/5,1)*Math.max(d/5,1)*100)/100}}function J5(e,t){let n=[...new Set(t.map(o=>o.relativePath))];if(n.length===0)return new Map;let r=n.map(()=>"?").join(", "),i=e.all(`SELECT relative_path, language
|
|
871
|
+
FROM documents
|
|
872
|
+
WHERE relative_path IN (${r})`,...n);return new Map(i.map(o=>[o.relative_path,o.language?.toLowerCase()??null]))}function Y5(e,t,n){let r=new Set,i=new Map;for(let o of t){if(n.get(o.relativePath)!=="clojure")continue;let s=i.get(o.relativePath);s||(s=new Set((z(e,o.relativePath)?.callables??[]).map(a=>`${a.name}:${a.startLine}`)),i.set(o.relativePath,s)),s.has(`${o.leaf}:${o.startLine}`)&&r.add(o.symbolId)}return r}import{createHash as X5,randomUUID as Q5}from"crypto";function Ft(e,t){return`${e}\0${t}`}function fSe(e,t,n,r,i,o={}){let s=new Map(e.map(l=>[Ft(l.check,l.findingId),l])),a=[],c=(l,u)=>{let d=n.get(l.findingId),m=u==="resolved"?o.verifiedAgainstByFinding?.get(Ft(l.check,l.findingId)):void 0;a.push({ts:i,check:l.check,findingId:l.findingId,event:u,commit:r,...o.comparisonBaseCommit?{comparisonBaseCommit:o.comparisonBaseCommit}:{},...m?{verifiedAgainstCommit:m}:{},...d?{symbol:d}:{}})};for(let l of t){let u=s.get(Ft(l.check,l.findingId));if(!u){c(l,"caught"),l.outcome==="suppressed"&&c(l,"suppressed");continue}u.outcome!==l.outcome&&(l.outcome==="resolved"?c(l,"resolved"):l.outcome==="suppressed"?c(l,"suppressed"):l.outcome==="still-open"&&c(l,"reopened"))}return a}function pSe(e){for(let t=e.length-1;t>=0;t-=1){let n=e[t];if(n?.event==="caught"||n?.event==="reopened")return n}}function Z5(e,t,n,r,i=new Set){let o=new Map(e.map(c=>[Ft(c.check,c.findingId),c])),s=new Set(t.map(c=>Ft(c.check,c.findingId))),a=new Set(n);for(let c of t){let l=Ft(c.check,c.findingId),u=o.get(l),d=c.suppressed?"suppressed":"still-open";u?o.set(l,{...u,lastSeen:r,timesShown:u.timesShown+1,outcome:d}):o.set(l,{check:c.check,findingId:c.findingId,firstSeen:r,lastSeen:r,timesShown:1,outcome:d})}for(let c of e){if(!a.has(c.check))continue;let l=Ft(c.check,c.findingId);s.has(l)||i.has(l)||c.outcome!=="resolved"&&o.set(l,{...c,outcome:"resolved"})}return[...o.values()]}function np(e,t){let n=new Map;for(let i of e){let o=n.get(i.check)??[];o.push(i),n.set(i.check,o)}let r=[];for(let[i,o]of n){let s=o.filter(d=>d.outcome==="resolved").length,a=o.filter(d=>d.outcome==="suppressed").length,c=o.filter(d=>d.outcome==="still-open").length,l=o.length,u=o.filter(d=>d.outcome==="still-open").sort((d,m)=>d.firstSeen-m.firstSeen)[0];r.push({check:i,seen:l,resolved:s,suppressed:a,stillOpen:c,resolutionRate:l>0?s/l:0,suppressionRate:l>0?a/l:0,oldestOpenAgeDays:u?Math.floor((t-u.firstSeen)/XI):null})}return r.sort((i,o)=>i.check.localeCompare(o.check))}var XI=864e5,eX=50,tX=.1,nX=10;function rX(e,t,n){return e.filter(r=>r.check===t).sort((r,i)=>i.firstSeen-r.firstSeen).slice(0,n)}function SSe(e,t,n){if(t.length===0)return null;let r=new Map(e.map(s=>[Ft(s.check,s.findingId),s])),i=t.map(s=>r.get(Ft(s.check,s.findingId))).filter(s=>s!==void 0&&s.timesShown>1);if(i.length===0)return null;let o=Math.max(...i.map(s=>Math.floor((n-s.firstSeen)/XI)));return`${t.length} finding(s), ${i.length} shown before and unresolved (oldest: ${o} day(s))`}function xSe(e,t){let n=[];for(let r of[...new Set(t)].sort()){let i=rX(e,r,eX);i.length<nX||i.filter(a=>a.outcome==="resolved").length/i.length>=tX||n.push(`(the ${r} check's findings are rarely acted on in this repo \u2014 consider suppressing with reasons or tuning its config)`)}return n}function rp(e){return Up(e).map(cl)}function CSe(e,t,n,r=Date.now(),i=new Set,o=Q5(),s){let a=iX(t),c=[...new Set(n)].sort(),l=new Set([...i].sort()),u=X5("sha256").update(JSON.stringify({checksRun:c,observed:a,observedAt:r,retainedKeys:[...l]})).digest("hex"),d=qp(e,{observationId:o,fingerprint:u,observedAt:r},m=>Z5(m.map(cl),a,c,r,l),s===void 0?{}:{busyTimeoutMs:s});return{observationId:o,status:d.status,previous:d.previous.map(cl),current:d.current.map(cl)}}function iX(e){let t=new Map;for(let n of e){let r=Ft(n.check,n.findingId),i=t.get(r);t.set(r,{check:n.check,findingId:n.findingId,suppressed:n.suppressed||(i?.suppressed??!1)})}return[...t.values()].sort((n,r)=>YI(n.check,r.check)||YI(n.findingId,r.findingId))}function YI(e,t){return e<t?-1:e>t?1:0}function cl(e){return{check:e.check,findingId:e.findingId,firstSeen:e.firstSeen,lastSeen:e.lastSeen,timesShown:e.timesShown,outcome:e.outcome}}function Sn(e){return e.scoreCount??e.count}function ew(e){let t=cX(e),{breakdown:n,pressure:r}=lX(e),i=ZI(n,"risk"),o=ZI(n,"hygiene");return{score:Math.min(i,o),riskScore:i,hygieneScore:o,scoreBreakdown:n,overview:{documents:e.statsResult.documents,symbols:e.statsResult.symbols,indexSizeBytes:e.statsResult.indexSizeBytes},findings:{deadSymbols:e.dead.count,deadLoc:e.dead.loc,isolatedSymbols:e.isolated.count,isolatedLoc:e.isolated.loc,cycles:e.realCycleCount,similarPairs:e.similarCount,duplicateBodyGroups:e.duplicateBodies.count,duplicateBodyLoc:e.duplicateBodies.loc,twinDriftGroups:e.twinDrift.count,twinDriftLoc:e.twinDrift.loc,reactComponentDuplicatePairs:e.reactComponentDuplicates.count,reactHookCandidatePairs:e.reactHookCandidates.count,reactHookCandidateScoreCount:Sn(e.reactHookCandidates),reactLargeComponentPressureFiles:e.reactLargeComponentPressure.count,vueComponentDuplicatePairs:e.vueComponentDuplicates.count,vueComposableCandidatePairs:e.vueComposableCandidates.count,vueComposableCandidateScoreCount:Sn(e.vueComposableCandidates),vueLargeViewPressureFiles:e.vueLargeViewPressure.count,extractionCandidates:e.extractCount,wrappers:e.wrappers.count,wrapperScoreCount:Sn(e.wrappers),passthroughs:e.passthroughs.count,staleTypes:e.stale.count,driftedFiles:e.drift.count,complexityHotspotCount:e.complexity.extremeCount,hiddenCouplingPairs:e.gitEvidence?.hiddenCoupling.pairCount??null,hiddenCouplingScoreCount:e.gitEvidence?.hiddenCoupling.scoreCount??null,coverageContractViolations:e.coverageContracts.count},axes:oX(e),validation:aX(e),suppressions:e.suppressions,actions:t,pressure:r,topComplexity:e.complexity.top,warnings:e.warnings.length>0?e.warnings:void 0,detectorPrecision:[]}}function oX(e){return{deletable:{loc:e.dead.loc+e.isolated.loc,symbols:e.dead.count+e.isolated.count},cycles:{count:e.realCycleCount},changeAmplification:e.gitEvidence?.amplification??null,hiddenCoupling:e.gitEvidence?.hiddenCoupling??null,churnWeightedComplexity:sX(e),evidenceQuality:{graphFindings:e.dead.count+e.isolated.count+e.realCycleCount,heuristicFindings:e.similarCount+e.duplicateBodies.count+e.twinDrift.count+e.reactComponentDuplicates.count+e.reactHookCandidates.count+e.reactLargeComponentPressure.count+e.vueComponentDuplicates.count+e.vueComposableCandidates.count+e.vueLargeViewPressure.count+e.extractCount+e.wrappers.count+e.passthroughs.count+e.stale.count+e.drift.count,userSuppressed:e.suppressions?.total??0}}}function sX(e){let t=e.gitEvidence?.fileStats;return t?e.complexity.top.map(n=>{let r=n.file?t[n.file]?.changes??0:0;return{...n,changes:r,weighted:Jt(n.score*Math.log2(1+r))}}).sort((n,r)=>r.weighted-n.weighted):null}function aX(e){let t=e.gitEvidence?.fileStats;if(!t)return null;let n={dead:e.dead.files??[],isolated:e.isolated.files??[],twinDrift:e.twinDrift.files??[],wrappers:e.wrappers.files??[],passthroughs:e.passthroughs.files??[],stale:e.stale.files??[],reactComponents:e.reactComponentDuplicates.files??[],reactHooks:e.reactHookCandidates.files??[],reactLargeComponents:e.reactLargeComponentPressure.files??[],vueComponents:e.vueComponentDuplicates.files??[],vueComposables:e.vueComposableCandidates.files??[],vueLargeViews:e.vueLargeViewPressure.files??[]},r=new Set(Object.values(n).flat()),i=0,o=0,s=0;for(let[u,d]of Object.entries(t))r.has(u)?i+=d.fixChanges:(o+=d.fixChanges,s+=1);let a=r.size>0?Jt(i/r.size):0,c=s>0?Jt(o/s):0,l={};for(let[u,d]of Object.entries(n)){let m=new Set(d);if(m.size===0)continue;let f=0;for(let g of m)f+=t[g]?.fixChanges??0;let p=Jt(f/m.size);l[u]={flaggedFiles:m.size,fixDensity:p,lift:c>0?Jt(p/c):null}}return{flaggedFiles:r.size,flaggedFixDensity:a,baselineFixDensity:c,ratio:r.size>0&&c>0?Jt(a/c):null,byCategory:l,validationBasis:{method:"subject-regex",commitsScanned:e.gitEvidence?.commitsScanned??0}}}function Jt(e){return Math.round(e*100)/100}function tw(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function ll(e,t="existing shared infrastructure discount"){let n=Sn(e);return Math.abs(n-e.count)<.01?"":` (${tw(n)} score-weighted after ${t})`}function Cs(e,t){let n=Sn(e),r=`${e.count} ${t}`;return Math.abs(n-e.count)<.01?r:`${r} (${tw(n)} score-weighted)`}function cX(e){let t=[];if(e.dead.count>0&&t.push({category:"Dead code",evidence:"graph-fact",description:`${e.dead.count} indexed symbols with no visible repository references \u2014 review runtime/framework roots and the capability disclosure, then verify any deletion with cleanup-plan --verify`,effort:"low",impact:"high",count:e.dead.count,locRecoverable:e.dead.loc}),e.isolated.count>0&&t.push({category:"Isolated symbols",evidence:"graph-fact",description:`${e.isolated.count} symbols completely disconnected from the codebase graph`,effort:"low",impact:"medium",count:e.isolated.count,locRecoverable:e.isolated.loc}),e.realCycleCount>0&&t.push({category:"Circular dependencies",evidence:"graph-fact",description:`${e.realCycleCount} indexed dependency cycle(s) \u2014 inspect ownership and runtime order before choosing whether or how to break them`,effort:"medium",impact:"high",count:e.realCycleCount,locRecoverable:0}),e.similarCount>0&&t.push({category:"Similar functions",evidence:"heuristic",description:`${e.similarCount} pairs share disclosed call or source-token evidence beyond imports \u2014 review domain identity before considering consolidation`,effort:"medium",impact:"medium",count:e.similarCount,locRecoverable:0}),e.duplicateBodies.count>0&&t.push({category:"Duplicate function bodies",evidence:"heuristic",description:`${e.duplicateBodies.count} exact small-body group(s) across files \u2014 consolidate only when the domain concept matches`,effort:"low",impact:"medium",count:e.duplicateBodies.count,locRecoverable:e.duplicateBodies.loc}),e.twinDrift.count>0&&t.push({category:"Drifted twin implementations",evidence:"heuristic",description:`${e.twinDrift.count} same-name (or near-name) function group(s) across files with diverged or identical bodies \u2014 determine whether they represent the same concept before acting`,effort:"medium",impact:"medium",count:e.twinDrift.count,locRecoverable:0}),e.reactComponentDuplicates.count>0&&t.push({category:"Duplicated React components",evidence:"heuristic",description:`${e.reactComponentDuplicates.count} React component pair(s) share JSX structure \u2014 review whether local product intent justifies reuse`,effort:"medium",impact:"medium",count:e.reactComponentDuplicates.count,locRecoverable:e.reactComponentDuplicates.loc}),e.reactHookCandidates.count>0&&t.push({category:"Duplicated React hook behavior",evidence:"heuristic",description:`${e.reactHookCandidates.count} React component pair(s) share state/effect/request behavior${ll(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${ll(e.vueComposableCandidates)} \u2014 review whether a common composable would preserve ownership and lifecycle semantics`,effort:"medium",impact:"medium",count:e.vueComposableCandidates.count,locRecoverable:e.vueComposableCandidates.loc}),e.vueLargeViewPressure.count>0&&t.push({category:"Large Vue views",evidence:"heuristic",description:`${e.vueLargeViewPressure.count} Vue file(s) concentrate template/script/style pressure \u2014 split by reason to change`,effort:"medium",impact:"medium",count:e.vueLargeViewPressure.count,locRecoverable:0}),e.extractCount>0&&t.push({category:"Extraction candidates",evidence:"heuristic",description:`${e.extractCount} large functions with isolated callee clusters \u2014 review same-file or feature-local extraction seams`,effort:"medium",impact:"medium",count:e.extractCount,locRecoverable:0}),e.wrappers.count>0&&t.push({category:"Wrapper functions",evidence:"heuristic",description:`${e.wrappers.count} single-consumer symbols${ll(e.wrappers,"boundary-evidence discount")} \u2014 inspect whether each is indirection or an intentional API, framework, or ownership boundary`,effort:"low",impact:"low",count:e.wrappers.count,locRecoverable:e.wrappers.loc}),e.passthroughs.count>0&&t.push({category:"Passthrough functions",evidence:"heuristic",description:`${e.passthroughs.count} functions that literally forward to one callee \u2014 inspect whether each is unnecessary indirection or an intentional boundary`,effort:"low",impact:"low",count:e.passthroughs.count,locRecoverable:e.passthroughs.loc}),e.stale.count>0){let i=[];e.stale.unused>0&&i.push(`${e.stale.unused} unused`),e.stale.singleUse>0&&i.push(`${e.stale.singleUse} single-consumer (not in types file)`),t.push({category:"Stale abstractions",evidence:"heuristic",description:`${i.join(", ")} \u2014 review public, runtime-registration, and ownership evidence before removing, moving, or inlining`,effort:"low",impact:"medium",count:e.stale.count,locRecoverable:e.stale.loc})}if(e.drift.count>0){let i=[];e.drift.unusedImports>0&&i.push(`${e.drift.unusedImports} unused imports`),e.drift.architectureViolations>0&&i.push(`${e.drift.architectureViolations} declared architecture violations`),t.push({category:"Structural drift",evidence:"heuristic",description:`${i.join(", ")} \u2014 repair direct dependency-rule breaks; inspect boundary signals with \`drift --architecture\``,effort:e.drift.architectureViolations>0?"medium":"low",impact:e.drift.architectureViolations>0?"medium":"low",count:e.drift.count,locRecoverable:0})}if(e.coverageContracts.count>0&&t.push({category:"Coverage contract drift",evidence:"graph-fact",description:`${e.coverageContracts.count} configured coverage contract(s) drifted from their ground-truth source (enumeration rot) \u2014 run \`scip-query diff-gate\` or \`scip-query health --json\` for the missing/extra keys`,effort:"low",impact:"medium",count:e.coverageContracts.count,locRecoverable:0}),e.gitEvidence&&e.gitEvidence.hiddenCoupling.pairCount>0){let i=e.gitEvidence.hiddenCoupling.top[0];t.push({category:"Hidden coupling",evidence:"change-graph",description:`${e.gitEvidence.hiddenCoupling.pairCount} file pair(s) co-change without a structural link`+ll({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:e.gitEvidence.hiddenCoupling.scoreCount},"broad/stale-history discount")+(i?` (e.g. ${i.fileA} \u2194 ${i.fileB})`:"")+" \u2014 inspect whether a shared concept, generated artifact, or coordinated contract explains the history",effort:"medium",impact:"high",count:e.gitEvidence.hiddenCoupling.pairCount,locRecoverable:0})}let n={high:3,medium:2,low:1},r={low:3,medium:2,high:1};return t.sort((i,o)=>{let s=n[i.impact]*r[i.effort];return n[o.impact]*r[o.effort]-s}),t}var QI={"dead-code":"risk",isolated:"risk",cycles:"risk",complexity:"risk","hidden-coupling":"risk","cycles-pressure":"risk","complexity-pressure":"risk","hidden-coupling-pressure":"risk",similar:"hygiene","duplicate-bodies":"hygiene","twin-drift":"hygiene","react-component-duplicates":"hygiene","react-hook-candidates":"hygiene","react-large-component-pressure":"hygiene","vue-component-duplicates":"hygiene","vue-composable-candidates":"hygiene","vue-large-view-pressure":"hygiene",extract:"hygiene",wrappers:"hygiene",passthroughs:"hygiene","stale-abstractions":"hygiene",drift:"hygiene","similar-pressure":"hygiene","duplicate-bodies-pressure":"hygiene","twin-drift-pressure":"hygiene","react-component-duplicates-pressure":"hygiene","react-hook-candidates-pressure":"hygiene","react-large-component-pressure-pressure":"hygiene","vue-component-duplicates-pressure":"hygiene","vue-composable-candidates-pressure":"hygiene","vue-large-view-pressure-pressure":"hygiene","extract-pressure":"hygiene","wrappers-pressure":"hygiene","passthroughs-pressure":"hygiene","stale-abstractions-pressure":"hygiene","drift-pressure":"hygiene"};function ZI(e,t){let n=e.filter(r=>r.kind===t).reduce((r,i)=>r+i.points,0);return Math.max(0,Math.min(100,100-n))}function lX(e){let t=Math.max(e.statsResult.documents,1),n=Math.max(e.statsResult.symbols,1),r=[],i=[],o=(R,D,w)=>{D>0&&r.push({axis:R,points:D,detail:w,kind:QI[R]??"hygiene"})},s=(R,D,w,k,L,ne,ee)=>{let _=Math.max(k,1);if(w<=_)return;let ue=w/_,re=Math.min(L,Math.ceil(Math.log2(ue)*ne));if(re<=0)return;let xn=QI[R]??"hygiene";i.push({axis:R,category:D,kind:xn,count:w,threshold:Jt(_),ratio:Jt(ue),extraPenalty:re}),o(R,re,`${w} ${ee} exceed pressure threshold ${Jt(_)} (${Jt(ue)}x)`)},a=e.dead.count/n;o("dead-code",Math.min(20,Math.round(a*200)),`${e.dead.count} dead symbols (${e.dead.loc} LOC deletable)`);let c=e.isolated.count/n;o("isolated",Math.min(10,Math.round(c*200)),`${e.isolated.count} isolated symbols (${e.isolated.loc} LOC deletable)`),o("cycles",Math.min(15,e.realCycleCount*5),`${e.realCycleCount} real dependency cycle(s)`);let l=e.similarCount/n*1e3;o("similar",Math.min(10,Math.round(l)),`${e.similarCount} similar function pair(s)`);let u=e.duplicateBodies.count/n*1e3;o("duplicate-bodies",Math.min(10,Math.round(u*2)),`${e.duplicateBodies.count} exact duplicate small-body group(s) (${e.duplicateBodies.loc} duplicate LOC)`);let d=e.twinDrift.count/n*1e3;o("twin-drift",Math.min(10,Math.round(d*2)),`${e.twinDrift.count} drifted twin implementation group(s) (same or near-same name, diverged or identical bodies)`);let m=e.reactComponentDuplicates.count/t*1e3;o("react-component-duplicates",Math.min(10,Math.round(m)),`${e.reactComponentDuplicates.count} duplicated React component pair(s)`);let f=Sn(e.reactHookCandidates),p=f/t*1e3;o("react-hook-candidates",Math.min(10,Math.round(p)),Cs(e.reactHookCandidates,"duplicated React behavior pair(s)"));let g=e.reactLargeComponentPressure.count/t*1e3;o("react-large-component-pressure",Math.min(5,Math.round(g/2)),`${e.reactLargeComponentPressure.count} large React component pressure file(s)`);let y=e.vueComponentDuplicates.count/t*1e3;o("vue-component-duplicates",Math.min(10,Math.round(y)),`${e.vueComponentDuplicates.count} duplicated Vue component pair(s)`);let h=Sn(e.vueComposableCandidates),C=h/t*1e3;o("vue-composable-candidates",Math.min(10,Math.round(C)),Cs(e.vueComposableCandidates,"duplicated Vue behavior pair(s)"));let b=e.vueLargeViewPressure.count/t*1e3;o("vue-large-view-pressure",Math.min(5,Math.round(b/2)),`${e.vueLargeViewPressure.count} large Vue view pressure file(s)`);let S=Sn(e.wrappers);o("wrappers",Math.min(3,S),Cs(e.wrappers,"wrapper candidate(s)"));let x=Sn(e.passthroughs);o("passthroughs",Math.min(3,x),Cs(e.passthroughs,"passthrough candidate(s)")),o("stale-abstractions",Math.min(8,e.stale.unused),`${e.stale.unused} unused stale abstraction(s); ${e.stale.singleUse} single-consumer signal(s)`);let v=e.drift.direct/t;if(o("drift",Math.min(5,Math.round(v*50)),`${e.drift.direct} direct drift finding(s); ${e.drift.signal} signal drift finding(s)`),o("complexity",Math.min(5,e.complexity.extremeCount*2),`${e.complexity.extremeCount} extreme complexity hotspot(s)`),e.gitEvidence){let R=e.gitEvidence.hiddenCoupling.scoreCount;o("hidden-coupling",Math.min(5,Math.ceil(R/10)),Cs({count:e.gitEvidence.hiddenCoupling.pairCount,scoreCount:R},"co-changing pair(s) without a structural link"))}if(s("cycles-pressure","Circular dependencies",e.realCycleCount,3,10,3,"cycle(s)"),s("complexity-pressure","Extreme complexity",e.complexity.extremeCount,3,5,2,"extreme complexity hotspot(s)"),e.gitEvidence){let R=e.gitEvidence.hiddenCoupling.scoreCount;s("hidden-coupling-pressure","Hidden coupling",R,50,10,4,"score-weighted co-changing pair(s)")}return s("similar-pressure","Similar functions",e.similarCount,Math.max(50,n*.01),8,4,"similar function pair(s)"),s("duplicate-bodies-pressure","Duplicate function bodies",e.duplicateBodies.count,Math.max(20,n*.005),8,4,"exact duplicate small-body group(s)"),s("twin-drift-pressure","Drifted twin implementations",e.twinDrift.count,Math.max(20,n*.005),8,4,"drifted twin implementation group(s)"),s("react-component-duplicates-pressure","Duplicated React components",e.reactComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated React component pair(s)"),s("react-hook-candidates-pressure","Duplicated React hook behavior",f,Math.max(10,t*.01),8,4,"duplicated React behavior pair(s)"),s("react-large-component-pressure-pressure","Large React components",e.reactLargeComponentPressure.count,Math.max(10,t*.01),4,2,"large React component pressure file(s)"),s("vue-component-duplicates-pressure","Duplicated Vue components",e.vueComponentDuplicates.count,Math.max(10,t*.01),8,4,"duplicated Vue component pair(s)"),s("vue-composable-candidates-pressure","Duplicated Vue behavior",h,Math.max(10,t*.01),8,4,"duplicated Vue behavior pair(s)"),s("vue-large-view-pressure-pressure","Large Vue views",e.vueLargeViewPressure.count,Math.max(10,t*.01),4,2,"large Vue view pressure file(s)"),s("extract-pressure","Extraction candidates",e.extractCount,Math.max(50,n*.01),4,2,"extraction candidate(s)"),s("wrappers-pressure","Wrapper functions",S,50,4,2,"wrapper candidate(s)"),s("passthroughs-pressure","Passthrough functions",x,50,4,2,"passthrough candidate(s)"),s("stale-abstractions-pressure","Single-consumer stale abstraction signals",e.stale.singleUse,Math.max(50,n*.02),4,2,"single-consumer stale abstraction signal(s)"),s("drift-pressure","Structural drift signals",e.drift.signal,Math.max(10,t*.1),4,2,"signal drift finding(s)"),{breakdown:r,pressure:i}}import{getHeapStatistics as uX}from"v8";var dX=64*1024*1024;function ip(){let e=globalThis.gc;if(!e)return;let t=uX();t.heap_size_limit-t.used_heap_size<dX||e()}var mX=50,fX=25e3,pX=2500,nw=2500,rw=50,gX=10,ul=["overview","dead","isolated","cycles","similar","duplicate-bodies","twin-drift","react-component-duplicates","react-hook-candidates","react-large-component-pressure","vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure","extract-candidates","wrapper-candidates","passthrough-candidates","stale-abstractions","drift","complexity-hotspots","git-evidence","suppressions","coverage-contracts"],hX={overview:(e,t,n,r)=>({phase:"overview",statsResult:r,warnings:n.warnings}),dead:(e,t,n)=>({phase:"dead",dead:xX(e,t,n)}),isolated:(e,t,n)=>({phase:"isolated",isolated:CX(e,t,n)}),cycles:(e,t,n)=>({phase:"cycles",realCycleCount:RX(e,t,n)}),similar:(e,t,n)=>({phase:"similar",similarCount:vX(e,t,n)}),"duplicate-bodies":(e,t,n)=>({phase:"duplicate-bodies",duplicateBodies:wX(e,t,n)}),"twin-drift":(e,t,n)=>({phase:"twin-drift",twinDrift:EX(e,t,n)}),"react-component-duplicates":(e,t,n)=>({phase:"react-component-duplicates",reactComponentDuplicates:DX(e,t,n)}),"react-hook-candidates":(e,t,n)=>({phase:"react-hook-candidates",reactHookCandidates:kX(e,t,n)}),"react-large-component-pressure":(e,t,n)=>({phase:"react-large-component-pressure",reactLargeComponentPressure:PX(e,t,n)}),"vue-component-duplicates":(e,t,n)=>({phase:"vue-component-duplicates",vueComponentDuplicates:FX(e,t,n)}),"vue-composable-candidates":(e,t,n)=>({phase:"vue-composable-candidates",vueComposableCandidates:TX(e,t,n)}),"vue-large-view-pressure":(e,t,n)=>({phase:"vue-large-view-pressure",vueLargeViewPressure:_X(e,t,n)}),"extract-candidates":(e,t,n)=>({phase:"extract-candidates",extractCount:IX(e,t,n)}),"wrapper-candidates":(e,t,n)=>({phase:"wrapper-candidates",wrappers:LX(e,t,n)}),"passthrough-candidates":(e,t,n)=>({phase:"passthrough-candidates",passthroughs:MX(e,t,n)}),"stale-abstractions":(e,t,n)=>({phase:"stale-abstractions",stale:AX(e,t,n)}),drift:(e,t,n)=>({phase:"drift",drift:BX(e,t,n)}),"complexity-hotspots":(e,t,n)=>({phase:"complexity-hotspots",complexity:$X(e,t,n)}),"git-evidence":(e,t,n)=>({phase:"git-evidence",gitEvidence:NX(e,n)}),suppressions:(e,t,n)=>({phase:"suppressions",suppressions:OX(e,n)}),"coverage-contracts":(e,t,n)=>({phase:"coverage-contracts",coverageContracts:jX(e,n)})};function op(e,t,n={}){return yX(e,[t],n)[0]}function yX(e,t,n={}){return bX(e,n.full!==!1,(r,i)=>{let o={...i,releaseCachesBetweenPhases:!1};return t.map(s=>hX[s](e,n.scope,o,r))})}function bX(e,t,n){let r=Er(e),i=HX(r,t);try{return n(r,i)}finally{Um(e,{semanticProvider:!0}),ip()}}function sp(e){return ew(SX(e))}function SX(e){let t=xe(e,"overview");return{statsResult:t.statsResult,warnings:t.warnings,dead:xe(e,"dead").dead,isolated:xe(e,"isolated").isolated,realCycleCount:xe(e,"cycles").realCycleCount,similarCount:xe(e,"similar").similarCount,duplicateBodies:xe(e,"duplicate-bodies").duplicateBodies,twinDrift:xe(e,"twin-drift").twinDrift,reactComponentDuplicates:xe(e,"react-component-duplicates").reactComponentDuplicates,reactHookCandidates:xe(e,"react-hook-candidates").reactHookCandidates,reactLargeComponentPressure:xe(e,"react-large-component-pressure").reactLargeComponentPressure,vueComponentDuplicates:xe(e,"vue-component-duplicates").vueComponentDuplicates,vueComposableCandidates:xe(e,"vue-composable-candidates").vueComposableCandidates,vueLargeViewPressure:xe(e,"vue-large-view-pressure").vueLargeViewPressure,extractCount:xe(e,"extract-candidates").extractCount,wrappers:xe(e,"wrapper-candidates").wrappers,passthroughs:xe(e,"passthrough-candidates").passthroughs,stale:xe(e,"stale-abstractions").stale,drift:xe(e,"drift").drift,complexity:xe(e,"complexity-hotspots").complexity,gitEvidence:iw(e,"git-evidence")?.gitEvidence??null,suppressions:iw(e,"suppressions")?.suppressions??null,coverageContracts:xe(e,"coverage-contracts").coverageContracts}}function iw(e,t){return e.find(n=>n.phase===t)}function xe(e,t){let n=e.find(r=>r.phase===t);if(!n)throw new Error(`Missing health phase result: ${t}`);return n}function xX(e,t,n){return ye(e,n,"dead",()=>{let r=Dr(e,{scope:t,...he.dead,scanLimit:n.candidateScanLimit,semantic:n.semantic});return dl(GX(e,r.symbols))})}function CX(e,t,n){return ye(e,n,"isolated",()=>{let r=Qo(e,{scope:t,...he.isolated,scanLimit:n.candidateScanLimit,semantic:n.semantic});return dl(VX(e,r))})}function RX(e,t,n){return ye(e,n,"cycles",()=>Yo(e,{scope:t}).filter(i=>i.kind==="real").length)}function vX(e,t,n){let r=ye(e,n,"similar",()=>Xm(e,{scope:t,...he.similar,scanLimit:n.candidateScanLimit,semantic:n.semantic}));return Math.min(r,n.candidateResultLimit)}function IX(e,t,n){return ye(e,n,"extract-candidates",()=>is(e,{scope:t,...he.extract,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}).length)}function wX(e,t,n){return ye(e,n,"duplicate-bodies",()=>{let r=ds(e,{scope:t,...he.duplicateBodies,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit}),i=new Set,o=0;for(let s of r)for(let a of s.functions.slice(1))i.add(a.file),o+=a.loc;return{count:r.length,loc:o,files:[...i]}})}function EX(e,t,n){return ye(e,n,"twin-drift",()=>{let r=_i(e,{scope:t,...he.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 DX(e,t,n){return ye(e,n,"react-component-duplicates",()=>{let r=es(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return ap(r)})}function kX(e,t,n){return ye(e,n,"react-hook-candidates",()=>{let r=ts(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return aw(r,zX)})}function PX(e,t,n){return ye(e,n,"react-large-component-pressure",()=>{let r=Qm(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return WX(r)})}function FX(e,t,n){return ye(e,n,"vue-component-duplicates",()=>{let r=ns(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return ap(r)})}function TX(e,t,n){return ye(e,n,"vue-composable-candidates",()=>{let r=rs(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return aw(r,KX)})}function _X(e,t,n){return ye(e,n,"vue-large-view-pressure",()=>{let r=Zm(e,{scope:t,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit});return dl(r)})}function LX(e,t,n){return ye(e,n,"wrapper-candidates",()=>{let r=bs(e,{scope:t,...he.wrappers,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return sw(r,JX)})}function MX(e,t,n){return ye(e,n,"passthrough-candidates",()=>{let r=gs(e,{scope:t,...he.passthroughs,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return sw(r,YX)})}function AX(e,t,n){return ye(e,n,"stale-abstractions",()=>{let r=ys(e,{scope:t,...he.stale,limit:n.candidateResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic}),i=r.filter(o=>o.consumers===0).length;return{count:r.length,loc:r.reduce((o,s)=>o+s.loc,0),files:[...new Set(r.map(o=>o.file))],unused:i,singleUse:r.length-i}})}function NX(e,t){return ye(e,t,"git-evidence",()=>{let n=Xe(e,{historyMode:t.gitHistoryMode}),r=n.fileChurn();if(!r)return null;let i=n.commitHistory(),o=ss(e,void 0,{limit:t.candidateResultLimit,historyMode:t.gitHistoryMode}),s={};for(let[a,c]of r)s[a]={changes:c.changes,fixChanges:c.fixChanges};return{amplification:n.changeAmplification(),hiddenCoupling:{pairCount:o.findings.length,scoreCount:cp(o.findings.reduce((a,c)=>a+ow(c),0)),top:o.findings.slice(0,5).map(a=>({fileA:a.fileA,fileB:a.fileB,together:a.together,confidence:a.confidence,focusedTogether:a.focusedTogether,broadTogether:a.broadTogether,broadCommitRatio:a.broadCommitRatio,lastTogetherAt:a.lastTogetherAt,recentTogether:a.recentTogether,commitScope:a.commitScope,recency:a.recency,scoreWeight:ow(a),subjectContext:a.subjectContext}))},fileStats:s,commitsScanned:i?.commits.length??0}})}function OX(e,t){return ye(e,t,"suppressions",()=>{let n=sl(e);return{total:n.total,byCategory:{...n.byCategory}}})}function jX(e,t){return ye(e,t,"coverage-contracts",()=>{let n=e.config.coverageContracts??[],i=rI(e,n).filter(o=>o.status!=="ok");return{count:i.length,loc:0,files:[...new Set(i.map(o=>o.file))].sort()}})}function BX(e,t,n){return ye(e,n,"drift",()=>{let r=ps(e,{scope:t,...he.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 $X(e,t,n){return ye(e,n,"complexity-hotspots",()=>{let r=tp(e,{scope:t,minLoc:10,limit:n.complexityResultLimit,scanLimit:n.candidateScanLimit,semantic:n.semantic});return{top:r.slice(0,5).map(i=>({symbol:i.shortName,score:i.score,file:i.file})),extremeCount:r.filter(i=>i.score>mX).length}})}function HX(e,t){let n=e.symbols>=fX||e.documents>=pX,r=t?Number.POSITIVE_INFINITY:rw,i=t?Number.POSITIVE_INFINITY:gX;return!n||t?{candidateScanLimit:void 0,candidateResultLimit:r,complexityResultLimit:i,semantic:!0,gitHistoryMode:t?"full":"bounded",releaseCachesBetweenPhases:!0,warnings:t&&n?["Large index detected; running health without candidate scan or result caps because full mode is enabled."]:[]}:{candidateScanLimit:nw,candidateResultLimit:r,complexityResultLimit:i,semantic:!1,gitHistoryMode:"bounded",releaseCachesBetweenPhases:!0,warnings:[`Large index detected; candidate-style health checks scanned their highest-priority ${nw} symbols and reported their top ${rw} findings. Enable full mode for unbounded candidate counts.`]}}function UX(e,t){t.releaseCachesBetweenPhases&&(Um(e),ip())}function ye(e,t,n,r){qX(n);try{return r()}finally{UX(e,t)}}function qX(e){process.env.SCIP_QUERY_HEALTH_TRACE==="1"&&console.error(`[health] ${e}`)}function GX(e,t){return t.filter(n=>!Le(e,n.relativePath)&&!ge(e,n.symbol,n.relativePath)&&n.kind==="dead-code")}function VX(e,t){return t.filter(n=>!Le(e,n.relativePath)&&!ge(e,n.symbol,n.relativePath))}function dl(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 sw(e,t){return{...dl(e),scoreCount:cp(e.reduce((r,i)=>r+t(i),0))}}function WX(e){let t=new Map;for(let n of e)t.set(n.file,Math.max(t.get(n.file)??0,n.loc));return{count:t.size,loc:[...t.values()].reduce((n,r)=>n+r,0),files:[...t.keys()]}}function ap(e){let t=new Map;for(let n of e)t.set(n.fileA,Math.max(t.get(n.fileA)??0,n.locA)),t.set(n.fileB,Math.max(t.get(n.fileB)??0,n.locB));return{count:e.length,loc:[...t.values()].reduce((n,r)=>n+r,0),files:[...t.keys()]}}function aw(e,t){return{...ap(e),scoreCount:cp(e.reduce((r,i)=>r+t(i),0))}}function zX(e){let t=e.sharedHooks.length>0,n=cw({namedState:e.sharedState,requests:e.sharedRequests,lifecycle:e.sharedEffects,functions:e.sharedHandlers});return t&&n<=2?0:t?.5:lw(e.sharedState,e.sharedHandlers,e.sharedHandlerVerbs)?.25:n>=2?1:.5}function KX(e){let t=e.sharedComposables.length+e.sharedStores.length>0,n=cw({namedState:e.sharedBindings,requests:e.sharedRequests,lifecycle:e.sharedLifecycle,functions:e.sharedFunctions});return t&&n<=2?0:t?.5:lw(e.sharedBindings,e.sharedFunctions,e.sharedFunctionVerbs)?.25:n>=2?1:.5}function cw(e){return e.requests.length*2+e.lifecycle.length+e.namedState.filter(t=>!dw.has(uw(t))).length+Math.min(e.functions.length,3)}function lw(e,t,n){let r=[...e,...t,...n].map(uw);return r.length>0&&r.every(i=>dw.has(i))}function uw(e){return e.replace(/^handle/,"").replace(/^is/,"").replace(/^has/,"").toLowerCase()}function JX(e){return e.actionTier==="signal"?.25:1}function YX(e){return e.actionTier==="signal"?.25:1}function ow(e){return e.commitScope==="broad-sweep"?e.recency==="recent"?.25:0:e.commitScope==="mixed"?e.recency==="recent"?.5:.25:e.recency==="recent"?1:.5}function cp(e){return Math.round(e*100)/100}var dw=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 XX(e,t,n,r={}){let i=Ym(e,t,n,r);return i?{symbolA:i.symbolA,symbolB:i.symbolB,similarity:i.similarity,sharedCallees:i.sharedEvidence,uniqueToA:i.uniqueToA,uniqueToB:i.uniqueToB,consolidationStrategy:i.consolidationStrategy}:null}function QX(e,t={}){let{scope:n,limit:r}=t,i=new T(e),o=sQ([...ZX(e,n),...nQ(e,i,n)]);return aQ(o),r?o.slice(0,r):o}function ZX(e,t){let n=[];for(let r of eQ(e,t)){if(e.isIgnored(r.barrel_path)||e.isIgnored(r.original_path)||Fm(e,r.barrel_path)||P(e,r.barrel_path)&&sa(e,r.barrel_path).length===0)continue;let i=tQ(e,r),o=i?.barrel_consumers??0,s=i?.direct_consumers??0;o!==0||s!==0||n.push({barrelFile:r.barrel_path,symbol:r.symbol,shortName:I(r.symbol),originalFile:r.original_path,barrelConsumers:o,directConsumers:s,...fw(e,r.barrel_path)})}return n}function eQ(e,t){let n=t?"AND barrel_d.relative_path LIKE ?":"",r=t?[`%${t}%`]:[];return e.all(`SELECT DISTINCT
|
|
873
|
+
barrel_d.id AS barrel_doc_id,
|
|
874
|
+
barrel_d.relative_path AS barrel_path,
|
|
875
|
+
gs.id AS symbol_id,
|
|
876
|
+
gs.symbol AS symbol,
|
|
877
|
+
orig_d.id AS original_doc_id,
|
|
878
|
+
orig_d.relative_path AS original_path
|
|
879
|
+
FROM mentions m
|
|
880
|
+
JOIN chunks c ON m.chunk_id = c.id
|
|
881
|
+
JOIN documents barrel_d ON c.document_id = barrel_d.id
|
|
882
|
+
JOIN global_symbols gs ON m.symbol_id = gs.id
|
|
883
|
+
JOIN (
|
|
884
|
+
SELECT m2.symbol_id, c2.document_id
|
|
885
|
+
FROM mentions m2
|
|
886
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
887
|
+
WHERE m2.role = 1
|
|
888
|
+
GROUP BY m2.symbol_id
|
|
889
|
+
) sym_def ON sym_def.symbol_id = gs.id
|
|
890
|
+
JOIN documents orig_d ON sym_def.document_id = orig_d.id
|
|
891
|
+
WHERE m.role != 1
|
|
892
|
+
AND (barrel_d.relative_path LIKE '%/index.ts'
|
|
893
|
+
OR barrel_d.relative_path LIKE '%/index.js'
|
|
894
|
+
OR barrel_d.relative_path = 'index.ts'
|
|
895
|
+
OR barrel_d.relative_path = 'index.js')
|
|
896
|
+
AND orig_d.id != barrel_d.id
|
|
897
|
+
${e.pathExclusionsFor("barrel_d","orig_d")}
|
|
898
|
+
${e.symbolNoiseFor("gs")}
|
|
899
|
+
-- Only function-level symbols (ending with ().), not module-level
|
|
900
|
+
AND gs.symbol LIKE '%().'
|
|
901
|
+
${n}
|
|
902
|
+
ORDER BY barrel_d.relative_path, gs.symbol`,...r)}function tQ(e,t){return e.get(`SELECT
|
|
903
|
+
SUM(CASE WHEN uses_barrel = 1 THEN 1 ELSE 0 END) AS barrel_consumers,
|
|
904
|
+
SUM(CASE WHEN uses_barrel = 0 THEN 1 ELSE 0 END) AS direct_consumers
|
|
905
|
+
FROM (
|
|
906
|
+
SELECT
|
|
907
|
+
consumer_d.id AS consumer_doc_id,
|
|
908
|
+
MAX(CASE WHEN EXISTS (
|
|
909
|
+
SELECT 1
|
|
910
|
+
FROM mentions barrel_m
|
|
911
|
+
JOIN chunks barrel_c ON barrel_m.chunk_id = barrel_c.id
|
|
912
|
+
WHERE barrel_c.document_id = consumer_d.id
|
|
913
|
+
AND barrel_m.role != 1
|
|
914
|
+
AND barrel_m.symbol_id IN (
|
|
915
|
+
SELECT m2.symbol_id
|
|
916
|
+
FROM mentions m2
|
|
917
|
+
JOIN chunks c2 ON m2.chunk_id = c2.id
|
|
918
|
+
WHERE c2.document_id = ?
|
|
919
|
+
AND m2.role != 1
|
|
920
|
+
)
|
|
921
|
+
) THEN 1 ELSE 0 END) AS uses_barrel
|
|
922
|
+
FROM mentions ref_m
|
|
923
|
+
JOIN chunks ref_c ON ref_m.chunk_id = ref_c.id
|
|
924
|
+
JOIN documents consumer_d ON ref_c.document_id = consumer_d.id
|
|
925
|
+
WHERE ref_m.symbol_id = ?
|
|
926
|
+
AND ref_m.role != 1
|
|
927
|
+
AND consumer_d.id != ?
|
|
928
|
+
AND consumer_d.id != ?
|
|
929
|
+
${e.pathExclusionsFor("consumer_d")}
|
|
930
|
+
GROUP BY consumer_d.id
|
|
931
|
+
)`,t.barrel_doc_id,t.symbol_id,t.barrel_doc_id,t.original_doc_id)}function nQ(e,t,n){let r=[];for(let i of rQ(e,n))pw(e,i,i)>0||r.push(...iQ(e,t,i));return r}function rQ(e,t){return M(e,{scope:t,includeIgnored:!1}).filter(n=>sa(e,n).length>0||rn(e,n).length>0)}function iQ(e,t,n){let r=sa(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>mw(e,t,n,o.sourcePath,[oQ(o.specifier)])),i=rn(e,n).filter(o=>o.sourcePath&&!e.isIgnored(o.sourcePath)).flatMap(o=>mw(e,t,n,o.sourcePath,o.kind==="named"&&o.names.length>0?o.names:[o.kind==="star"?`* from ${o.sourcePath}`:`* namespace from ${o.sourcePath}`]));return[...r,...i]}function mw(e,t,n,r,i){let o=t.definitionsForFile(r);return i.map(s=>{let a=o.find(c=>c.leaf===s);return{barrelFile:n,symbol:a?.symbol??`source-reexport:${n}:${s}`,shortName:a?I(a.symbol):s,originalFile:r,barrelConsumers:0,directConsumers:pw(e,r,n),...fw(e,n)}})}function oQ(e){return e.split("::").at(-1)?.split("/").at(-1)?.replace(/\.[^.]+$/,"")??e}function fw(e,t){return wr(e,t)?{actionTier:"signal",surfaceEvidence:["barrel file is declared on the package public surface"],recommendation:"Review the package API before removing this re-export; local consumers are zero, but external consumers may import through the public barrel."}:{actionTier:"direct",surfaceEvidence:[],recommendation:"Remove this unused re-export when the barrel is not part of an external API surface."}}function pw(e,t,n){let r=new Set;for(let i of M(e,{includeIgnored:!1}))if(i!==n)for(let o of te(e,i))o.sourcePath===t&&r.add(i);return r.size}function sQ(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 aQ(e){e.sort((t,n)=>n.directConsumers-t.directConsumers||t.barrelFile.localeCompare(n.barrelFile)||t.shortName.localeCompare(n.shortName))}function cQ(e,t={}){let{samples:n=50,scope:r,maxDisagreements:i=5}=t,o=new T(e),s=lQ(o.productionCallableDefinitions({scope:r,minLoc:2,requireFunctionLikeSymbol:!0}),n),a=uQ(e,s);if(s.length===0||!a)return{available:!1,sampleSize:s.length,oracleCoverage:0,scores:[],topDisagreements:[]};let c={references:gw(),callees:gw()},l=[],u=0,d=a==="semantic"?Qa(e,s):new Map,m=a==="source"?fQ(e,o,s):null;for(let f of s){let p=ml(f,a==="semantic"?Xa(e,f).map(S=>S.file):[...m?.referencesBySymbolId.get(f.symbolId)??[]]),g=ml(f,a==="semantic"?(d.get(f.symbolId)??[]).map(S=>S.file):[...m?.calleesBySymbolId.get(f.symbolId)??[]]);u+=1;let y=ml(f,Nt(e,f,{semanticEvidence:U}).map(S=>S.file)),h=ml(f,(o.calleeMap([f],{semantic:!1}).get(f.symbolId)??[]).map(S=>S.file)),C=lp(a,"references"),b=lp(a,"callees");hw(c.references,f,"references",y,p,C,l),hw(c.callees,f,"callees",h,g,b,l)}return l.sort((f,p)=>p.cheapOnly.length+p.oracleOnly.length-(f.cheapOnly.length+f.oracleOnly.length)),{available:!0,sampleSize:s.length,oracleCoverage:s.length>0?dp(u/s.length):0,oracleKind:a,scores:["references","callees"].map(f=>mQ(f,c[f],a)),topDisagreements:l.slice(0,i)}}function gw(){return{comparedSymbols:0,agreed:0,cheapTotal:0,oracleTotal:0,skippedOraclePartial:0}}function lQ(e,t){let n=[...e].sort((o,s)=>o.symbolId-s.symbolId);if(n.length<=t)return n;let r=n.length/t,i=[];for(let o=0;o<t;o++)i.push(n[Math.floor(o*r)]);return i}function uQ(e,t){let n=t[0];if(!n)return null;if(up(e,n))return"source";try{if(Ye(e).capability("semantic-references",n.relativePath).available)return"semantic"}catch{}return t.some(r=>up(e,r))?"source":null}function ml(e,t){let n=new Set;for(let r of t)r!==e.relativePath&&n.add(r);return n}function hw(e,t,n,r,i,o,s){if(!o&&i.size===0){e.skippedOraclePartial+=1;return}e.comparedSymbols+=1,e.cheapTotal+=r.size,e.oracleTotal+=i.size;let a=[],c=[];for(let l of r)i.has(l)?e.agreed+=1:a.push(l);for(let l of i)r.has(l)||c.push(l);(a.length>0||c.length>0)&&s.push({symbol:I(t.symbol),question:n,cheapOnly:a,oracleOnly:c})}var dQ={references:!0,callees:!1};function mQ(e,t,n){let r=t.oracleTotal>0?t.agreed/t.oracleTotal:1,i=t.cheapTotal-t.agreed,o=lp(n,e);return{question:e,comparedSymbols:t.comparedSymbols,precision:o&&t.cheapTotal>0?dp(t.agreed/t.cheapTotal):null,recall:dp(r),unverified:i,skippedOraclePartial:t.skippedOraclePartial}}function lp(e,t){return e==="semantic"?dQ[t]:!1}function up(e,t){return N(t.relativePath)==="clojure"&&z(e,t.relativePath)!==null}function fQ(e,t,n){let r=new Map,i=new Map,o=n.filter(c=>up(e,c)),s=new Map;for(let c of o){let l=s.get(c.leaf)??[];l.push(c),s.set(c.leaf,l)}for(let c of t.sourceFiles()){if(N(c)!=="clojure")continue;let l=z(e,c);if(l)for(let u of l.fileIdentifiers)for(let d of s.get(u)??[])yw(r,d.symbolId,c)}let a=new Map;for(let c of t.scopedDefinitions()){if(N(c.relativePath)!=="clojure")continue;let l=a.get(c.leaf)??[];l.push(c),a.set(c.leaf,l)}for(let c of o){let l=z(e,c.relativePath);if(l){for(let u of l.callSites)if(!(u.line<c.startLine||u.line>c.endLine))for(let d of a.get(u.calleeLeaf)??[])yw(i,c.symbolId,d.relativePath)}}return{referencesBySymbolId:r,calleesBySymbolId:i}}function yw(e,t,n){let r=e.get(t);if(r){r.add(n);return}e.set(t,new Set([n]))}function dp(e){return Math.round(e*1e3)/1e3}var pQ=new Set(qt());function gQ(e,t={}){let{scope:n,minLoc:r=1,limit:i,scanLimit:o,maxShapeFrequency:s=12}=t,a=t.semantic!==!1,c=bQ(e,hQ(e,{scope:n,minLoc:r,scanLimit:o}),{semantic:a,maxShapeFrequency:s}),l=xQ(c);return i?l.slice(0,i):l}function hQ(e,t){let n=De(e,{scope:t.scope}).filter(r=>yQ(r)&&!e.isIgnored(r.relativePath)).filter(r=>O(r)>=t.minLoc);return typeof t.scanLimit=="number"&&t.scanLimit>0&&n.sort((r,i)=>O(i)-O(r)||r.relativePath.localeCompare(i.relativePath)),le(n,t.scanLimit)}function yQ(e){return!e.isFunctionLike||Fe(e.symbol)?!1:e.kind===null||pQ.has(e.kind)}function bQ(e,t,n){let r=[];for(let s of t){let a=RQ(e,s,n);a&&r.push({signature:a,definition:s,fn:SQ(s)})}let i=new Map;for(let s of r)i.set(s.signature,(i.get(s.signature)??0)+1);let o=new Map;for(let s of r){let a=CQ(s.fn.loc),c=(i.get(s.signature)??0)>n.maxShapeFrequency,l=c?Tf(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 SQ(e){return{symbol:e.symbol,shortName:I(e.symbol),file:e.relativePath,startLine:e.startLine,endLine:e.endLine,loc:O(e)}}function xQ(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 CQ(e){return e<=5?"<=5":e<=20?"6-20":">20"}function RQ(e,t,n){if(n.semantic){let o=dS(e,t);if(o)return o}let r=vQ(t.documentation),i=r?EQ(r):null;return i||DQ(IQ(e,t.relativePath,t.startLine,t.endLine,t.leaf),t.leaf)}function vQ(e){return on(sn(e))}function IQ(e,t,n,r,i){let o=P(e,t);if(!o)return null;let s=o.split(/\r?\n/),a=PQ(s,n,r,i);for(let c of a){let l=Math.min(s.length-1,Math.max(c,c+4)),u="";for(let d=c;d<=l;d+=1){let m=s[d]?.trim();if(m&&(u=u?`${u} ${m}`:m,wQ(u)))return u}if(u&&u.includes("("))return u}return null}function wQ(e){let t=e.replace(/\s+/g," ").trim();return!t.includes("(")||Xi(t)>0?!1:/[;{]$/.test(t)||/\)\s*(?::\s*[^={]+)?\s*(?:=>|=|throws\b|where\b|$)/i.test(t)||/\)\s*As\s+.+$/i.test(t)}function EQ(e){if(!e||!e.trim())return null;let t=e.replace(/^```\w*\s*/,"").replace(/\s*```$/,"").replace(/^\(method\)\s*/,"").replace(/^\(property\)\s*/,"").replace(/^\(function\)\s*/,"").replace(/^\(class\)\s*/,"").replace(/^\(interface\)\s*/,"").replace(/^\(enum\)\s*/,"").replace(/^\(type alias\)\s*/,"").replace(/^\(const\)\s*/,"").replace(/^\(var\)\s*/,"").trim(),n=t.indexOf("(");return n===-1||(t=t.slice(n),t=t.replace(/\s+/g,"").toLowerCase(),t.length<3)?null:t}function DQ(e,t){if(!e||!e.trim())return null;let n=e.replace(/\s+/g," ").trim(),r=n.indexOf("(");if(r===-1)return null;let i=n.slice(0,r),s=new RegExp(`\\b${H(t)}\\b`,"i").exec(i);s&&typeof s.index=="number"&&(i=i.slice(0,s.index)),i=i.replace(/\b(public|private|protected|internal|final|static|abstract|sealed|virtual|override|async|suspend|inline|constexpr|consteval|constinit|const|pub|fn|function|def|sub|friend|shared|readonly|new|open|partial|export)\b/gi," ").replace(/\s+/g," ").trim();let a=kQ(n.slice(r)).replace(/\)\s*=\s*[\s\S]*$/,")").replace(/\s+throws\s+[^={]+$/i,"").replace(/\s+where\s+.+$/i,"").replace(/\s+/g," ").trim();if(!a.startsWith("("))return null;let c=`${i?`${i} `:""}${a}`.replace(/\s+/g,"").toLowerCase();return c.length>=3?c:null}function kQ(e){let t=0,n=0,r=0,i=0,o=null,s=!1;for(let a=0;a<e.length;a+=1){let c=e[a];if(o){if(s){s=!1;continue}if(c==="\\"){s=!0;continue}c===o&&(o=null);continue}if(c==='"'||c==="'"||c==="`"){o=c;continue}if(c==="(")t+=1;else if(c===")")t=Math.max(0,t-1);else if(c==="[")r+=1;else if(c==="]")r=Math.max(0,r-1);else if(c==="<")i+=1;else if(c===">")i=Math.max(0,i-1);else if(c==="{"){if(t===0&&r===0&&i===0)return e.slice(0,a);n+=1}else if(c==="}")n=Math.max(0,n-1);else if(c==="="&&e[a+1]===">"&&t===0&&n===0&&r===0&&i===0)return e.slice(0,a)}return e}function PQ(e,t,n,r){let i=H(r),o=new RegExp(`\\b${i}\\b\\s*\\(`,"i"),s=new RegExp(`\\bdef\\s+${i}\\b`,"i"),a=[],c=new Set,l=Math.max(0,Math.min(t,e.length-1)),u=Math.max(l,Math.min(e.length-1,Math.max(n,t+4)));for(let d=l;d<=u;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}for(let d=0;d<e.length;d+=1){let m=e[d]??"";(o.test(m)||s.test(m))&&!c.has(d)&&(c.add(d),a.push(d))}return a}import{spawnSync as GCe}from"child_process";import{spawn as TQ}from"child_process";import{performance as bw}from"perf_hooks";var Cw={probe:1e4,git:3e4,analysis:18e4,install:3e5,indexer:6e5},Tr=class extends Error{constructor(n,r,i,o={}){super(i,o.cause===void 0?void 0:{cause:o.cause});this.kind=n;this.label=r;this.name="BoundedProcessError",this.timedOut=o.timedOut??!1,this.reaped=o.reaped??!1,this.stdout=o.stdout??"",this.stderr=o.stderr??"",this.stdoutTruncated=o.stdoutTruncated??!1,this.stderrTruncated=o.stderrTruncated??!1}kind;label;timedOut;reaped;stdout;stderr;stdoutTruncated;stderrTruncated};function fl(e,t){if(!Number.isFinite(e)||e<=0)throw new TypeError(`${t} must be a positive finite number.`)}function Sw(e,t,n,r){let i=Math.max(0,r-n);i>0&&e.push(t.subarray(0,i))}function xw(e,t,n){let r=Buffer.concat([...e,t]);e.length=0,e.push(r.subarray(Math.max(0,r.length-n)))}function _Q(e,t){if(e.exitCode!==null||e.signalCode!==null||e.pid===void 0)return!1;if(!t)return!0;let n=Rt(e.pid);return n!==null&&ft(t,n)}function Rw(e){fl(e.timeoutMs,"timeoutMs"),fl(e.maxStdoutBytes,"maxStdoutBytes"),fl(e.maxStderrBytes,"maxStderrBytes");let t=e.terminationGraceMs??1e3;return fl(t,"terminationGraceMs"),new Promise((n,r)=>{let i=bw.now(),o;try{o=TQ(e.command,[...e.args??[]],{cwd:e.cwd,env:e.env,detached:e.detached,stdio:["pipe","pipe","pipe"]})}catch(b){r(new Tr("spawn",e.label,`${e.label} could not start.`,{cause:b,reaped:!0}));return}let s=[],a=[],c=0,l=0,u=!1,d=!1,m=null,f=!1,p=null,g=o.pid===void 0?null:Rt(o.pid),y=b=>{m||f||(m=b,o.kill("SIGTERM"),p=setTimeout(()=>{!f&&_Q(o,g)&&o.kill("SIGKILL")},t),p.unref())},h=setTimeout(()=>{y({kind:"timeout",timedOut:!0,message:`${e.label} timed out after ${e.timeoutMs}ms.`})},e.timeoutMs);h.unref();let C=()=>{y({kind:"aborted",timedOut:!1,message:`${e.label} was cancelled.`})};e.signal?.addEventListener("abort",C,{once:!0}),e.signal?.aborted&&C(),o.stdout.on("data",b=>{let S=Buffer.isBuffer(b)?b:Buffer.from(b);e.outputLimitBehavior==="truncate-tail"?xw(s,S,e.maxStdoutBytes):Sw(s,S,c,e.maxStdoutBytes),c+=S.length,c>e.maxStdoutBytes&&(u=!0,e.outputLimitBehavior!=="truncate-tail"&&y({kind:"stdout-limit",timedOut:!1,message:`${e.label} exceeded stdout limit (${e.maxStdoutBytes} bytes).`}))}),o.stderr.on("data",b=>{let S=Buffer.isBuffer(b)?b:Buffer.from(b);e.outputLimitBehavior==="truncate-tail"?xw(a,S,e.maxStderrBytes):Sw(a,S,l,e.maxStderrBytes),l+=S.length,l>e.maxStderrBytes&&(d=!0,e.outputLimitBehavior!=="truncate-tail"&&y({kind:"stderr-limit",timedOut:!1,message:`${e.label} exceeded stderr limit (${e.maxStderrBytes} bytes).`}))}),o.on("error",b=>{if(!f&&!m){if(o.pid===void 0){clearTimeout(h),p&&clearTimeout(p),e.signal?.removeEventListener("abort",C),f=!0,r(new Tr("spawn",e.label,`${e.label} could not start: ${b.message}`,{cause:b,reaped:!0}));return}y({kind:"spawn",timedOut:!1,message:`${e.label} failed after start: ${b.message}`})}}),o.on("close",(b,S)=>{if(f)return;f=!0,clearTimeout(h),p&&clearTimeout(p),e.signal?.removeEventListener("abort",C);let x=Buffer.concat(s).toString("utf8"),v=Buffer.concat(a).toString("utf8");if(m){r(new Tr(m.kind,e.label,m.message,{timedOut:m.timedOut,reaped:!0,stdout:x,stderr:v,stdoutTruncated:u,stderrTruncated:d}));return}n({status:b,signal:S,stdout:x,stderr:v,timedOut:!1,durationMs:bw.now()-i,stdoutTruncated:u,stderrTruncated:d})}),e.input===void 0?o.stdin.end():o.stdin.end(e.input)})}var fp="scip-query-isolated-analysis",pp=1,Ai=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 KCe(e,t){console.log(JSON.stringify({protocol:fp,schemaVersion:pp,producer:{name:"scip-query",version:It},command:e,result:t}))}function vw(e,t){let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function pl(e){let t=e.timeoutMs??Cw.analysis,n=e.maxBuffer??10*1024*1024;return Rw({command:process.execPath,args:[...process.execArgv,e.cliPath,e.command,...e.args??[]],cwd:process.cwd(),env:e.env??process.env,label:e.label,timeoutMs:t,maxStdoutBytes:n,maxStderrBytes:n}).catch(r=>{throw r instanceof Tr&&r.kind==="timeout"?new Ai(e.label,t,r.reaped):r}).then(r=>{let i=r.stderr.trim();if(r.status!==0)throw new Error(`${e.label} failed${i?`:
|
|
932
|
+
${i}`:""}`);return LQ(r.stdout,e)})}function LQ(e,t){let n;try{n=JSON.parse(e)}catch(r){throw new Error(`${t.label} returned invalid JSON: ${r instanceof Error?r.message:r}`,{cause:r})}if(!q(n))throw new Error(`${t.label} returned a non-object isolated-analysis message.`);if(n.protocol!==fp)throw new Error(`${t.label} returned protocol ${mp(n.protocol)}; expected ${fp}.`);if(n.schemaVersion!==pp)throw new Error(`${t.label} returned unsupported isolated-analysis schemaVersion ${mp(n.schemaVersion)}; expected ${pp}.`);if(!MQ(n.producer))throw new Error(`${t.label} did not identify a scip-query producer version.`);if(n.command!==t.command)throw new Error(`${t.label} returned result for command ${mp(n.command)}; expected ${t.command}.`);if(!Object.hasOwn(n,"result"))throw new Error(`${t.label} omitted the isolated-analysis result.`);return n.result}function MQ(e){return q(e)&&e.name==="scip-query"&&typeof e.version=="string"&&e.version.length>0}function mp(e){return typeof e=="string"?JSON.stringify(e):String(e)}async function gp(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 Iw(e,t){let n=new Set,r=[];for(let i of e){if(n.has(i))continue;let o=t.find(a=>a.has(i));if(!o){n.add(i),r.push([i]);continue}let s=e.filter(a=>o.has(a));s.forEach(a=>n.add(a)),r.push(s)}return r}import{spawnSync as AQ}from"child_process";import{existsSync as NQ,mkdirSync as OQ,readFileSync as jQ,renameSync as BQ,writeFileSync as $Q}from"fs";import{dirname as ww,join as HQ}from"path";var gl=3,UQ="health-report-cache.json";function hp(e,t,n,r=WQ()){let i=Ne(e);return i?{version:gl,projectFingerprint:i,cliVersion:n,scope:t.scope??null,full:t.full===!0,phaseTimeoutMs:t.phaseTimeoutMs??null,gitHead:r.gitHead(e.config.projectRoot)}:null}function Ew(e,t,n=Fw()){let r=kw(e),i=Pw(t),o=!1;return E("health.report-cache.read",()=>{if(!n.existsSync(r))return null;try{let s=JSON.parse(n.readFileSync(r,"utf8"));return!qQ(s)||s.keyHash!==i?null:(o=!0,s.report)}catch{return null}},()=>({available:!0,hit:o,keyHash:i}))}function Dw(e,t,n,r=Fw()){let i=kw(e),o={version:gl,keyHash:Pw(t),key:t,writtenAt:r.nowIso(),report:n};r.mkdirSync(ww(i),{recursive:!0});let s=`${i}.${process.pid}.${Date.now()}.tmp`;r.writeFileSync(s,JSON.stringify(o)),r.renameSync(s,i)}function kw(e){return HQ(ww(e.config.dbPath),UQ)}function Pw(e){return Ce(JSON.stringify(e))}function qQ(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===gl&&typeof t.keyHash=="string"&&GQ(t.key)&&typeof t.writtenAt=="string"&&VQ(t.report)}function GQ(e){if(!e||typeof e!="object")return!1;let t=e;return t.version===gl&&typeof t.projectFingerprint=="string"&&typeof t.cliVersion=="string"&&(t.scope===null||typeof t.scope=="string")&&typeof t.full=="boolean"&&(t.phaseTimeoutMs===null||typeof t.phaseTimeoutMs=="number")&&(t.gitHead===null||typeof t.gitHead=="string")}function VQ(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.score=="number"&&typeof t.riskScore=="number"&&typeof t.hygieneScore=="number"&&typeof t.overview=="object"&&typeof t.findings=="object"&&Array.isArray(t.scoreBreakdown)&&Array.isArray(t.actions)&&Array.isArray(t.pressure)&&Array.isArray(t.topComplexity)&&Array.isArray(t.detectorPrecision)}function WQ(){return{gitHead(e){let t=AQ("git",["rev-parse","HEAD"],{cwd:e,encoding:"utf8",timeout:3e4,killSignal:"SIGKILL"});return t.status===0?t.stdout.trim():null}}}function Fw(){return{existsSync:NQ,mkdirSync:OQ,readFileSync:jQ,renameSync:BQ,writeFileSync:$Q,nowIso:()=>new Date().toISOString()}}var Lw="__health-phase",KQ="__diff-impact-batch",JQ=10,YQ=4,XQ=8,QQ=25e3,ZQ=2500,yp=2500,e4=4,t4=12,Tw=3e4,Mw=new Set(["react-component-duplicates","react-hook-candidates","react-large-component-pressure"]),Aw=new Set(["vue-component-duplicates","vue-composable-candidates","vue-large-view-pressure"]),n4=new Set([...Aw,"suppressions"]),r4=new Set(["similar","extract-candidates"]),hl=2,_w=nr({kind:"health-semantic-prewarm",invalidation:X("health-semantic-prewarm"),serialize:e=>JSON.stringify(e),deserialize:i4});function i4(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return n.version!==hl||typeof n.definitions!="number"||!Number.isFinite(n.definitions)||typeof n.referenceCacheWrites!="number"||!Number.isFinite(n.referenceCacheWrites)||typeof n.referenceIncomplete!="number"||!Number.isFinite(n.referenceIncomplete)||typeof n.calleeRows!="number"||!Number.isFinite(n.calleeRows)||typeof n.warmedAt!="number"||!Number.isFinite(n.warmedAt)?null:{version:hl,definitions:n.definitions,referenceCacheWrites:n.referenceCacheWrites,referenceIncomplete:n.referenceIncomplete,calleeRows:n.calleeRows,warmedAt:n.warmedAt}}catch{return null}}function Nw(e){console.log(`Heuristic ${e}: review before acting; these are candidates, not exact compiler facts.
|
|
933
|
+
`)}function o4(e){let t=Er(e);return t.symbols>=QQ||t.documents>=ZQ}function Ow(e,t,n,r={}){return o4(e)?n?(r.quiet||console.error(`Large index detected; ${t} is running the unbounded semantic pass because --full was supplied.`),{semantic:!0}):(r.quiet||console.error(`Large index detected; ${t} will scan the highest-priority ${yp} candidates with semantic enrichment disabled. Run "scip-query ${t} --full" for the unbounded semantic pass.`),{scanLimit:yp,semantic:!1,analysisBudget:{scanLimit:yp,semanticEnrichment:!1,reason:"large index default budget; pass --full for unbounded semantic analysis"}}):{semantic:!0}}function SRe(e){return e?`analysis budget: scanning up to ${e.scanLimit} candidate(s); semantic enrichment=${e.semanticEnrichment}; ${e.reason}`:null}var s4={env:process.env,projectFingerprint:Ne,semanticEngineFingerprint:u4,readMarker:(e,t,n)=>_w.read(e,t,n),writeMarker:(e,t,n,r)=>_w.write(e,t,n,r),candidateDefinitions:(e,t)=>new T(e).scopedDefinitions(t.scope).filter(n=>_e(n.relativePath)!==null),materializeReferences:(e,t,n)=>Ye(e).materializeReferences(t,n),materializeCallees:Md};function a4(e,t,n=s4){if(t.full!==!0)return Qn("default-mode");if((n.env??process.env).SCIP_QUERY_HEALTH_SEMANTIC_PREWARM==="0")return Qn("disabled");let r=Qn("error");return E("health.semantic-prewarm",()=>{try{r=c4(e,t,n)}catch(i){r=Qn("error",{error:i instanceof Error?i.message:String(i)})}return r},()=>d4(r))}function c4(e,t,n){let r=n.projectFingerprint(e);if(!r)return Qn("missing-project-fingerprint");let i=l4(t,n.semanticEngineFingerprint(e)),o=n.readMarker(e,i,r);if(o&&o.referenceIncomplete===0)return Qn("cache-hit");let s=[];if(s=E("health.semantic-prewarm.candidate-definitions",()=>(s=n.candidateDefinitions(e,t),s),()=>({definitions:s.length})),s.length===0)return Qn("no-semantic-definitions");let a=0,c=E("health.semantic-prewarm.references",()=>{let m=n.materializeReferences(e,s,{prefetchCallees:!0});return a=m.cacheHits+m.cacheWrites+m.inMemoryHits,m},()=>({definitions:s.length,rows:a}));if(c.cacheHits+c.cacheWrites+c.inMemoryHits===0&&c.misses+c.unkeyed>0)return Qn("provider-unavailable",{definitions:s.length,referenceMisses:c.misses});let u=0,d=E("health.semantic-prewarm.callees",()=>{let m=n.materializeCallees(e,s);return u=m.size,m},()=>({definitions:s.length,rows:u}));return c.incomplete>0?{status:"partial",reason:"incomplete-references",definitions:s.length,referenceCacheHits:c.cacheHits,referenceCacheWrites:c.cacheWrites,referenceMisses:c.misses,referenceIncomplete:c.incomplete,calleeRows:d.size}:(E("health.semantic-prewarm.marker-write",()=>n.writeMarker(e,i,r,{version:hl,definitions:s.length,referenceCacheWrites:c.cacheWrites,referenceIncomplete:c.incomplete,calleeRows:d.size,warmedAt:Date.now()})),{status:"warmed",reason:"cache-miss",definitions:s.length,referenceCacheHits:c.cacheHits,referenceCacheWrites:c.cacheWrites,referenceMisses:c.misses,referenceIncomplete:c.incomplete,calleeRows:d.size})}function l4(e,t){return JSON.stringify({version:hl,cliVersion:It,semanticEngineFingerprint:t,scope:e.scope??null})}function u4(e){return Ce(JSON.stringify({kind:"health-semantic-prewarm-engine",rust:fr(e.config.projectRoot)}))}function Qn(e,t={}){return{status:"skipped",reason:e,definitions:0,referenceCacheHits:0,referenceCacheWrites:0,referenceMisses:0,referenceIncomplete:0,calleeRows:0,...t}}function d4(e){return{status:e.status,reason:e.reason,definitions:e.definitions,referenceCacheHits:e.referenceCacheHits,referenceCacheWrites:e.referenceCacheWrites,referenceMisses:e.referenceMisses,referenceIncomplete:e.referenceIncomplete,calleeRows:e.calleeRows,error:e.error}}async function xRe(e){let t=y4(e),n={...e,phaseTimeoutMs:t??null},r=mn(m=>{let f=hp(m,n,It);if(!f)return null;let p=Ew(m,f);return p?(p.detectorPrecision=np(rp(m),Date.now()),p):null});if(r)return r;let{applicability:i,overview:o}=mn(m=>({applicability:m4(m,e),overview:op(m,"overview",e)})),s=new Map;s.set("overview",o);let a=ul.filter(m=>m==="overview"?!1:f4(m,i)?!0:(s.set(m,_r(m)),!1)),c=p4(a);e.full&&mn(m=>a4(m,e));let l=await gp(c,b4(c.length),m=>g4(m,e,t)),u=[];if(l.flat().forEach(m=>{m.healthPhaseMeta&&u.push(`Health phase "${m.phase}" deferred: ${m.healthPhaseMeta.reason}. Run health --full for exhaustive analysis.`),s.set(m.phase,m)}),u.length>0){let m=s.get("overview");s.set("overview",{...m,warnings:[...m.warnings,...u]})}let d=sp(ul.map(m=>s.get(m)));return d.detectorPrecision=mn(m=>np(rp(m),Date.now())),mn(m=>{let f=hp(m,n,It);f&&Dw(m,f,d)}),d}function m4(e,t){return Xs(e,{scope:t.scope})}function f4(e,t){return Mw.has(e)?t.react:Aw.has(e)?t.vue:!0}function p4(e){return Iw(e,[Mw,n4,r4])}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 g4(e,t,n){if(e.length===1)return h4(e[0],t,n).then(s=>[s]);let r=e.join(","),i=process.argv[1]??Sp(import.meta.url),o=[r];return t.scope&&o.push("--scope",t.scope),t.full&&o.push("--full"),pl({cliPath:i,command:Lw,args:o,label:`Health phases "${r}"`,timeoutMs:n}).catch(s=>{if(t.full||!(s instanceof Ai))throw s;return e.map(a=>jw(a,s.timeoutMs,`timed out after ${s.timeoutMs}ms`))})}function h4(e,t,n){let r=process.argv[1]??Sp(import.meta.url),i=[e];return t.scope&&i.push("--scope",t.scope),t.full&&i.push("--full"),pl({cliPath:r,command:Lw,args:i,label:`Health phase "${e}"`,timeoutMs:n}).catch(o=>{if(t.full||!(o instanceof Ai))throw o;return jw(e,o.timeoutMs,`timed out after ${o.timeoutMs}ms`)})}function y4(e,t=process.env){if(e.full)return;let n=t.SCIP_QUERY_HEALTH_PHASE_TIMEOUT_MS;if(!n)return Tw;let r=parseInt(n,10);return!Number.isFinite(r)||r<0?Tw:r===0?void 0:r}function jw(e,t,n){let r={healthPhaseMeta:{status:"deferred",reason:n,timeoutMs:t}};switch(e){case"overview":throw new Error("Overview health phase cannot be deferred.");case"dead":return{phase:e,dead:{count:0,loc:0,files:[]},...r};case"isolated":return{phase:e,isolated:{count:0,loc:0,files:[]},...r};case"cycles":return{phase:e,realCycleCount:0,...r};case"similar":return{phase:e,similarCount:0,...r};case"duplicate-bodies":return{phase:e,duplicateBodies:{count:0,loc:0,files:[]},...r};case"twin-drift":return{phase:e,twinDrift:{count:0,loc:0,files:[]},...r};case"react-component-duplicates":return{..._r(e),...r};case"react-hook-candidates":return{..._r(e),...r};case"react-large-component-pressure":return{..._r(e),...r};case"vue-component-duplicates":return{..._r(e),...r};case"vue-composable-candidates":return{..._r(e),...r};case"vue-large-view-pressure":return{..._r(e),...r};case"extract-candidates":return{phase:e,extractCount:0,...r};case"wrapper-candidates":return{phase:e,wrappers:{count:0,loc:0,files:[]},...r};case"passthrough-candidates":return{phase:e,passthroughs:{count:0,loc:0,files:[]},...r};case"stale-abstractions":return{phase:e,stale:{count:0,loc:0,files:[],unused:0,singleUse:0},...r};case"drift":return{phase:e,drift:{count:0,unusedImports:0,architectureViolations:0,layerViolations:0,direct:0,signal:0},...r};case"complexity-hotspots":return{phase:e,complexity:{top:[],extremeCount:0},...r};case"git-evidence":return{phase:e,gitEvidence:null,...r};case"suppressions":return{phase:e,suppressions:{total:0,byCategory:{}},...r};case"coverage-contracts":return{phase:e,coverageContracts:{count:0,loc:0,files:[]},...r}}}var b4=Bw({envKey:"SCIP_QUERY_HEALTH_CONCURRENCY",defaultMinimum:e4,defaultMaximum:t4});function CRe(e){if(console.log(`
|
|
934
|
+
Codebase Health Score: ${e.score}/100`),console.log(` Risk: ${e.riskScore}/100 (risk-oriented graph facts + change graph)`),console.log(` Hygiene: ${e.hygieneScore}/100 (tidiness candidates)
|
|
935
|
+
`),console.log(` ${e.overview.documents} files | ${e.overview.symbols} symbols | ${cC(e.overview.indexSizeBytes)}
|
|
936
|
+
`),e.warnings&&e.warnings.length>0){console.log(" Warnings:");for(let n of e.warnings)console.log(` ${n}`);console.log("")}console.log(" Findings:");let t=e.findings;if(t.deadSymbols>0&&console.log(` Dead code: ${t.deadSymbols} symbols (${t.deadLoc} LOC)`),t.isolatedSymbols>0&&console.log(` Isolated symbols: ${t.isolatedSymbols} (${t.isolatedLoc} LOC)`),t.cycles>0&&console.log(` Circular deps: ${t.cycles}`),t.similarPairs>0&&console.log(` Similar pairs: ${t.similarPairs}`),t.twinDriftGroups>0&&console.log(` Drifted twins: ${t.twinDriftGroups} group(s)`),t.reactComponentDuplicatePairs>0&&console.log(` React components: ${t.reactComponentDuplicatePairs} duplicate pair(s)`),t.reactHookCandidatePairs>0&&console.log(` React hook reuse: ${bp(t.reactHookCandidatePairs,t.reactHookCandidateScoreCount)} candidate pair(s)`),t.reactLargeComponentPressureFiles>0&&console.log(` React large comps: ${t.reactLargeComponentPressureFiles} component(s)`),t.vueComponentDuplicatePairs>0&&console.log(` Vue components: ${t.vueComponentDuplicatePairs} duplicate pair(s)`),t.vueComposableCandidatePairs>0&&console.log(` Vue composables: ${bp(t.vueComposableCandidatePairs,t.vueComposableCandidateScoreCount)} candidate pair(s)`),t.vueLargeViewPressureFiles>0&&console.log(` Vue large views: ${t.vueLargeViewPressureFiles} file(s)`),t.extractionCandidates>0&&console.log(` Extract candidates: ${t.extractionCandidates}`),t.wrappers>0&&console.log(` Wrapper functions: ${bp(t.wrappers,t.wrapperScoreCount)}`),t.passthroughs>0&&console.log(` Passthroughs: ${t.passthroughs}`),t.staleTypes>0&&console.log(` Stale abstractions: ${t.staleTypes}`),t.driftedFiles>0&&console.log(` Pattern drift: ${t.driftedFiles} files`),t.complexityHotspotCount>0&&console.log(` Complexity hotspots: ${t.complexityHotspotCount}`),e.actions.length>0){console.log(`
|
|
937
|
+
Prioritized Actions (highest impact + lowest effort first):`);for(let n=0;n<e.actions.length;n++){let r=e.actions[n],i=r.locRecoverable>0?` (~${r.locRecoverable} LOC involved)`:"";console.log(` ${n+1}. [${r.effort} effort / ${r.impact} impact] ${r.description}${i}`)}}if(e.topComplexity.length>0){console.log(`
|
|
938
|
+
Top Complexity Hotspots:`);for(let n of e.topComplexity)console.log(` ${n.score.toFixed(1).padStart(6)} ${n.symbol}`)}if(C4(e),x4(e),e.scoreBreakdown.length>0){console.log(`
|
|
939
|
+
Score Breakdown (100 minus the following):`);for(let n of e.scoreBreakdown)console.log(` -${String(n.points).padStart(2)} ${n.axis}: ${n.detail}`)}e.actions.length===0&&console.log(e.warnings&&e.warnings.length>0?`
|
|
940
|
+
No findings from completed analyses. Review warnings before interpreting this result as clean.`:`
|
|
941
|
+
No issues found. Codebase is clean.`)}function bp(e,t){return Math.abs(e-t)<.01?String(e):`${e} (${S4(t)} score-weighted)`}function S4(e){return Number.isInteger(e)?String(e):e.toFixed(2).replace(/0+$/,"").replace(/\.$/,"")}function x4(e){if(e.pressure.length!==0){console.log(`
|
|
942
|
+
Maintenance Pressure:`);for(let t of e.pressure)console.log(` ${t.category}: ${t.count} / ${t.threshold} threshold (${t.ratio}x, -${t.extraPenalty} ${t.kind})`)}}function C4(e){let t=e.axes;if(console.log(`
|
|
943
|
+
Axes:`),console.log(` Zero-reference candidates: ${t.deletable.loc} LOC across ${t.deletable.symbols} symbols`),t.changeAmplification){let r=t.changeAmplification;console.log(` Change amplification: ${r.medianFilesPerCommit} files/commit median, ${r.p90FilesPerCommit} p90 (${r.commitsAnalyzed} commits)`)}if(t.hiddenCoupling&&t.hiddenCoupling.pairCount>0){console.log(` Hidden coupling: ${t.hiddenCoupling.pairCount} co-changing pair(s) without a dependency edge`);for(let r of t.hiddenCoupling.top.slice(0,3))console.log(` ${r.fileA} <-> ${r.fileB} (${r.together}x together, ${Math.round(r.confidence*100)}%)`)}if(t.churnWeightedComplexity&&t.churnWeightedComplexity.length>0){let r=t.churnWeightedComplexity[0];r.weighted>0&&console.log(` Churn x complexity: hottest is ${r.symbol} (${r.changes} changes, weighted ${r.weighted})`)}let n=t.evidenceQuality;if(console.log(` Evidence quality: ${n.graphFindings} graph-fact finding(s), ${n.heuristicFindings} heuristic finding(s), ${n.userSuppressed} user-suppressed`),e.validation&&e.validation.flaggedFiles>0){let r=e.validation,i=r.ratio===null?"n/a":`${r.ratio}x`;console.log(` Validation: flagged files fix-density ${r.flaggedFixDensity} vs baseline ${r.baselineFixDensity} (${i})`),console.log(` fix-commit signal: subject-keyword heuristic over ${r.validationBasis.commitsScanned} commits`)}}async function RRe(e){let t=mn(i=>{let o=Xn(i,{base:e.base});return o.note?{kind:"complete",result:Pi(i,{base:e.base})}:o.changedFiles.length===0?{kind:"complete",result:Pi(i,{base:e.base})}:{kind:"batched",plan:o}});if(t.kind==="complete")return t.result;let n=vw(t.plan.changedFiles,JQ),r=await gp(n,R4(n.length),i=>w4(i,e));return Gc(t.plan.changedFiles,r)}var R4=Bw({envKey:"SCIP_QUERY_DIFF_IMPACT_CONCURRENCY",defaultMinimum:YQ,defaultMaximum:XQ});function Bw(e){return(t,n=process.env,r=zQ)=>v4(t,n,r,e)}function v4(e,t,n,r){let i=t[r.envKey],o=I4(n,r),s=i?parseInt(i,10):o;return!Number.isFinite(s)||s<1?Math.min(o,e):Math.min(s,e)}function I4(e,t){let n=e(),r=Number.isFinite(n)?Math.max(t.defaultMinimum,n-1):0;return Math.min(t.defaultMaximum,Math.max(t.defaultMinimum,r))}function w4(e,t){let n=process.argv[1]??Sp(import.meta.url),r=[];return t.base&&r.push("--base",t.base),pl({cliPath:n,command:KQ,args:r,env:{...process.env,SCIP_QUERY_DIFF_IMPACT_FILES:JSON.stringify(e)},label:"Diff-impact batch"})}function vRe(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}`);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:"),Ut.list(e.changedSymbols,n=>` ${n.file} ${n.shortName} (fan-in: ${n.fanIn})`)),e.affectedConsumers.length>0&&(console.log(`
|
|
944
|
+
Affected consumer files:`),Ut.list(e.affectedConsumers,n=>` ${n.file} (${n.consumedSymbols} symbol(s))`))}var E4="scip-query-result";var D4=1,k4=1;function $w(e){let t=e.resultSchemaVersion??k4;if(!P4(t))throw new Error("CLI result schema version must be a positive safe integer.");let{producerVersion:n,...r}=e;return{kind:E4,schemaVersion:D4,producer:{name:"scip-query",version:n},resultSchemaVersion:t,...r}}function Hw(e,t){return JSON.stringify(e,null,t?0:2)}function P4(e){return Number.isSafeInteger(e)&&Number(e)>0}var Uw=Symbol("option-value-source"),qw=new Map,Gw=new Map;function TRe(e){qw=new Map(e)}function _Re(e){Gw=new Map(e)}function vs(e){return(...t)=>{let{args:n,opts:r}=B4(t);mn(i=>e({db:i,args:n,opts:r}))}}function yl(e,t){return vs(n=>{let r=Ow(n.db,e,Rs(n.opts,"full"),{quiet:Rs(n.opts,"json")});t({...n,budget:r})})}function LRe(e){return vs(t=>Ni(t,e,{kind:"list"}))}function MRe(e){return vs(t=>Ni(t,e,{kind:"table",headers:e.headers,dashWidths:e.dashWidths}))}function ARe(e){return vs(t=>Ni(t,e,{kind:"grouped",key:e.key}))}function F4(e){return vs(t=>xp(t,e))}function NRe(e){return F4({commandName:e.commandName,query:e.query,emptyMessage:e.emptyMessage,heuristicLabel:e.heuristicLabel,before:e.before,render:(t,n)=>Ut.sectionedReport(e.sections(t,n)),toJson:e.toJson,coverage:e.coverage,agentResult:e.agentResult,after:e.after})}function T4(e,t){return yl(e,n=>xp(n,{...t,commandName:t.commandName??e}))}function ORe(e,t){return T4(e,{commandName:t.commandName??e,query:t.query,emptyMessage:t.emptyMessage,heuristicLabel:t.heuristicLabel,before:t.before,render:(n,r)=>Ut.sectionedReport(t.sections(n,r)),toJson:t.toJson,coverage:t.coverage,agentResult:t.agentResult,after:t.after})}function jRe(e,t){return yl(e,n=>Ni(n,{...t,commandName:e},{kind:"list"}))}function BRe(e,t){return yl(e,n=>Ni(n,{...t,commandName:e},{kind:"table",headers:t.headers,dashWidths:t.dashWidths}))}function $Re(e,t){return yl(e,n=>Ni(n,{...t,commandName:e},{kind:"grouped",key:t.key}))}function HRe(e,t){return String(e[t])}function URe(e,t){let n=e[t];return typeof n=="string"?n:void 0}function qRe(e,t){let n=e[t];return typeof n=="string"?n:void 0}function Vw(e,t){let n=e[t];return typeof n=="number"?n:void 0}function Rs(e,t){return!!e[t]}function GRe(e,t){let n=e[t];return Array.isArray(n)&&n.every(r=>typeof r=="string")?n:[]}function VRe(e,t,n){return Vw(e,t)??n}function WRe(e,t,n){let r=Vw(e,t),i=r!==void 0&&_4(e,t)!=="default";if(Rs(e,"full")){if(i)throw new Error("--full cannot be combined with --limit. Use --full for all findings, or --limit N for a capped report.");return Number.MAX_SAFE_INTEGER}return r??n}function _4(e,t){return e[Uw]?.(t)}function Ni(e,t,n){xp(e,{commandName:t.commandName,query:t.query,emptyMessage:(r,i)=>r.length===0&&t.emptyMessage?t.emptyMessage(i):void 0,heuristicLabel:t.heuristicLabel,render:(r,i)=>{n.kind==="list"?Ut.list(r,o=>t.format(o,i)):n.kind==="table"?Ut.table(n.headers,r.map(o=>t.format(o,i)),n.dashWidths):Ut.groupedByFile(r,o=>t.format(o,i),n.key?o=>n.key(o,i):void 0)},toJson:t.toJson,coverage:t.coverage,agentResult:t.agentResult,before:t.before,after:t.after})}function xp(e,t){let n=t.query(e);if(Rs(e.opts,"json")){if(!t.commandName)throw new Error("JSON output requires a command name so its result contract can be identified.");M4(t.commandName,e.args,e.opts,t.toJson?t.toJson(n,e):n,{analysisBudget:L4(e),coverage:t.coverage?.(n,e),agentResult:t.agentResult?.(n,e)});return}let r=t.emptyMessage?.(n,e);if(r){Ut.empty(r);return}t.heuristicLabel&&Nw(t.heuristicLabel),t.before?.(n,e),t.render(n,e),t.after?.(n,e)}function L4(e){return e.budget?.analysisBudget}function M4(e,t,n,r,i={}){let o=qw.get(e),s=Gw.get(e),a=i.coverage??N4(s,r,i.analysisBudget);a&&A4(a);let c=$w({producerVersion:It,command:e,...o?{evidence:o}:{},...i.analysisBudget?{analysisBudget:i.analysisBudget}:{},args:j4(t),options:n,result:r,...a?{coverage:a}:{},...i.agentResult!==void 0?{agentResult:i.agentResult}:{},...i.resultSchemaVersion===void 0?{}:{resultSchemaVersion:i.resultSchemaVersion}});console.log(Hw(c,Rs(n,"compact")))}function A4(e){if(!Number.isSafeInteger(e.returned)||e.returned<0)throw new Error("Invocation coverage returned count must be a non-negative safe integer.");if(e.complete===!0&&!e.totalKnown)throw new Error("Complete invocation coverage must know its total.");if(e.totalKnown){if(!Number.isSafeInteger(e.total)||(e.total??-1)<e.returned)throw new Error("Known invocation coverage total must be a safe integer at least as large as returned.");let t=e.total-e.returned;if(e.omitted!==t)throw new Error("Known invocation coverage omitted count must equal total minus returned.")}else if(e.total!==void 0||e.omitted!==void 0)throw new Error("Unknown invocation coverage cannot claim a total or omitted count.");if(e.omittedIdentities&&e.omittedIdentities.length!==e.omitted)throw new Error("Omitted identity count must equal the disclosed omitted count.")}function N4(e,t,n){if(!e)return;let r=O4(t);return e.coverage==="complete"?{complete:!0,totalKnown:!0,returned:r,total:r,omitted:0}:e.coverage==="sampled"?{complete:!1,totalKnown:!1,returned:r}:e.coverage==="bounded"&&n?{complete:!1,totalKnown:!1,returned:r}:{complete:null,totalKnown:!1,returned:r}}function O4(e){if(Array.isArray(e))return e.length;if(!e||typeof e!="object")return e==null?0:1;let t=e;if(Array.isArray(t.rows))return t.rows.length;let n=Object.values(t).filter(Array.isArray);return n.length>0?n.reduce((r,i)=>r+i.length,0):1}function j4(e){return e.filter(t=>typeof t=="string"||typeof t=="number"||typeof t=="boolean")}function B4(e){if(e.length===0)return{args:[],opts:{}};let t=e[e.length-1];return{args:e.slice(0,-1),opts:$4(t)}}function $4(e){if(!e||typeof e!="object")return{};let t=e;if(typeof t.opts=="function"){let n=t.opts();return!n||typeof n!="object"?{}:(typeof t.getOptionValueSource=="function"&&Object.defineProperty(n,Uw,{value:r=>t.getOptionValueSource(r),enumerable:!1}),n)}return e}export{Cl as a,Ep as b,H4 as c,q as d,Is as e,Oi as f,ws as g,Tt as h,K4 as i,Pp as j,Kw as k,Ne as l,o3 as m,M as n,M8 as o,Gr as p,Mt as q,He as r,G as s,Qp as t,Zp as u,eg as v,RE as w,E as x,m3 as y,vn as z,H as A,ct as B,w3 as C,E3 as D,Y as E,nP as F,Z8 as G,Vg as H,d9 as I,ae as J,I as K,F as L,Q as M,De as N,$ as O,to as P,z9 as Q,zo as R,qt as S,PC as T,Cce as U,K7 as V,Tu as W,J7 as X,fy as Y,EL as Z,Mu as _,ree as $,PL as aa,iee as ba,gy as ca,va as da,Ln as ea,ln as fa,ft as ga,Rt as ha,we as ia,so as ja,ei as ka,vt as la,Ia as ma,rt as na,Nn as oa,wa as pa,ii as qa,mr as ra,Ea as sa,_M as ta,qu as ua,fo as va,Wte as wa,yne as xa,bne as ya,qA as za,Sb as Aa,sd as Ba,qe as Ca,b3 as Da,Nr as Ea,NE as Fa,og as Ga,S3 as Ha,Ps as Ia,_t as Ja,li as Ka,ui as La,Ot as Ma,Fb as Na,lN as Oa,$a as Pa,Gb as Qa,Ka as Ra,yie as Sa,Er as Ta,p1 as Ua,S1 as Va,Kie as Wa,Am as Xa,Nm as Ya,Om as Za,jm as _a,Bm as $a,Dr as ab,bH as bb,CH as cb,RH as db,vH as eb,ioe as fb,NH as gb,BH as hb,$H as ib,HH as jb,qH as kb,GH as lb,VH as mb,iR as nb,kr as ob,mU as pb,Qo as qb,gU as rb,hU as sb,vU as tb,DU as ub,Vm as vb,Mc as wb,Ym as xb,Zo as yb,yq as zb,es as Ab,ts as Bb,Qm as Cb,ns as Db,rs as Eb,Zm as Fb,lG as Gb,is as Hb,gV as Ib,cf as Jb,lf as Kb,KV as Lb,ss as Mb,Xn as Nb,wv as Ob,Yz as Pb,ds as Qb,hK as Rb,ps as Sb,gs as Tb,ys as Ub,bs as Vb,fJ as Wb,Bf as Xb,Hf as Yb,qf as Zb,Vf as _b,Uhe as $b,xI as ac,Wf as bc,kJ as cc,PJ as dc,FJ as ec,TJ as fc,MJ as gc,AJ as hc,NJ as ic,OJ as jc,bY as kc,SY as lc,DY as mc,HY as nc,KY as oc,d5 as pc,Qf as qc,ep as rc,al as sc,q5 as tc,tp as uc,Ft as vc,fSe as wc,pSe as xc,SSe as yc,xSe as zc,rp as Ac,CSe as Bc,ul as Cc,op as Dc,yX as Ec,XX as Fc,doe as Gc,QX as Hc,cQ as Ic,gQ as Jc,vS as Kc,Za as Lc,Nd as Mc,IS as Nc,ec as Oc,DS as Pc,rc as Qc,gi as Rc,pi as Sc,xO as Tc,sc as Uc,zS as Vc,Joe as Wc,Yoe as Xc,Xoe as Yc,Qoe as Zc,Zoe as _c,Lo as $c,cx as ad,Rj as bd,dse as cd,Mo as dd,mx as ed,It as fd,tm as gd,nm as hd,Rse as id,_se as jd,Lse as kd,Mse as ld,Ase as md,Use as nd,qse as od,Gse as pd,Vse as qd,tae as rd,aae as sd,cae as td,bc as ud,Qx as vd,Zx as wd,Ir as xd,eC as yd,Sm as zd,_ae as Ad,xm as Bd,Im as Cd,sC as Dd,qae as Ed,aC as Fd,Gae as Gd,Vae as Hd,Wae as Id,mn as Jd,zae as Kd,cC as Ld,Kae as Md,Cw as Nd,Tr as Od,Rw as Pd,KCe as Qd,lC as Rd,GB as Sd,Yae as Td,Xae as Ud,Ut as Vd,Lw as Wd,KQ as Xd,Nw as Yd,Ow as Zd,SRe as _d,xRe as $d,CRe as ae,RRe as be,vRe as ce,TRe as de,_Re as ee,vs as fe,yl as ge,LRe as he,MRe as ie,ARe as je,F4 as ke,NRe as le,T4 as me,ORe as ne,jRe as oe,BRe as pe,$Re as qe,HRe as re,URe as se,qRe as te,Vw as ue,Rs as ve,GRe as we,VRe as xe,WRe as ye,_4 as ze,M4 as Ae,B4 as Be,$4 as Ce};
|
|
945
|
+
//# sourceMappingURL=chunk-JJJCO4QC.js.map
|