From 5a73f7f12bf1a2dc3ed1b281bb6cdb8d1a49b59a Mon Sep 17 00:00:00 2001
From: Mucheen <1528136628@qq.com>
Date: Thu, 19 Nov 2026 14:35:51 +0800
Subject: [PATCH 1/6] feat(python): package interpreter discovery and Pyrefly
bootstrap
---
.cargo/config.toml | 13 +
.github/workflows/ci.yml | 23 +-
.github/workflows/package.yml | 70 ++
.gitignore | 2 +
README.md | 45 +-
backend/Cargo.lock | 329 ++++++++
backend/Cargo.toml | 19 +
backend/src/discovery.rs | 290 +++++++
backend/src/discovery/metadata.rs | 207 +++++
backend/src/discovery/project.rs | 259 +++++++
backend/src/inspect.rs | 47 ++
backend/src/main.rs | 25 +
backend/src/pyrefly.rs | 128 +++
backend/src/requirements.rs | 130 ++++
docs/feature-matrix.md | 16 +-
.../python_support_plugin_e2e_test.go | 211 +++--
e2e/host/lithe-host.json | 6 +-
.../plugin.json | 31 +-
.../scripts/backend.py | 177 -----
.../scripts/lithe_rpc.py | 170 +---
.../scripts/toolchain_provider.py | 727 ------------------
scripts/lib/backend.mjs | 74 ++
scripts/package.mjs | 10 +
scripts/package/archives.test.mjs | 32 +-
scripts/test.mjs | 161 ++--
25 files changed, 1910 insertions(+), 1292 deletions(-)
create mode 100644 .cargo/config.toml
create mode 100644 .github/workflows/package.yml
create mode 100644 backend/Cargo.lock
create mode 100644 backend/Cargo.toml
create mode 100644 backend/src/discovery.rs
create mode 100644 backend/src/discovery/metadata.rs
create mode 100644 backend/src/discovery/project.rs
create mode 100644 backend/src/inspect.rs
create mode 100644 backend/src/main.rs
create mode 100644 backend/src/pyrefly.rs
create mode 100644 backend/src/requirements.rs
delete mode 100644 io.github.lithe-idea.python-support/scripts/backend.py
delete mode 100644 io.github.lithe-idea.python-support/scripts/toolchain_provider.py
create mode 100644 scripts/lib/backend.mjs
diff --git a/.cargo/config.toml b/.cargo/config.toml
new file mode 100644
index 0000000..59f0f82
--- /dev/null
+++ b/.cargo/config.toml
@@ -0,0 +1,13 @@
+# The package-local backend must start without a separately installed CRT.
+[target.x86_64-pc-windows-msvc]
+rustflags = ["-C", "target-feature=+crt-static"]
+
+[target.aarch64-pc-windows-msvc]
+rustflags = ["-C", "target-feature=+crt-static"]
+
+# The bundled musl targets use Rust's linker, including for local cross-builds.
+[target.x86_64-unknown-linux-musl]
+linker = "rust-lld"
+
+[target.aarch64-unknown-linux-musl]
+linker = "rust-lld"
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 4d951b5..ae36c7c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -10,6 +10,10 @@ permissions:
jobs:
package:
+ uses: ./.github/workflows/package.yml
+
+ verify-store:
+ needs: package
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
@@ -17,9 +21,14 @@ jobs:
- uses: actions/setup-node@v4
with:
node-version: 22
- - name: Build all 6 platform archives
- run: node scripts/package.mjs
- - name: Verify release archives
+ - uses: actions/download-artifact@v4
+ with:
+ pattern: python-support-archive-*
+ merge-multiple: true
+ path: dist
+ - name: Verify six release archives
+ env:
+ LITHE_EXPECT_ALL_ARCHIVES: "1"
run: node --test --test-timeout=60000 scripts/package/*.test.mjs
- name: Validate against Lithe Store rules
run: |
@@ -37,12 +46,6 @@ jobs:
}
process.exit(failed ? 1 : 0);
"
- - name: Upload built platform archives
- uses: actions/upload-artifact@v4
- with:
- name: python-support-archives
- path: dist/python-support-*.zip
- if-no-files-found: error
commands:
needs: package
@@ -72,7 +75,7 @@ jobs:
run: python -m pip install --disable-pip-version-check pytest
- uses: actions/download-artifact@v4
with:
- name: python-support-archives
+ name: python-support-archive-${{ matrix.platform }}
path: dist
- name: Unpack Windows archive under a path with spaces
if: runner.os == 'Windows'
diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml
new file mode 100644
index 0000000..4cfb10e
--- /dev/null
+++ b/.github/workflows/package.yml
@@ -0,0 +1,70 @@
+name: Package Python Support
+
+on:
+ workflow_call:
+ inputs:
+ tag:
+ type: string
+ required: false
+
+permissions:
+ contents: read
+
+jobs:
+ package:
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 20
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - os: macos-latest
+ platform: darwin-arm64
+ target: aarch64-apple-darwin
+ - os: macos-15-intel
+ platform: darwin-x64
+ target: x86_64-apple-darwin
+ - os: ubuntu-latest
+ platform: linux-x64
+ target: x86_64-unknown-linux-musl
+ - os: ubuntu-24.04-arm
+ platform: linux-arm64
+ target: aarch64-unknown-linux-musl
+ - os: windows-latest
+ platform: windows-x64
+ target: x86_64-pc-windows-msvc
+ - os: windows-11-arm
+ platform: windows-arm64
+ target: aarch64-pc-windows-msvc
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ - name: Configure Rust
+ shell: bash
+ env:
+ TARGET: ${{ matrix.target }}
+ run: |
+ rustup toolchain install 1.87 --profile minimal --target "$TARGET"
+ rustup override set 1.87
+ - name: Test backend
+ run: cargo test --locked --manifest-path backend/Cargo.toml
+ - name: Assemble plugin archive
+ shell: bash
+ env:
+ PLATFORM: ${{ matrix.platform }}
+ TAG: ${{ inputs.tag }}
+ run: |
+ args=(--platform "$PLATFORM")
+ if [[ -n "$TAG" ]]; then
+ args+=(--expect-tag "$TAG")
+ fi
+ node scripts/package.mjs "${args[@]}"
+ - name: Verify archive
+ run: node --test --test-timeout=60000 scripts/package/archives.test.mjs
+ - uses: actions/upload-artifact@v4
+ with:
+ name: python-support-archive-${{ matrix.platform }}
+ path: dist/python-support-*-${{ matrix.platform }}.zip
+ if-no-files-found: error
diff --git a/.gitignore b/.gitignore
index 1245915..3c2c02d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,3 +4,5 @@
dist/
**/__pycache__/
*.py[cod]
+
+/backend/target/
diff --git a/README.md b/README.md
index 07deecd..ab15821 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# Python Support for Lithe (`io.github.lithe-idea.python-support`)
-Python language support plugin for Lithe (`v0.2.0`, `schemaVersion: 0`, `pluginAPIVersion: 0`), bundling [Pyrefly](https://github.com/facebook/pyrefly) `1.4.1` for fast static type checking and LSP navigation, [debugpy](https://github.com/microsoft/debugpy) `1.8.22` for source-level debugging, and a zero-compilation pure-Python (`python -I -B`) plugin backend and build provider.
+Python language support plugin for Lithe (`schemaVersion: 0`, `pluginAPIVersion: 0`), bundling [Pyrefly](https://github.com/facebook/pyrefly) `1.4.1` for fast static type checking and LSP navigation, [debugpy](https://github.com/microsoft/debugpy) `1.8.22` for source-level debugging, a packaged Rust backend for interpreter discovery and language-server startup, and a Python build provider for model, run, and pytest integration.
遵循 Lithe 插件契约 v1(`schemaVersion: 0`),为 Lithe 桌面端(macOS / Windows / Linux)提供开箱即用的 Python 语言支持、宿主工具链驱动的 `Pyrefly` 解释器注入、`.venv` / `.conda` / `conda` / `uv` / `pyenv` 多来源环境发现、动态 `pytest` 测试树收集与执行、`uv` / `conda` / `Ruff` 构建任务、源码级断点调试及新建项目向导。跨平台实现与验证记录详见 [docs/feature-matrix.md](docs/feature-matrix.md)。
@@ -11,13 +11,14 @@ Python language support plugin for Lithe (`v0.2.0`, `schemaVersion: 0`, `pluginA
1. **语言与编辑器基础(`languages: python`)**
- 识别 `.py`、`.pyi`、`.pyw`,配置 `#` 行注释与括号/引号自动配对,声明 `pyproject.toml` / `setup.py` / `setup.cfg` / `requirements.txt` / `Pipfile` / `pyrefly.toml` 项目标记及 `.venv` / `venv` / `.conda` 项目依赖目录。
2. **后端解析的语言服务器启动与解释器自动注入(`backend` + `languageServers: python` / Pyrefly `1.4.1`)**
- - 启动语言服务器前,宿主需要能够发现 Python 3.9 或更高版本以执行启动解析后端。宿主会传入可用于自动启动的解释器路径,项目内环境交由 Pyrefly 按自身规则发现。
- - 构建期按平台固定版本与 SHA-256 打包 `pyrefly 1.4.1`(Unix:`bin/pyrefly`,Windows:`bin/pyrefly.exe`),6 个平台发布包共享同一套纯 Python(`python -I -B`)插件后端 `scripts/backend.py`。
+ - 插件包内的 Rust 后端直接启动 Pyrefly,无需先找到 Python。宿主会传入可用于自动启动的解释器路径,缺失时由 Pyrefly 按自身规则发现项目环境。构建、测试与调试仍用宿主选择的 Python。
+ - 构建期按平台固定版本与 SHA-256 打包 `pyrefly 1.4.1`(Unix:`bin/pyrefly`,Windows:`bin/pyrefly.exe`),每个包也包含同一目标架构的 `bin/lithe-python-backend`(Windows 为 `.exe`)。
- `languageServers[0]` 采用 `"launch": {"kind": "backend", "function": "pyrefly.resolveLaunch", "timeoutMilliseconds": 30000}`:根据 `platform.os` 动态返回包内 `bin/pyrefly` 或 `bin/pyrefly.exe` 与 `arguments: ["lsp"]`,合并全部即时设置(`typeCheckingMode`、`displayTypeErrors`、`diagnosticMode`、`autoImportCompletions`、`completeFunctionParens`、`importFormat`)。
- 当宿主在调用参数中传入已选定的非项目内解释器 `tools.python.executable`(如外部 `conda`、`uv`、`pyenv` 或系统环境)时,自动注入 `workspaceConfiguration.python.pythonPath`;当 `tools.python` 缺失(未选定或项目内虚拟环境尚未获信任)时优雅省略 `pythonPath`,保留 `pyrefly` 原生 `.venv` / `pyproject.toml` 自动发现且不阻断启动。
-3. **工具链与多环境发现增强(`toolDefinitions: python` + `toolchain_provider.py`)**
+3. **工具链与多环境发现增强(`toolDefinitions: python` + `toolchainProviders: 0`)**
- 严格按 Core 4 层优先级解析:项目级显式绑定 → 项目内环境(`.venv` / `venv` / `.conda`,`projectKind: "environment"`,受宿主工作区信任门控并保留字面软链路径)→ 全局设置 → `VIRTUAL_ENV` 与 `PATH`(`python3` / `python`)→ 16 条跨平台自动发现规则(覆盖 `UV_PYTHON_INSTALL_DIR`、`XDG_DATA_HOME`、`PYENV_ROOT`、`CONDA_ENVS_PATH`、`CONDA_PREFIX`、`WORKON_HOME`、`LOCALAPPDATA`、`APPDATA`、Homebrew、macOS Framework、`~/.pyenv`、`~/.local/share/uv`、`*conda*/envs/*`、`miniforge*/envs/*`)。
- - `scripts/toolchain_provider.py` 完整实现 `litheToolchains`(`toolchains/query`)协议(支持 `~/.conda/environments.txt`、`CONDA_ENVS_PATH`、`UV_PYTHON_INSTALL_DIR`、`PYENV_ROOT`、Poetry 与 Pipenv 外部虚拟环境、`.python-version` 与 `pyproject.toml` `requires-python`)。当前桌面宿主通过清单中的 `toolDefinitions` 发现已安装解释器。提供者协议可独立验证,在桌面端启用还需要宿主支持 `toolchainProviders`、清单声明以及满足 Core 自举契约的打包运行时。
+ - Rust 提供者读取 conda 环境登记表和安装元数据,以及 uv、pyenv、Poetry、Pipenv 管理的外部环境。项目中的 `.python-version` 选择版本,同一目录的 `pyproject.toml` 限制可选版本。宿主观察这些输入并在变化后重新查询。
+ - 需要支持 `toolchainProviders: 0` 的 Lithe 桌面端。外部环境的解释器链接若指向环境目录之外,Core 会拒绝将该环境作为提供者候选。常见于以链接方式创建的 Unix Poetry/Pipenv 环境。使用常规可执行文件副本的环境可被发现,项目内 `.venv` 继续使用宿主的信任流程。
4. **4 个独立构建系统与动态 `pytest` 测试树(`buildSystems` & `buildProviders`)**
- `python`:通过纯 Python 构建提供者 `scripts/build_provider.py --cache ${workspaceStateDir}`(`python -I -B`,`executesProjectCode: true`,`mayUseNetwork: false`)承载:
- `lithe/build/model`:复用 `scripts/build_model.py` 纯 `ast` + `tomllib`(Python 3.9–3.10 自动回退内置 `vendor/tomli`)静态提取 `[project.scripts]`、包 `__main__.py`、顶层 `__main__` 脚本、Django `manage.py`、FastAPI ASGI、Flask WSGI 运行目标(绝不执行用户代码),派生 7 类声明式 `run` 配置;
@@ -37,27 +38,27 @@ Python language support plugin for Lithe (`v0.2.0`, `schemaVersion: 0`, `pluginA
## 日志接线说明(Structured Logging v2 Wiring)
-本插件 `0.2.0` 包含纯 Python 插件后端(`scripts/backend.py`)、构建提供者(`scripts/build_provider.py`)与声明式贡献,全部诊断严格遵循 Lithe 结构化日志 v2 规范(Core `rust/logging/README.md`、`shared/plugins/contract/v1/README.md#structured-plugin-diagnostics` 与 `shared/plugins/guides/plugin-logging.md`),**零自建插件日志文件**,已安装插件目录在运行期保持 **100% 只读**。
+插件包含包内 Rust SDK 后端、构建提供者(`scripts/build_provider.py`)与声明式贡献,诊断通过 Lithe 结构化日志 v2 规范(Core `rust/logging/README.md`、`shared/plugins/contract/v1/README.md#structured-plugin-diagnostics` 与 `shared/plugins/guides/plugin-logging.md`),**零自建插件日志文件**,已安装插件目录在运行期保持 **100% 只读**。
### 1. 后端与构建 Provider 协议接线(统一通道:`plugins/io.github.lithe-idea.python-support/host`)
-`scripts/lithe_rpc.py` 实现 stdio JSON-RPC 2.0 协议帧传输,与宿主代记的声明式贡献共用同一个结构化日志通道 `plugins/io.github.lithe-idea.python-support/host`(见 Core `rust/logging/events/plugins.json`):
-- **强制协商 `litheLogging` 0**:`initialize` 缺少 `experimental.litheLogging` `versions: [0]` 时立即以 `-32600` 拒绝握手;握手成功后将 Python 层 `sys.stdout` 重定向到 `sys.stderr`,确保 `stdout` 仅输出合法 `Content-Length` JSON-RPC 帧。
+Rust SDK 和构建提供者的 `scripts/lithe_rpc.py` 通过 stdio JSON-RPC 2.0 发送结构化诊断,与宿主代记的声明式贡献共用通道 `plugins/io.github.lithe-idea.python-support/host`(见 Core `rust/logging/events/plugins.json`):
+- **强制协商 `litheLogging` 0**:`initialize` 缺少 `experimental.litheLogging` `versions: [0]` 时立即以 `-32600` 拒绝握手;两种后端的 `stdout` 均只输出 `Content-Length` JSON-RPC 帧。
- **请求级 `operationId` 关联与时序**:所有 `lithe/log` 通知严格在对应 JSON-RPC 响应帧发出**之前**写入 `stdout`,携带宿主请求传入的 `operationID`(回退为受控请求 ID),确保 Core 将诊断精确关联到活跃操作。
-- **取消不记失败**:收到 `$/cancelRequest` 时立即终止关联子进程组(POSIX `os.killpg` / Windows `taskkill /T /F`),返回 `-32800` 且**不发送** `operationFinished` 或 `operationFailed`。
+- **取消不记失败**:收到 `$/cancelRequest` 时停止扫描或终止构建子进程组(POSIX 进程组 / Windows Job Object),返回 `-32800` 且不发送 `operationFinished` 或 `operationFailed`。
| `operation` | 所属进程 | 成功事件与级别 | 降级 / 恢复事件(`WARN`) | 失败事件与级别(`ERROR`) | 受控 `code` 类别标识 |
| --- | --- | --- | --- | --- | --- |
-| `initialize` | `backend.py` / `build_provider.py` | 握手由 Core 记录 `plugins.host.protocol.initialized`(`INFO`) | `plugins.operation.fallback_selected`(`code: "functions_unavailable"`,当宿主未协商 `litheFunctions` 时) | 握手失败由 Core / 宿主记录 | `functions_unavailable` |
-| `pyrefly.resolveLaunch` | `backend.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "invalid_tool_hint"`,`count: 1`)
恢复:`plugins.operation.recovery_finished`(`code: "tool_hint_restored"`,`count: 1`) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `invalid_tool_hint`、`tool_hint_restored`、`python.unknownServer`、`internal_error` |
-| `python.inspectEnvironment` | `backend.py` | **已启用 `suppressSuccessDiagnostics`**(高频只读查询成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidExecutable`、`internal_error` |
+| `initialize` | Rust 后端 / `build_provider.py` | 握手由 Core 记录 `plugins.host.protocol.initialized`(`INFO`) | — | 握手失败由 Core / 宿主记录 | 宿主协议错误 |
+| `pyrefly.resolveLaunch` | Rust 后端 | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "invalid_tool_hint"`,`count: 1`)
恢复:`plugins.operation.recovery_finished`(`code: "tool_hint_restored"`,`count: 1`) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `invalid_tool_hint`、`tool_hint_restored`、`python.unknownServer`、`internal_error` |
+| `python.inspectEnvironment` | Rust 后端 | **已启用 `suppressSuccessDiagnostics`**(高频只读查询成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidExecutable`、`python.environmentUnavailable`、`internal_error` |
| `lithe/build/model` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "pyproject_parse_failed"`,`count: 1`)
恢复:`plugins.operation.recovery_finished`(`code: "pyproject_restored"`,`count: 1`) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `pyproject_parse_failed`、`pyproject_restored`、`python.invalidRoot`、`python.projectUnavailable`、`internal_error` |
| `lithe/build/discoverTests` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "test_discovery_truncated"`,`count` 为超出条数、大小或无法表示为有效选择器而省略的条目数) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `test_discovery_truncated`、`python.pytestUnavailable`、`python.pytestTimedOut`、`python.pytestCollectionFailed`、`python.interpreterUnavailable`、`python.cacheUnavailable` |
| `lithe/build/test` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`;测试断言失败仍属正常协议返回 `exitCode != 0`,失效/越界选择器、进程级超时或解释器缺失才记 `ERROR`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidTestSelector`、`python.staleTestSelector`、`python.pytestTimedOut`、`python.interpreterUnavailable`、`python.projectUnavailable`、`internal_error` |
| `lithe/build/runEntrypoints` | `build_provider.py` | **已启用 `suppressSuccessDiagnostics`**(打开文件高频静态入口探测成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidRoot`、`python.projectUnavailable`、`internal_error` |
| `notification` / `result-encoding` / `shutdown` | `lithe_rpc.py` | — | — | `plugins.operation.failed`(`ERROR`) | `framing_error`、`result_encoding_failed`、`internal_error` |
-> 注:`toolchains/query` 的错误码与超时由工具链契约(`plugin.toolchain.*`)结构化返回并由宿主工具链层统一观测;因 Core `plugin_logging` 操作白名单未纳入 `toolchains/query`,后端不为其额外发送 `lithe/log` 以避免产生 `plugins.diagnostics.rejected`。
+`toolchains/query` 是高频只读操作,成功由 SDK 返回事实。取消、读取失败、扫描超限与不安全输入通过 `plugin.toolchain.*` 结构化返回。宿主工具链层观察并处理查询及解码失败。协议 v0 的 SDK 无该操作的诊断回调。
### 2. 宿主代记的声明式插件操作(通道:`plugins/io.github.lithe-idea.python-support/host`)
@@ -72,7 +73,7 @@ Python language support plugin for Lithe (`v0.2.0`, `schemaVersion: 0`, `pluginA
| 组件 / 命令 | v2 结构化通道或原生文件位置 | 级别、限流、脱敏与清理策略 |
| --- | --- | --- |
-| `backend.py` / `build_provider.py`(纯 Python 后端与构建 Provider) | 结构化通道:`plugins/io.github.lithe-idea.python-support/host`
未分类 `stderr`:`plugins.host.stderr.received`(`DEBUG`) | **零自建日志文件**;会话启动与握手由 Core 记录 `plugins.host.process.started` / `plugins.host.protocol.initialized` / `plugins.host.session.updated`;未预期异常在 `stderr` 仅输出 `: ()` 受控短词,**绝不拼接文件路径、命令参数、源码片段、输出内容或环境变量值**。Core 对 `stderr` 按每行 4 KiB 限流并脱敏截断,仅在详细诊断开启时落盘。 |
+| Rust 后端 / `build_provider.py` | 结构化通道:`plugins/io.github.lithe-idea.python-support/host`
未分类 `stderr`:`plugins.host.stderr.received`(`DEBUG`) | **零自建日志文件**;会话启动与握手由 Core 记录 `plugins.host.process.started` / `plugins.host.protocol.initialized` / `plugins.host.session.updated`;未预期异常在 `stderr` 仅输出 `: ()` 受控短词,**绝不拼接文件路径、命令参数、源码片段、输出内容或环境变量值**。Core 对 `stderr` 按每行 4 KiB 限流并脱敏截断,仅在详细诊断开启时落盘。 |
| `pyrefly lsp`(语言服务器) | 结构化通道:`plugins/io.github.lithe-idea.python-support/host`(或宿主内置 `lsp/python`) | Core 记录 `plugins.host.process.started`、`plugins.host.protocol.initialized`、`plugins.host.session.updated`;`window/logMessage` 与 `window/showMessage` 保留显式 `ERROR`/`WARN`/`INFO`/`DEBUG` 级别;未分类 `stderr` 经 `plugins.host.stderr.received` 记为 `DEBUG`(仅详细诊断开启时落盘);详细诊断开启(15 分钟单次到期)时仅接纳 `$/logTrace.message` 摘要,拒绝 `verbose` 载荷。`pyrefly` 不写任何插件内文件。 |
| `debugpy`(调试适配器与启动器) | 结构化通道:`debug/debugpy`
原生日志文件:`sessions//plugins/io.github.lithe-idea.python-support/files/debugpy.*.log` | 结构化会话事件写入 `debug/debugpy`;上游 `debugpy` 原生日志通过 `--log-dir ${logDir}` 定向写入宿主 `Store.PluginFilesDirectory` 创建的当前会话专属目录(权限 `0700`,逐段校验拒绝软链越界,绝不写插件安装目录或 app bundle),按 `` 建文件并随宿主日志会话生命周期统一保留与清理。 |
| `pytest`、构建任务与项目生成 | 构建/测试面板流式输出(`lithe/build/progress`)与 JUnit XML(`.pytest_cache/lithe-junit.xml`) | `lithe/build/discoverTests` 将 `pytest` 缓存重定向至 `${workspaceStateDir}`;进程 `stdout`、用户测试代码与环境变量值仅进入协议进度流或报告文件,绝不进入 v2 结构化诊断日志。 |
@@ -86,34 +87,42 @@ Python language support plugin for Lithe (`v0.2.0`, `schemaVersion: 0`, `pluginA
| 路径 | 归属与用途 | 生命周期 | 跨 Git Worktree 复用策略 |
| --- | --- | --- | --- |
| `.cache/` | `scripts/package.mjs` 下载并经 SHA-256 校验的上游原始归档(`pyrefly` 6 平台压缩包、`debugpy` wheel、`tomli` wheel) | 本地持久化缓存(已被 `.gitignore` 忽略) | **可安全复制复用**(文件名含上游版本与平台,读取前强制校验 `vendor-lock.json` SHA-256;复制到新工作树 `.cache/`,勿跨并发打包共享写) |
+| `backend/target/` | Rust 后端编译输出,包含按平台目标区分的产物 | 随工作树保留,可重新由 Cargo 生成 | 不共享,构建时由固定的 Cargo.lock 和 Rust 目标重建。Cargo 使用全局 registry 与 Git 依赖下载缓存。 |
| `.artifacts/stage/` | 打包过程中的单平台解包暂存目录 | 每次 `scripts/package.mjs` 按平台重建(`.gitignore` 忽略) | **不可复用**(构建中间产物,毫秒级重建) |
| `.artifacts/lithe-host/` | `scripts/e2e-host.mjs` 检出的宿主稀疏工作树及其编译产物 | 本地按需保留(`.gitignore` 忽略) | 其内部 `.artifacts/desktop` 在同一操作系统、CPU 架构与相同 `PINNED_CORE_REVISION` 前提下可按宿主规则复制加速,不得跨工作树软链共用;任何运行时会话日志目录(`sessions//plugins/.../files/`)与状态目录严禁跨工作树复制 |
| `dist/` | 最终产出的 `python-support--.zip` 发布包 | 打包输出(`.gitignore` 忽略) | 按需重新运行 `node scripts/package.mjs` 生成 |
### 常用命令
+打包需要 Node.js 与 Rust 1.87,并由 `backend/Cargo.lock` 固定依赖。SDK 固定到 Core 的 Git 提交。Linux 目标使用 musl,Windows 使用 MSVC 并静态链接 C 运行库,macOS 使用系统链接器。发布使用 CI 的六平台构建矩阵。
+
插件测试使用真实 pytest。将 pytest 安装到 `PYTHON` 对应的环境,或通过 `PYTEST_PYTHON` 指定已安装 pytest 的解释器。
```bash
# 打包当前开发平台(例如 macOS Apple Silicon)
node scripts/package.mjs --platform darwin-arm64
-# 打包全部 6 个目标平台(darwin-arm64, darwin-x64, windows-x64, windows-arm64, linux-x64, linux-arm64)
+# 本机具备全部六种 Rust 目标和链接器时打包全部平台
node scripts/package.mjs
# 校验 dist/ 下构建产物的目录安全性、Windows 文件名/大小写兼容性与清单一致性
node --test --test-timeout=60000 scripts/package/*.test.mjs
-# 运行契约不变量检查、backend/build_provider/toolchain_provider 协议单测、pyrefly LSP 解释器注入与回退、pytest 动态发现与执行、debugpy 调试及只读包哈希不变断言
+# 运行 Rust 规则测试、打包后端协议验证及真实 Pyrefly / pytest / debugpy 工作流
+cargo test --locked --manifest-path backend/Cargo.toml
node scripts/test.mjs
-# 针对真实 Lithe 桌面宿主与 Rust Core 运行端到端集成测试
+# 使用 e2e/host/lithe-host.json 固定的兼容桌面候选
node scripts/e2e-host.mjs
+
+# 也可使用另一个兼容的本地检出和提交
+node scripts/e2e-host.mjs --source /path/to/Lithe-IDEA --ref COMPATIBLE_HOST_COMMIT
```
---
## 许可证(License)
-- 插件清单、脚本、模板、图标与文档采用 [Apache-2.0](LICENSE) 许可协议。
+- 插件清单、Rust 后端、脚本、模板、图标与文档采用 [Apache-2.0](LICENSE) 许可协议。
- 随包分发的第三方开源组件(Pyrefly `1.4.1`、debugpy `1.8.22`、Tomli `2.5.0`,均为 MIT 许可)完整版权声明与许可证全文见 [io.github.lithe-idea.python-support/THIRD-PARTY-NOTICES.txt](io.github.lithe-idea.python-support/THIRD-PARTY-NOTICES.txt) 及包内 `vendor/debugpy/ThirdPartyNotices.txt`。
+- Rust 后端的依赖及对应许可证由 `Cargo.lock` 固定,全文随包附在 `RUST-THIRD-PARTY-NOTICES.txt`。
diff --git a/backend/Cargo.lock b/backend/Cargo.lock
new file mode 100644
index 0000000..fee9c6e
--- /dev/null
+++ b/backend/Cargo.lock
@@ -0,0 +1,329 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "base64"
+version = "0.22.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer",
+ "crypto-common",
+]
+
+[[package]]
+name = "dunce"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
+
+[[package]]
+name = "equivalent"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
+
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+
+[[package]]
+name = "indexmap"
+version = "2.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
+dependencies = [
+ "equivalent",
+ "hashbrown",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
+
+[[package]]
+name = "libc"
+version = "0.2.191"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
+
+[[package]]
+name = "lithe-plugin-sdk"
+version = "0.4.0"
+source = "git+https://github.com/Lithe-IDEA/Lithe-core-rust.git?rev=e56af624d3f615982f90c6249f7aa43c9b3b218e#e56af624d3f615982f90c6249f7aa43c9b3b218e"
+dependencies = [
+ "base64",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "lithe-python-backend"
+version = "0.1.0"
+dependencies = [
+ "base64",
+ "dunce",
+ "lithe-plugin-sdk",
+ "pep440_rs",
+ "serde_json",
+ "sha2",
+ "toml",
+]
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "pep440_rs"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "31095ca1f396e3de32745f42b20deef7bc09077f918b085307e8eab6ddd8fb9c"
+dependencies = [
+ "once_cell",
+ "serde",
+ "unicode-width",
+ "unscanny",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.154"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "serde_spanned"
+version = "1.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "toml"
+version = "0.9.12+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863"
+dependencies = [
+ "indexmap",
+ "serde_core",
+ "serde_spanned",
+ "toml_datetime",
+ "toml_parser",
+ "toml_writer",
+ "winnow 0.7.15",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "0.7.5+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "toml_parser"
+version = "1.1.5+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
+dependencies = [
+ "winnow 1.0.5",
+]
+
+[[package]]
+name = "toml_writer"
+version = "1.2.0+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
+
+[[package]]
+name = "unicode-width"
+version = "0.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557"
+
+[[package]]
+name = "unscanny"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e9df2af067a7953e9c3831320f35c1cc0600c30d44d9f7a12b01db1cd88d6b47"
+
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "winnow"
+version = "0.7.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
+
+[[package]]
+name = "winnow"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
diff --git a/backend/Cargo.toml b/backend/Cargo.toml
new file mode 100644
index 0000000..d8154f0
--- /dev/null
+++ b/backend/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "lithe-python-backend"
+version = "0.1.0"
+edition = "2021"
+rust-version = "1.87"
+license = "Apache-2.0"
+publish = false
+
+[dependencies]
+base64 = "0.22"
+dunce = "1"
+lithe-plugin-sdk = { git = "https://github.com/Lithe-IDEA/Lithe-core-rust.git", rev = "e56af624d3f615982f90c6249f7aa43c9b3b218e" }
+pep440_rs = "0.7"
+serde_json = "1"
+sha2 = "0.10"
+toml = "0.9"
+
+[profile.release]
+strip = "symbols"
diff --git a/backend/src/discovery.rs b/backend/src/discovery.rs
new file mode 100644
index 0000000..52e531a
--- /dev/null
+++ b/backend/src/discovery.rs
@@ -0,0 +1,290 @@
+//! Collects bounded, read-only Python environment facts for the host resolver.
+
+mod metadata;
+mod project;
+
+use self::metadata::{canonical_directory, read_text, Metadata, Source};
+use lithe_plugin_sdk::toolchains::{
+ ToolchainInstallation, ToolchainQuery, ToolchainQueryError, ToolchainQueryResult,
+ ToolchainStatement,
+};
+use lithe_plugin_sdk::Cancellation;
+use pep440_rs::Version;
+use std::collections::{BTreeMap, BTreeSet};
+use std::env;
+use std::ffi::OsString;
+use std::path::{Path, PathBuf};
+
+type Failure = ToolchainQueryError;
+type Result = std::result::Result;
+
+const MAX_SCAN_ENTRIES: usize = 16384;
+const MAX_INSTALLATIONS: usize = 512;
+const MAX_WATCH_PATHS: usize = 256;
+const MAX_PATH_BYTES: usize = 4096;
+const PROVIDER_TOOL: &str = "python";
+
+struct Installation {
+ home: String,
+ names: BTreeSet,
+ version: Version,
+}
+
+struct Snapshot<'a> {
+ cancelled: &'a Cancellation,
+ workspace: Option,
+ scan_entries: usize,
+ installations: BTreeMap,
+ watch: BTreeSet,
+ statements: Vec,
+}
+
+pub(crate) fn query(
+ request: &ToolchainQuery,
+ cancelled: &Cancellation,
+) -> Result {
+ cancelled.check()?;
+ if request.tools.as_slice() != [PROVIDER_TOOL] {
+ return Err(Failure::InvalidParams);
+ }
+ let workspace = request
+ .workspace
+ .as_ref()
+ .map(|workspace| {
+ let root =
+ canonical_directory(Path::new(&workspace.root))?.ok_or(Failure::UnsafePath)?;
+ let directory = canonical_directory(&root.join(&workspace.directory))?
+ .filter(|directory| directory.starts_with(&root))
+ .ok_or(Failure::UnsafePath)?;
+ Ok::<_, Failure>((root, directory))
+ })
+ .transpose()?;
+ let mut snapshot = Snapshot {
+ cancelled,
+ workspace: workspace.as_ref().map(|(root, _)| root.clone()),
+ scan_entries: 0,
+ installations: BTreeMap::new(),
+ watch: BTreeSet::new(),
+ statements: Vec::new(),
+ };
+
+ let user_home = env::home_dir().filter(|path| path.is_absolute());
+ if let Some(home) = &user_home {
+ snapshot.conda_registry(&home.join(".conda/environments.txt"))?;
+ }
+ if let Some(paths) = env::var_os("CONDA_ENVS_PATH") {
+ for path in env::split_paths(&paths).filter(|path| path.is_absolute()) {
+ snapshot.scan(&path, Source::Conda)?;
+ }
+ }
+ if let Some(prefix) = absolute_env("CONDA_PREFIX") {
+ snapshot.observe(&prefix, Source::Conda)?;
+ snapshot.scan(&prefix.join("envs"), Source::Conda)?;
+ }
+ if let Some(uv) = uv_root(user_home.as_deref()) {
+ snapshot.scan(&uv, Source::Uv)?;
+ }
+ if let Some(pyenv) = pyenv_root(user_home.as_deref()) {
+ snapshot.scan(&pyenv.join("versions"), Source::Pyenv)?;
+ }
+ if let Some(poetry) = poetry_root(user_home.as_deref()) {
+ snapshot.scan(&poetry, Source::Poetry)?;
+ }
+ if let Some(pipenv) = pipenv_root(user_home.as_deref()) {
+ snapshot.scan(&pipenv, Source::Pipenv)?;
+ }
+ if let Some((root, directory)) = workspace {
+ project::read(&mut snapshot, &root, &directory)?;
+ }
+ cancelled.check()?;
+ Ok(ToolchainQueryResult {
+ installations: snapshot
+ .installations
+ .into_values()
+ .map(|installation| ToolchainInstallation {
+ tool: PROVIDER_TOOL.to_owned(),
+ version: installation.version.to_string(),
+ home: installation.home,
+ })
+ .collect(),
+ statements: snapshot.statements,
+ watch: snapshot.watch.into_iter().collect(),
+ })
+}
+
+impl Snapshot<'_> {
+ fn watch(&mut self, path: &Path) -> Result<()> {
+ self.watch.insert(wire_path(path)?);
+ if self.watch.len() > MAX_WATCH_PATHS {
+ return Err(Failure::LimitExceeded);
+ }
+ Ok(())
+ }
+
+ fn step(&mut self) -> Result<()> {
+ self.cancelled.check()?;
+ self.scan_entries += 1;
+ if self.scan_entries > MAX_SCAN_ENTRIES {
+ return Err(Failure::LimitExceeded);
+ }
+ Ok(())
+ }
+
+ fn conda_registry(&mut self, path: &Path) -> Result<()> {
+ self.watch(path)?;
+ if let Some(registry) = read_text(path, None)? {
+ for line in registry
+ .lines()
+ .map(str::trim)
+ .filter(|line| !line.starts_with('#'))
+ {
+ self.step()?;
+ let path = Path::new(line);
+ if path.is_absolute() {
+ self.observe(path, Source::Conda)?;
+ }
+ }
+ }
+ Ok(())
+ }
+
+ fn scan(&mut self, root: &Path, source: Source) -> Result<()> {
+ self.watch(root)?;
+ let Some(root) = canonical_directory(root)? else {
+ return Ok(());
+ };
+ if self
+ .workspace
+ .as_ref()
+ .is_some_and(|workspace| root.starts_with(workspace))
+ {
+ return Ok(());
+ }
+ for entry in std::fs::read_dir(root).map_err(metadata::io_failure)? {
+ self.step()?;
+ let entry = entry.map_err(metadata::io_failure)?;
+ if !entry.file_name().as_encoded_bytes().starts_with(b".") {
+ self.observe(&entry.path(), source)?;
+ }
+ }
+ Ok(())
+ }
+
+ fn observe(&mut self, candidate: &Path, source: Source) -> Result<()> {
+ let Some(home) = canonical_directory(candidate)? else {
+ return Ok(());
+ };
+ if self
+ .workspace
+ .as_ref()
+ .is_some_and(|root| home.starts_with(root))
+ {
+ return Ok(());
+ }
+ let names: BTreeSet<_> = [candidate, &home]
+ .into_iter()
+ .filter_map(Path::file_name)
+ .map(OsString::from)
+ .collect();
+ if let Some(existing) = self.installations.get_mut(&home) {
+ existing.names.extend(names);
+ return Ok(());
+ }
+ if !metadata::has_safe_executable(&home)? {
+ return Ok(());
+ }
+ let Some(Metadata { version, input }) =
+ metadata::version(&home, candidate, source, || self.step())?
+ else {
+ return Ok(());
+ };
+ // A directory watch covers manager additions/removals. The version
+ // source is observed separately when it can change in place.
+ if let Some(input) = input {
+ self.watch(&input)?;
+ }
+ let wire_home = wire_path(&home)?;
+ self.installations.insert(
+ home,
+ Installation {
+ home: wire_home,
+ names,
+ version,
+ },
+ );
+ if self.installations.len() > MAX_INSTALLATIONS {
+ return Err(Failure::LimitExceeded);
+ }
+ Ok(())
+ }
+}
+
+fn wire_path(path: &Path) -> Result {
+ path.to_str()
+ .filter(|value| {
+ path.is_absolute()
+ && value.len() <= MAX_PATH_BYTES
+ && !value.chars().any(char::is_control)
+ })
+ .map(str::to_owned)
+ .ok_or(Failure::UnsafePath)
+}
+
+fn absolute_env(key: &str) -> Option {
+ env::var_os(key)
+ .map(PathBuf::from)
+ .filter(|path| path.is_absolute())
+}
+
+fn uv_root(home: Option<&Path>) -> Option {
+ absolute_env("UV_PYTHON_INSTALL_DIR").or_else(|| {
+ if cfg!(windows) {
+ absolute_env("APPDATA").map(|path| path.join("uv/data/python"))
+ } else {
+ absolute_env("XDG_DATA_HOME")
+ .or_else(|| home.map(|path| path.join(".local/share")))
+ .map(|path| path.join("uv/python"))
+ }
+ })
+}
+
+fn pyenv_root(home: Option<&Path>) -> Option {
+ absolute_env("PYENV_ROOT").or_else(|| {
+ home.map(|path| {
+ path.join(if cfg!(windows) {
+ ".pyenv/pyenv-win"
+ } else {
+ ".pyenv"
+ })
+ })
+ })
+}
+
+fn poetry_root(home: Option<&Path>) -> Option {
+ absolute_env("POETRY_VIRTUALENVS_PATH").or_else(|| {
+ let cache = absolute_env("POETRY_CACHE_DIR").or_else(|| {
+ if cfg!(target_os = "macos") {
+ home.map(|path| path.join("Library/Caches/pypoetry"))
+ } else if cfg!(windows) {
+ absolute_env("LOCALAPPDATA").map(|path| path.join("pypoetry/Cache"))
+ } else {
+ absolute_env("XDG_CACHE_HOME")
+ .or_else(|| home.map(|path| path.join(".cache")))
+ .map(|path| path.join("pypoetry"))
+ }
+ });
+ cache.map(|path| path.join("virtualenvs"))
+ })
+}
+
+fn pipenv_root(home: Option<&Path>) -> Option {
+ absolute_env("WORKON_HOME").or_else(|| {
+ home.map(|path| {
+ path.join(if cfg!(windows) {
+ ".virtualenvs"
+ } else {
+ ".local/share/virtualenvs"
+ })
+ })
+ })
+}
diff --git a/backend/src/discovery/metadata.rs b/backend/src/discovery/metadata.rs
new file mode 100644
index 0000000..14ea3e8
--- /dev/null
+++ b/backend/src/discovery/metadata.rs
@@ -0,0 +1,207 @@
+//! Captures version metadata without executing any candidate interpreter.
+
+use super::{Failure, Result};
+use crate::requirements::{managed_release, numeric_release};
+use pep440_rs::Version;
+use serde_json::Value;
+use std::fs::{self, File};
+use std::io::{self, Read};
+use std::path::{Path, PathBuf};
+
+const MAX_SOURCE_BYTES: u64 = 256 * 1024;
+
+#[derive(Clone, Copy)]
+pub(super) enum Source {
+ Conda,
+ Uv,
+ Pyenv,
+ Poetry,
+ Pipenv,
+}
+
+pub(super) struct Metadata {
+ pub(super) version: Version,
+ pub(super) input: Option,
+}
+
+pub(super) fn io_failure(_: io::Error) -> Failure {
+ // This is a failure reading the manager's data, distinct from a trust
+ // denial for the query itself. Core can fall back to lower sources.
+ Failure::ProviderUnavailable
+}
+
+fn optional(result: io::Result) -> Result