Skip to content

The agent that grows with you

Route build and CI Python preparation through PM operations

etherneta154b89b9f41
diff --git a/.github/actions/detect-changes/action.yml b/.github/actions/detect-changes/action.yml
index 0f2ef680df4..b9ff0f0f7aa 100644
--- a/.github/actions/detect-changes/action.yml
+++ b/.github/actions/detect-changes/action.yml
@@ -40,7 +40,7 @@ outputs:
description: Check pyproject.toml dependency upper bounds.
value: ${{ steps.classify.outputs.deps }}
uv_lock:
- description: Run `uv lock --check` (pyproject.toml / uv.lock changes only).
+ description: Run the PM project-lock check (pyproject.toml / uv.lock changes only).
value: ${{ steps.classify.outputs.uv_lock }}
npm_lock:
description: Post/update the semantic package-lock.json diff PR comment.
diff --git a/.github/actions/save-pm-cache/README.md b/.github/actions/save-pm-cache/README.md
index f6f51420112..ef5e498b9e4 100644
--- a/.github/actions/save-pm-cache/README.md
+++ b/.github/actions/save-pm-cache/README.md
@@ -6,7 +6,7 @@ pruning mode. A metadata or dependency change can reuse compatible wheels;
uv still resolves and installs from the frozen project lock.
Bundle jobs set `save-python-cache: false` and call `save-pm-cache` after their
-build step with the `uv-path`, `uv-cache-path`, and `python-cache-key` outputs.
+build step with the `python-path`, `uv-cache-path`, and `python-cache-key` outputs.
Both the caller and this composite use `!cancelled()` so a failed build does
not suppress the save. Cancellation is excluded to avoid racing a dying uv
process. A runner crash or job timeout can still prevent the save.
@@ -22,8 +22,8 @@ automatic cache path and its exact-hit smoke tests remain available.
Smoke namespaces precede the native/dependency identity, outside production's
restore prefix. PM Toolchain cleanup removes its run-scoped snapshots.
-Before saving, `uv cache prune` removes dangling entries. It does not use
-`--ci`: that option discards downloaded wheels, while bundles copy the full
+Before saving, `python -m pm.build_env --prune-cache --cache PATH` removes
+dangling entries. It does not use `--ci`: that option discards downloaded wheels, while bundles copy the full
cache for offline dependency installation. Pruning happens after payload staging
and packaging, and it does not change the staged payload.
diff --git a/.github/actions/save-pm-cache/action.yml b/.github/actions/save-pm-cache/action.yml
index 2b54b218cc8..4f42f17e2cc 100644
--- a/.github/actions/save-pm-cache/action.yml
+++ b/.github/actions/save-pm-cache/action.yml
@@ -1,8 +1,8 @@
name: Save the PM Python dependency cache
description: Prune dangling entries and save a rolling cache after the consumer, even when it failed.
inputs:
- uv:
- description: Absolute path to the PM-provisioned uv executable.
+ python:
+ description: Prepared Python used to invoke PM.
required: true
path:
description: Cache directory exported by setup-pm.
@@ -20,11 +20,11 @@ runs:
if: ${{ !cancelled() }}
shell: bash
env:
- PM_UV: ${{ inputs.uv }}
- UV_CACHE_DIR: ${{ inputs.path }}
+ PM_PYTHON: ${{ inputs.python }}
+ PM_CACHE: ${{ inputs.path }}
# Keep downloaded wheels as well as source-built wheels. Bundles copy
# this cache for offline installs; --ci would discard required inputs.
- run: '"$PM_UV" cache prune'
+ run: '"$PM_PYTHON" -m pm.build_env --prune-cache --cache "$PM_CACHE"'
- name: Save reusable Python dependencies
if: ${{ !cancelled() && steps.prune.outcome == 'success' }}
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
diff --git a/.github/actions/setup-pm/README.md b/.github/actions/setup-pm/README.md
index 84dbbfc9a55..b9abb8597c7 100644
--- a/.github/actions/setup-pm/README.md
+++ b/.github/actions/setup-pm/README.md
@@ -11,28 +11,31 @@ not resolve a version range, install another setup action, or modify the lock.
with:
toolchain: all
extras: '["dev"]'
-- run: python --version && uv --version && node --version && npm --version
+- run: python --version && node --version && npm --version
```
-`toolchain` defaults to `python` (Python and uv). `node` installs Node and npm;
+`toolchain` defaults to `python` (Python and PM's private installer). `node` installs Node and npm;
`all` installs both pairs. There are no version overrides. `extras` is a JSON
array because GitHub action inputs are strings. Omit it for tools only; `[]`
installs the core Python dependencies, and `["dev"]` adds the dev extra. PM
-checks `uv.lock`, installs the requested dependencies, validates the environment,
-and publishes its selection. It does not enable plugins.
+checks `uv.lock`, installs the requested dependencies, and validates the environment.
+The dev extra uses an independent test environment including the test dependency
+group; only non-test installs publish an application selection. It does not enable plugins.
-Subsequent steps get `python`, `python3`, `uv`, `uvx`, `node`, `npm` and `npx`
+Subsequent steps get `python`, `python3`, `node`, `npm` and `npx`
for the selected toolchain on PATH. The pinned npm precedes Node's bundled npm.
On Windows, PM selects the host architecture even if the bootstrap interpreter
runs under x64 emulation. A disposable command environment supplies the missing
`python3.exe` alias without changing the verified interpreter store.
-For Python dependencies, the action exports `HERMES_PYTHON`, `VIRTUAL_ENV` and
-`UV_PROJECT_ENVIRONMENT`. Use `scripts/run_tests.sh`; do not activate `.venv`.
-The environment belongs to PM under the runner's temporary home, not the
-checkout. Tool-only jobs can install small CI-specific package subsets with
-`uv pip install --python "$HERMES_PYTHON" package==version`; these writes do not
-modify the cached tool store. Native builds still need their system libraries
+For Python dependencies, the action exports `HERMES_PYTHON` and `VIRTUAL_ENV`.
+Use `scripts/run_tests.sh`; do not activate `.venv`. The environment belongs to
+PM under the runner's temporary home, not the checkout. No installer executable
+or `UV_*` policy variables are exposed. Tool-only jobs can prepare small isolated
+CI environments with `python -m scripts.ci.python_packages package==version`.
+This exports the selected Python and tool entrypoints for subsequent steps;
+append `-- -m module ...` to run a Python command directly and preserve its exit
+status. Neither route modifies the cached tool store. Native builds still need their system libraries
and compiler, such as OpenSSL for Windows ARM64 cryptography.
## Caches
@@ -59,7 +62,7 @@ that toolchain. `python-cache-dependency-glob` defaults to `pyproject.toml` and
An npm cache without a matching lockfile fails, rather than caching an
unversioned dependency set.
-`prune-python-cache: true` registers `uv cache prune --ci --force` at teardown,
+`prune-python-cache: true` registers PM's CI cache-pruning operation at teardown,
after the caller's installs and before the cache save. It is skipped on an
exact hit. The default is `false`, as in setup-uv v9; migrated v8 callers opt in
to retain their former policy. The small nested JavaScript action exists only
@@ -67,7 +70,7 @@ because GitHub composite actions cannot declare their own post step. It uses
Node's standard library and has no bundled dependencies.
Outputs include `python-version`, `uv-version`, `node-version`, `npm-version`,
-`python-path`, `uv-path`, `venv`, `target`, and the three `*-cache-hit` flags.
+`python-path`, `venv`, `target`, and the three `*-cache-hit` flags.
Use the version outputs in installed-tree cache keys instead of repeating pins.
`.github/workflows/pm-toolchain.yml` exercises cold setup and a separate warm
diff --git a/.github/actions/setup-pm/action.yml b/.github/actions/setup-pm/action.yml
index 51ad688fa5a..3c14042db2f 100644
--- a/.github/actions/setup-pm/action.yml
+++ b/.github/actions/setup-pm/action.yml
@@ -52,9 +52,6 @@ outputs:
python-path:
description: Interpreter for subsequent steps, including requested extras.
value: ${{ steps.dependencies.outputs.python-path || steps.install.outputs.python-path }}
- uv-path:
- description: PM-provisioned uv executable.
- value: ${{ steps.install.outputs.uv-path }}
venv:
description: Dependency environment; isolated test environment for dev, otherwise PM-selected runtime.
value: ${{ steps.dependencies.outputs.venv }}
@@ -154,7 +151,7 @@ runs:
if: inputs.toolchain != 'node' && inputs.cache-python == 'true' && inputs.save-python-cache == 'true' && inputs.prune-python-cache == 'true' && steps.python-cache.outputs.cache-hit != 'true'
uses: ./.github/actions/setup-pm/prune
with:
- uv: ${{ steps.install.outputs.uv-path }}
+ python: ${{ steps.install.outputs.python-path }}
cache: ${{ steps.install.outputs.uv-cache-path }}
- name: Require an npm dependency lock for caching
@@ -181,5 +178,5 @@ runs:
_PM_TOOLCHAIN: ${{ inputs.toolchain }}
_PM_EXTRAS: ${{ inputs.extras }}
run: |
- "$UV_PYTHON" -S "$_PM_ACTION/../../../scripts/ci/setup_toolchain.py" dependencies \
+ "$HERMES_PYTHON" -S "$_PM_ACTION/../../../scripts/ci/setup_toolchain.py" dependencies \
--toolchain "$_PM_TOOLCHAIN" --extras "$_PM_EXTRAS" --home "$HERMES_HOME"
diff --git a/.github/actions/setup-pm/prune/action.yml b/.github/actions/setup-pm/prune/action.yml
index 1a807290cd9..eb3729d2238 100644
--- a/.github/actions/setup-pm/prune/action.yml
+++ b/.github/actions/setup-pm/prune/action.yml
@@ -1,8 +1,8 @@
name: Prune the PM uv cache at job teardown
description: Register uv pruning before the enclosing cache action saves.
inputs:
- uv:
- description: Absolute path to the PM-provisioned uv executable.
+ python:
+ description: Prepared Python used to invoke the PM cache operation.
required: true
cache:
description: Cache directory restored by the enclosing setup action.
diff --git a/.github/actions/setup-pm/prune/index.mjs b/.github/actions/setup-pm/prune/index.mjs
index e45a13f2173..80b3984861c 100644
--- a/.github/actions/setup-pm/prune/index.mjs
+++ b/.github/actions/setup-pm/prune/index.mjs
@@ -5,19 +5,19 @@ import { pathToFileURL } from 'node:url'
// Composite actions cannot register a post step. Called after actions/cache,
// this action's post runs first, pruning the cache just before it is saved.
export function run(env, execute = spawnSync) {
- if (!env.STATE_uv) {
- for (const [key, value] of Object.entries({ uv: env.INPUT_UV, cache: env.INPUT_CACHE })) {
+ if (!env.STATE_python) {
+ for (const [key, value] of Object.entries({ python: env.INPUT_PYTHON, cache: env.INPUT_CACHE })) {
if (!value || /[\r\n\0]/.test(value)) throw new Error(`invalid ${key}`)
appendFileSync(env.GITHUB_STATE, `${key}=${value}\n`, 'utf8')
}
return
}
- const result = execute(env.STATE_uv, ['cache', 'prune', '--ci', '--force'], {
- env: { ...env, UV_CACHE_DIR: env.STATE_cache },
+ const result = execute(env.STATE_python, ['-m', 'pm.build_env', '--prune-cache', '--cache', env.STATE_cache, '--ci'], {
+ env,
stdio: 'inherit',
})
if (result.error) throw result.error
- if (result.status !== 0) throw new Error(`uv cache prune failed: ${result.status}`)
+ if (result.status !== 0) throw new Error(`PM cache prune failed: ${result.status}`)
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
diff --git a/.github/workflows/canary-release.yml b/.github/workflows/canary-release.yml
index 85ea1f7e817..916d3691132 100644
--- a/.github/workflows/canary-release.yml
+++ b/.github/workflows/canary-release.yml
@@ -85,4 +85,4 @@ jobs:
CLOUDFLARE_R2_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_ACCESS_KEY_ID }}
CLOUDFLARE_R2_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_SECRET_ACCESS_KEY }}
CLOUDFLARE_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET }}
- run: uv run --no-project --with ruamel.yaml==0.18.17 python -m scripts.releases.r2 prune-canaries --keep-days 14
+ run: python -m scripts.ci.python_packages ruamel.yaml==0.18.17 -- -m scripts.releases.r2 prune-canaries --keep-days 14
diff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.yml
index fa016a9b3f4..35c7073a427 100644
--- a/.github/workflows/deploy-site.yml
+++ b/.github/workflows/deploy-site.yml
@@ -75,7 +75,7 @@ jobs:
- name: Install ruamel.yaml for skill extraction
uses: ./.github/actions/retry
with:
- command: uv pip install --python "$HERMES_PYTHON" ruamel.yaml==0.18.17 httpx==0.28.1
+ command: python -m scripts.ci.python_packages ruamel.yaml==0.18.17 httpx==0.28.1
- name: Prepare skills index (unified multi-source catalog)
env:
diff --git a/.github/workflows/desktop-bundled-release.yml b/.github/workflows/desktop-bundled-release.yml
index 145e1f04ba4..12af1db0b0d 100644
--- a/.github/workflows/desktop-bundled-release.yml
+++ b/.github/workflows/desktop-bundled-release.yml
@@ -468,8 +468,7 @@ jobs:
# every non-Linux target (macos universal2, win_amd64, win_arm64).
shell: bash
run: |
- uv tool install cmake==3.31.6
- echo "$(uv tool dir --bin)" >> "$GITHUB_PATH"
+ python -m scripts.ci.python_packages cmake==3.31.6
- name: Build and package
shell: bash
@@ -499,7 +498,7 @@ jobs:
if: ${{ !cancelled() && steps.pm.outcome == 'success' }}
uses: ./.github/actions/save-pm-cache
with:
- uv: ${{ steps.pm.outputs.uv-path }}
+ python: ${{ steps.pm.outputs.python-path }}
path: ${{ steps.pm.outputs.uv-cache-path }}
key: ${{ steps.pm.outputs.python-cache-key }}
@@ -741,8 +740,7 @@ jobs:
# CMake 3.x first on PATH so the sdist build configures.
shell: bash
run: |
- uv tool install cmake==3.31.6
- echo "$(uv tool dir --bin)" >> "$GITHUB_PATH"
+ python -m scripts.ci.python_packages cmake==3.31.6
- name: Build and package
shell: bash
@@ -776,7 +774,7 @@ jobs:
if: ${{ !cancelled() && steps.pm.outcome == 'success' }}
uses: ./.github/actions/save-pm-cache
with:
- uv: ${{ steps.pm.outputs.uv-path }}
+ python: ${{ steps.pm.outputs.python-path }}
path: ${{ steps.pm.outputs.uv-cache-path }}
key: ${{ steps.pm.outputs.python-cache-key }}
@@ -1255,7 +1253,7 @@ jobs:
# (feed-side); the pointer upload is the last write of the run.
shell: bash
run: |
- uv run --no-project --with ruamel.yaml==0.18.17 python -m scripts.releases.r2 finalize --tag "$HERMES_PAYLOAD_TAG" --dir staged
+ python -m scripts.ci.python_packages ruamel.yaml==0.18.17 -- -m scripts.releases.r2 finalize --tag "$HERMES_PAYLOAD_TAG" --dir staged
termux-deb:
name: Build + publish the termux .deb (aarch64)
@@ -1418,7 +1416,7 @@ jobs:
termux-build/payload/SHA256SUMS
termux-build/payload/.work/resolved.txt
termux-build/payload/.work/build_set.txt
- key: termux-wheelhouse-${{ hashFiles('uv.lock', 'pyproject.toml', 'pm/lock.json', 'scripts/termux/runtime_libs.json', 'scripts/termux/build_config.sh', 'scripts/termux/build_wheels.py', 'scripts/termux/termux_build.sh', 'scripts/termux/retag_wheel.py', 'scripts/termux/python_linkage.py', 'scripts/termux/wheelhouse_cache.py', 'scripts/termux/termux-builder.Dockerfile') }}
+ key: termux-wheelhouse-${{ hashFiles('uv.lock', 'pyproject.toml', 'pm/lock.json', 'scripts/termux/runtime_libs.json', 'scripts/termux/build_config.sh', 'scripts/termux/build_wheels.py', 'scripts/termux/termux_build.sh', 'scripts/termux/retag_wheel.py', 'scripts/termux/python_linkage.py', 'scripts/termux/wheelhouse_cache.py', 'scripts/termux/build_environment.py', 'pm/environment.py', 'pm/build_operations.py', 'pm/operations.py', 'pm/pyproject.toml', 'pm/uv.lock', 'scripts/termux/termux-builder.Dockerfile') }}
restore-keys: |
termux-wheelhouse-
@@ -1453,7 +1451,7 @@ jobs:
termux-build/payload/SHA256SUMS
termux-build/payload/.work/resolved.txt
termux-build/payload/.work/build_set.txt
- key: termux-wheelhouse-${{ hashFiles('uv.lock', 'pyproject.toml', 'pm/lock.json', 'scripts/termux/runtime_libs.json', 'scripts/termux/build_config.sh', 'scripts/termux/build_wheels.py', 'scripts/termux/termux_build.sh', 'scripts/termux/retag_wheel.py', 'scripts/termux/python_linkage.py', 'scripts/termux/wheelhouse_cache.py', 'scripts/termux/termux-builder.Dockerfile') }}
+ key: termux-wheelhouse-${{ hashFiles('uv.lock', 'pyproject.toml', 'pm/lock.json', 'scripts/termux/runtime_libs.json', 'scripts/termux/build_config.sh', 'scripts/termux/build_wheels.py', 'scripts/termux/termux_build.sh', 'scripts/termux/retag_wheel.py', 'scripts/termux/python_linkage.py', 'scripts/termux/wheelhouse_cache.py', 'scripts/termux/build_environment.py', 'pm/environment.py', 'pm/build_operations.py', 'pm/operations.py', 'pm/pyproject.toml', 'pm/uv.lock', 'scripts/termux/termux-builder.Dockerfile') }}
- name: Assemble the .deb
shell: bash
@@ -1819,7 +1817,7 @@ jobs:
- uses: ./.github/actions/setup-pm
with:
cache-python: false
- - run: uv run --no-project --with ruamel.yaml==0.18.17 python -m scripts.bundles.release_artifacts promote --root verified
+ - run: python -m scripts.ci.python_packages ruamel.yaml==0.18.17 -- -m scripts.bundles.release_artifacts promote --root verified
- run: python scripts/render-builds-table.py --tag "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY"
stable-phase-result:
diff --git a/.github/workflows/docs-site-checks.yml b/.github/workflows/docs-site-checks.yml
index ca44f47ab2a..f4e99cca865 100644
--- a/.github/workflows/docs-site-checks.yml
+++ b/.github/workflows/docs-site-checks.yml
@@ -28,7 +28,7 @@ jobs:
- name: Install ascii-guard
uses: ./.github/actions/retry
with:
- command: uv pip install --python "$HERMES_PYTHON" ascii-guard==2.3.0 ruamel.yaml==0.18.17
+ command: python -m scripts.ci.python_packages ascii-guard==2.3.0 ruamel.yaml==0.18.17
- name: Extract skill metadata for dashboard
run: python3 website/scripts/extract-skills.py
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index 3dc91272e6e..cf8d657fa51 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -46,7 +46,7 @@ jobs:
- name: Install ruff + ty
uses: ./.github/actions/retry
with:
- command: uv tool install ruff && uv tool install ty
+ command: python -m scripts.ci.python_packages ruff==0.15.10 ty==0.0.21
- name: Determine base ref
id: base
@@ -137,7 +137,7 @@ jobs:
- name: Install ruff
uses: ./.github/actions/retry
with:
- command: uv tool install ruff
+ command: python -m scripts.ci.python_packages ruff==0.15.10
- name: ruff check .
# No --exit-zero, no || true. Exit code propagates to the job,
diff --git a/.github/workflows/pm-bundle.yml b/.github/workflows/pm-bundle.yml
index 4bffeb0218b..81a49951954 100644
--- a/.github/workflows/pm-bundle.yml
+++ b/.github/workflows/pm-bundle.yml
@@ -112,8 +112,7 @@ jobs:
if: startsWith(matrix.target.label, 'darwin-') || startsWith(matrix.target.label, 'win32-')
shell: bash
run: |
- uv tool install cmake==3.31.6
- echo "$(uv tool dir --bin)" >> "$GITHUB_PATH"
+ python -m scripts.ci.python_packages cmake==3.31.6
- name: Stage the payload
shell: bash
@@ -133,7 +132,7 @@ jobs:
if: ${{ !cancelled() && steps.pm.outcome == 'success' }}
uses: ./.github/actions/save-pm-cache
with:
- uv: ${{ steps.pm.outputs.uv-path }}
+ python: ${{ steps.pm.outputs.python-path }}
path: ${{ steps.pm.outputs.uv-cache-path }}
key: ${{ steps.pm.outputs.python-cache-key }}
diff --git a/.github/workflows/pm-toolchain.yml b/.github/workflows/pm-toolchain.yml
index c1f5a08e996..68149dde50f 100644
--- a/.github/workflows/pm-toolchain.yml
+++ b/.github/workflows/pm-toolchain.yml
@@ -59,8 +59,7 @@ jobs:
cache-suffix: smoke-consumers-${{ github.run_id }}-${{ github.run_attempt }}
- name: Install the docs tools into the command environment
run: |
- uv pip install --python "$HERMES_PYTHON" ascii-guard==2.3.0 ruamel.yaml==0.18.17 httpx==0.28.1
- python3 -c 'import ruamel.yaml,httpx; print(ruamel.yaml.__version__, httpx.__version__)'
+ python -m scripts.ci.python_packages ascii-guard==2.3.0 ruamel.yaml==0.18.17 httpx==0.28.1 -- -c 'import ruamel.yaml,httpx; print(ruamel.yaml.__version__, httpx.__version__)'
- name: Install the locked desktop and test workspaces
run: npm ci --workspace apps/desktop --workspace tests-js --include-workspace-root --include=dev --ignore-scripts --no-audit --no-fund
- name: Exercise the actual after-pack relocation hook
diff --git a/.github/workflows/skills-index.yml b/.github/workflows/skills-index.yml
index 60c980206b3..c991a898506 100644
--- a/.github/workflows/skills-index.yml
+++ b/.github/workflows/skills-index.yml
@@ -39,7 +39,7 @@ jobs:
- name: Install dependencies
uses: ./.github/actions/retry
with:
- command: uv pip install --python "$HERMES_PYTHON" httpx==0.28.1 ruamel.yaml==0.18.17
+ command: python -m scripts.ci.python_packages httpx==0.28.1 ruamel.yaml==0.18.17
- name: Build skills index
env:
diff --git a/.github/workflows/uv-lockfile-check.yml b/.github/workflows/uv-lockfile-check.yml
index a5318503759..6fba516a14d 100644
--- a/.github/workflows/uv-lockfile-check.yml
+++ b/.github/workflows/uv-lockfile-check.yml
@@ -19,23 +19,23 @@ name: uv.lock check
# Failure mode this creates: if `main` has advanced since you branched
# (e.g. someone merged a PR that added a dep to pyproject.toml + its
# corresponding uv.lock entries), your branch's uv.lock is missing those
-# new entries. `uv lock --check` resolves against the merged pyproject
+# new entries. `python -m pm.build_env --source . --check-lock` resolves against the merged pyproject
# and sees a lockfile that doesn't cover all the current deps → fails
# with "The lockfile at uv.lock needs to be updated."
#
-# This can be confusing: `uv lock --check` passes locally (your branch
+# This can be confusing: `python -m pm.build_env --source . --check-lock` passes locally (your branch
# is internally consistent) but fails in CI (merged state isn't).
#
# Fix is to sync your branch with main and regenerate the lockfile:
#
# git fetch origin main
# git rebase origin/main # or merge, whatever the repo prefers
-# uv lock # regenerates uv.lock against new pyproject.toml
+# python -m pm.build_env --source . --lock-only # regenerates uv.lock against new pyproject.toml
# git add uv.lock
# git commit -m "chore: refresh uv.lock after rebase onto main"
# git push --force-with-lease # if you rebased
#
-# If you also changed pyproject.toml in your PR, `uv lock` handles that
+# If you also changed pyproject.toml in your PR, `python -m pm.build_env --source . --lock-only` handles that
# at the same time — one regeneration covers both your changes and the
# drift from main.
#
@@ -59,7 +59,7 @@ concurrency:
jobs:
check:
- name: uv lock --check
+ name: python -m pm.build_env --source . --check-lock
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
@@ -73,7 +73,7 @@ jobs:
cache-python: true
prune-python-cache: true
- # `uv lock --check` re-resolves the project from pyproject.toml and
+ # `python -m pm.build_env --source . --check-lock` re-resolves the project from pyproject.toml and
# compares the result to uv.lock, exiting non-zero if they disagree.
# No network writes, no file modifications.
#
@@ -83,7 +83,7 @@ jobs:
- name: Verify uv.lock is up-to-date
id: verify
run: |
- # uv lock --check re-resolves against PyPI (network). Retry so a
+ # python -m pm.build_env --source . --check-lock re-resolves against PyPI (network). Retry so a
# registry blip doesn't read as "lockfile stale". A genuinely stale
# lockfile fails all attempts (deterministic), costing only seconds.
#
@@ -95,12 +95,12 @@ jobs:
# registry, versus "lockfile needs to be updated" when the lock is
# genuinely stale. Only the second is the contributor's to fix, so
# an unreachable registry says so instead of sending them to
- # `uv lock` with nothing to regenerate.
+ # `python -m pm.build_env --source . --lock-only` with nothing to regenerate.
ok=false
net_fail=false
delays=(5 15 45)
for i in 1 2 3; do
- if uv lock --check >lock-check.log 2>&1; then
+ if python -m pm.build_env --source . --check-lock >lock-check.log 2>&1; then
ok=true
net_fail=false
cat lock-check.log
@@ -116,12 +116,12 @@ jobs:
break
fi
[ "$i" = 3 ] && break
- echo "::warning::uv lock --check could not reach the registry (attempt $i); retrying in ${delays[$((i-1))]}s"
+ echo "::warning::python -m pm.build_env --source . --check-lock could not reach the registry (attempt $i); retrying in ${delays[$((i-1))]}s"
sleep "${delays[$((i-1))]}"
done
if [ "$ok" != true ] && [ "$net_fail" = true ]; then
echo "::error title=uv.lock check could not reach PyPI::Registry unreachable after 3 attempts — infrastructure failure, not a stale lockfile. Re-run the job."
- review_status='[{"source":"uv.lock check","results":[{"kind":"action_required","title":"uv.lock check could not reach PyPI","summary":"`uv lock --check` could not reach the package registry after 3 attempts. This is an infrastructure failure, not a stale lockfile.","how_to_fix":"Re-run the failed job. No change to `uv.lock` is needed."}]}]'
+ review_status='[{"source":"uv.lock check","results":[{"kind":"action_required","title":"uv.lock check could not reach PyPI","summary":"`python -m pm.build_env --source . --check-lock` could not reach the package registry after 3 attempts. This is an infrastructure failure, not a stale lockfile.","how_to_fix":"Re-run the failed job. No change to `uv.lock` is needed."}]}]'
echo "review_status=${review_status}" >> "$GITHUB_OUTPUT"
echo "review_status=${review_status}" > review-status.json
exit 1
@@ -132,7 +132,7 @@ jobs:
**If this is a PR:** this check runs against the merged state
(your branch + current `main`), not just your branch. If
- `uv lock --check` passes locally, your branch is likely behind
+ `python -m pm.build_env --source . --check-lock` passes locally, your branch is likely behind
`main` — recent changes to `pyproject.toml` on `main` aren't
reflected in your branch's `uv.lock` yet.
@@ -141,13 +141,13 @@ jobs:
```bash
git fetch origin main
git rebase origin/main # or `git merge origin/main`
- uv lock # regenerate against new pyproject.toml
+ python -m pm.build_env --source . --lock-only # regenerate against new pyproject.toml
git add uv.lock
git commit -m "chore: refresh uv.lock after syncing with main"
git push --force-with-lease # drop --force-with-lease if you merged
```
- **If you only changed pyproject.toml:** run `uv lock` locally
+ **If you only changed pyproject.toml:** run `python -m pm.build_env --source . --lock-only` locally
and commit the result.
This check is blocking because the Docker image build uses
@@ -155,8 +155,8 @@ jobs:
— catching it here avoids a ~15 min failed docker run
on `main` post-merge.
EOF
- echo "::error title=uv.lock out of sync::Run \`uv lock\` locally and commit the result. If on a PR, sync with main first."
- review_status='[{"source":"uv.lock check","results":[{"kind":"action_required","title":"uv.lock out of sync","summary":"uv.lock is out of sync with pyproject.toml.","how_to_fix":"Run `uv lock` locally and commit the result. If on a PR, sync with main first:\n```\ngit fetch origin main\ngit rebase origin/main\nuv lock\ngit add uv.lock\ngit commit -m \"chore: refresh uv.lock\"\n```\n"}]}]'
+ echo "::error title=uv.lock out of sync::Run \`python -m pm.build_env --source . --lock-only\` locally and commit the result. If on a PR, sync with main first."
+ review_status='[{"source":"uv.lock check","results":[{"kind":"action_required","title":"uv.lock out of sync","summary":"uv.lock is out of sync with pyproject.toml.","how_to_fix":"Run `python -m pm.build_env --source . --lock-only` locally and commit the result. If on a PR, sync with main first:\n```\ngit fetch origin main\ngit rebase origin/main\npython -m pm.build_env --source . --lock-only\ngit add uv.lock\ngit commit -m \"chore: refresh uv.lock\"\n```\n"}]}]'
echo "review_status=${review_status}" >> "$GITHUB_OUTPUT"
echo "review_status=${review_status}" > review-status.json
exit 1
diff --git a/Dockerfile b/Dockerfile
index 6e9ee6c846f..99c8f05d9e9 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -187,8 +187,8 @@ WORKDIR /opt/hermes
# download — the same code path pm.sh/pm.ps1 and the desktop payload use)
# into the image's own runtime dir, a self-contained store baked under
# /opt/hermes, outside the /opt/data volume so it survives the overlay.
-# The pinned uv is linked onto PATH so the `uv sync` / `uv pip install`
-# build steps below run the lockfile's uv, not a second download.
+# PM alone resolves the pinned uv for dependency preparation; build consumers
+# receive Python environments, never an installer executable.
#
# Full Chromium supports both headed and headless sessions. It is staged
# here rather than by `npx playwright install`,
@@ -210,9 +210,7 @@ COPY hermes_cli/__init__.py hermes_cli/runtime_paths.py hermes_cli/runtime_state
COPY scripts/bundles/payload.py scripts/bundles/payload.py
RUN set -eu; \
python3 -c 'from pm.ensure import ensure; [ensure(name, explicit=True) for name in ("uv", "chromium")]'; \
- ln -sf /opt/hermes/tools/uv-*/uv /usr/local/bin/uv; \
python3 -c 'from pathlib import Path; from pm.lock import Facts; from pm.registry import get_package; from pm.store import current_target; root = Path("/opt/hermes/tools"); fact = Facts(root / "facts.json").get("python"); binary = get_package("python").binary(root / fact["entry"], current_target()); Path("/usr/local/bin/python3").symlink_to(binary)'; \
- uv --version; \
browser_bin="$(find /opt/hermes/tools/chromium-* -type f \( -name chrome -o -name chromium \) -print -quit)"; \
test -n "$browser_bin"; \
"$browser_bin" --version; \
@@ -221,12 +219,10 @@ RUN set -eu; \
# PM is resident too: never borrow application libraries or create its worker
# environment under /root (unreachable to the runtime UID).
-RUN python3 -c 'from pathlib import Path; from pm.runtime_stage import stage_runtime; from scripts.bundles.payload import seal_pm_runtime; root = Path("/opt/hermes"); python = Path("/usr/local/bin/python3").resolve(); stage_runtime(Path("/usr/local/bin/uv"), python, root / "pm-runtime", project=root / "pm"); seal_pm_runtime(root, python)'
+RUN python3 -c 'from pathlib import Path; from pm import stage_manager_runtime; from scripts.bundles.payload import seal_pm_runtime; root = Path("/opt/hermes"); python = Path("/usr/local/bin/python3").resolve(); stage_manager_runtime(python=python, destination=root / "pm-runtime", project=root / "pm"); seal_pm_runtime(root, python)'
-# Raw uv commands must use PM's staged interpreter, not download another
-# under /root where the unprivileged runtime user cannot traverse it.
-ENV UV_PYTHON=/usr/local/bin/python3
-ENV UV_PYTHON_DOWNLOADS=never
+# JS build helpers use the prepared interpreter without an installer parent.
+ENV HERMES_PYTHON=/usr/local/bin/python3
# The standalone interpreter records its builder's clang toolchain;
# native extensions must use the compiler installed in this image.
ENV CC=gcc CXX=g++
@@ -319,9 +315,8 @@ RUN cd plugins/platforms/photon/sidecar && \
# Source binding is created after the source copy below.
COPY pyproject.toml uv.lock ./
RUN touch ./README.md
-COPY scripts/build/python_env.py scripts/build/python_env.py
-RUN python3 -m scripts.build.python_env --source /opt/hermes --python /usr/local/bin/python3 \
- --uv /usr/local/bin/uv --out /opt/hermes/.venv --no-install-project \
+RUN python3 -m pm.build_env --source /opt/hermes --python /usr/local/bin/python3 \
+ --out /opt/hermes/.venv --no-install-project --sealed \
--extra all --extra messaging --extra otlp --extra anthropic --extra bedrock \
--extra azure-identity --extra hindsight --extra matrix
diff --git a/scripts/build/README.md b/scripts/build/README.md
index 7e42ea0188d..6f667a97379 100644
--- a/scripts/build/README.md
+++ b/scripts/build/README.md
@@ -13,11 +13,11 @@ build or a target-native runtime.
| Layer | Owns | Examples |
|---|---|---|
-| Dependency provider | Tools, locked dependencies, native libraries and build environments | `node-deps.mjs`, `python_env.py`, PM, Nix `importNpmLock`/uv2nix, Termux wheelhouse |
+| Dependency provider | Tools, locked dependencies, native libraries and build environments | `node-deps.mjs`, PM Python operations, Nix `importNpmLock`/uv2nix, Termux wheelhouse |
| Product builder | Compilation or application assembly from prepared inputs | `tui.mjs`, `web.mjs`, `desktop.mjs`, `agent.py`, `../generate_icons.py` |
| Distribution adapter | Product selection, target preparation, package layout, signing and publication | `../bundles/`, `../../Dockerfile`, `../../nix/`, `../termux/` |
-`node-deps.mjs` and `python_env.py` prepare dependencies. Unlike the product
+`node-deps.mjs` and `pm.build_environment` prepare dependencies. Unlike the product
builders, they can access package registries. There is no universal installer,
all-products dispatcher, or cross-platform Python environment.
@@ -150,30 +150,44 @@ has no no-argument mode. The Node product parsers expose no `--help` flag.
## Python dependency provider
```sh
-python -m scripts.build.python_env --source /work/source \
- --python /work/tools/python --uv /work/tools/uv --out /work/venv \
+python -m pm.build_env --source /work/source \
+ --python /work/tools/python --out /work/venv --sealed \
--extra all --extra messaging
```
| Argument | Contract |
|---|---|
-| `--source`, `--python`, `--uv`, `--out` | Required prepared source, interpreter, uv executable, and fresh environment destination |
-| `--cache` | Optional cache directory. Default: `OUT.parent/.uv-cache` |
+| `--source`, `--out` | Required prepared source and fresh environment destination |
+| `--python` | Optional build interpreter; otherwise PM selects its pinned Python |
+| `--cache` | Optional build cache directory; otherwise PM selects its cache |
+| `--group` | Repeatable build/test dependency-group selection |
+| `--sealed` | Prune build-time editable and virtualenv marker `.pth` files |
| `--extra` | Repeatable extra selection |
| `--all-extras` | Select all extras instead of `--extra` |
| `--no-install-project` | Exclude the root application install, but retain workspace-member installation |
| `--offline` | Prohibit uv network access. Required artifacts must already be available |
`OUT` must not exist. Failure removes this invocation's environment, not a
-pre-existing environment. Success prints its Python executable. The Python
-function `build_python_environment` additionally requires an explicit `env`
-mapping. It returns the same executable as a `Path`.
-
-The provider uses `pm.environment.PythonEnvironment` for environment creation,
-frozen workspace sync, and dependency checks. It preserves project uv policy,
-uses the supplied interpreter, and disables interpreter downloads. It does not
-discover user plugins or publish a live PM selection. Nix and Termux retain
-separate dependency providers. The uv cache remains available after this call.
+pre-existing environment. Success prints its Python executable. The CLI is an
+explicit build request. The Python
+function `pm.build_environment` accepts the same semantic inputs and an optional
+explicit build `env` mapping. It returns the same executable as a `Path`.
+
+PM owns pinned installer acquisition, environment creation, frozen workspace
+sync, dependency checks, and failure cleanup. Callers never resolve or pass a uv
+executable. It preserves project policy, uses the supplied interpreter, and
+disables interpreter downloads. It does not discover user plugins or publish a
+live PM selection. Nix retains its declarative dependency provider. Termux builds
+native wheels separately, then uses PM's requirements-environment operation with
+an explicit bionic interpreter and an offline wheelhouse. The build cache remains
+available after this call.
+
+Other build adapters use the same command with `--requirements FILE` (or repeated
+`--requirement SPEC`) for a caller-owned dependency list, `--manager-runtime` for
+the independent PM graph, `--check-lock` for non-mutating CI lock validation, and
+`--export-requirements FILE` for marker-preserving frozen export. Cache teardown
+uses `python -m pm.build_env --prune-cache --cache PATH`; add `--ci` only when the
+cache will not be packaged for offline installation.
Native bundle staging keeps its HOME and PM state temporary, but not its uv
cache. `scripts.bundles.stage --cache PATH` (or `hermes pm bundle --cache PATH`)
@@ -297,7 +311,7 @@ These locations define the interfaces described here:
| Web inputs and TypeScript check | `web.mjs:8–71` |
| Desktop inputs and native checks | `desktop.mjs:11–69` |
| Locked workspace union | `node-deps.mjs:31–68` |
-| Python provider | `python_env.py:21–76`, `../../pm/environment.py:50–133` |
+| Python provider | `../../pm/operations.py`, `../../pm/environment.py` |
| Agent input fields and checks | `inputs.py:30–115` |
| Agent assembly and outputs | `agent.py:76–168` |
| Launcher implementation | `launchers.py`, `launcher_wrapper.py`, `mint_launchers.py` |
diff --git a/scripts/build/python_env.py b/scripts/build/python_env.py
deleted file mode 100644
index 5a13d87843d..00000000000
--- a/scripts/build/python_env.py
+++ /dev/null
@@ -1,81 +0,0 @@
-"""Native/Docker dependency preparation over PM's explicit uv mechanics.
-
-Unlike live PM, a build never discovers plugins or publishes a selection.
-The source is the prepared application tree; editable installs keep pointing
-at that tree. Nix and Termux retain their own dependency providers.
-"""
-from __future__ import annotations
-
-import argparse
-from collections.abc import Mapping, Sequence
-import os
-from pathlib import Path
-import shutil
-import subprocess
-import sys
-
-from pm.environment import PythonEnvironment, prune_site_pth
-from pm.package import InstallError
-
-
-def build_python_environment(
- *, source: Path, python: Path, uv: Path, out: Path,
- env: Mapping[str, str], cache: Path | None = None,
- extras: Sequence[str] = (), all_extras: bool = False,
- no_install_project: bool = False, offline: bool = False,
-) -> Path:
- """Build a fresh environment and return its Python executable after validation.
-
- ``out`` must not exist. Failure removes only this invocation's destination;
- a pre-existing environment is never deleted or used as a successful result.
- The cache (default: ``out.parent / ".uv-cache"``) remains available to the
- native offline-cache packager. ``no_install_project`` prepares only the
- locked dependencies, before an application source layer is available.
- """
- source, out = source.absolute(), out.absolute()
- cache = out.parent / ".uv-cache" if cache is None else cache.absolute()
- environment = PythonEnvironment(
- uv=uv.absolute(), python=python.absolute(), destination=out,
- cache=cache.absolute(), env=env, offline=offline, output=sys.stderr,
- )
- out.mkdir(parents=True)
- try:
- environment.create()
- environment.sync(source, extras=extras, all_extras=all_extras,
- no_install_project=no_install_project)
- environment.check()
- # The sealed payload must never process uv's venv-marker or
- # editable-install .pth files (see pm.environment.prune_site_pth):
- # the launcher addsitedirs the venv, and those two would repoint
- # sys.prefix / shadow the repo snapshot with build-machine paths.
- prune_site_pth(out)
- except BaseException:
- shutil.rmtree(out, ignore_errors=True)
- raise
- return environment.executable
-
-
-def main(argv: Sequence[str] | None = None) -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--source", required=True, type=Path)
- parser.add_argument("--python", required=True, type=Path)
- parser.add_argument("--uv", required=True, type=Path)
- parser.add_argument("--out", required=True, type=Path)
- parser.add_argument("--cache", type=Path, help="uv cache; defaults to OUT's sibling .uv-cache")
- selection = parser.add_mutually_exclusive_group()
- selection.add_argument("--extra", dest="extras", action="append", default=[])
- selection.add_argument("--all-extras", action="store_true")
- parser.add_argument("--no-install-project", action="store_true")
- parser.add_argument("--offline", action="store_true")
- args = parser.parse_args(argv)
- try:
- executable = build_python_environment(**vars(args), env=dict(os.environ))
- except (InstallError, OSError, ValueError, subprocess.TimeoutExpired) as exc:
- print(f"python environment: {exc}", file=sys.stderr)
- return 1
- print(executable)
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/scripts/bundles/desktop.py b/scripts/bundles/desktop.py
index 4981d0d9755..3f5d5395a6e 100644
--- a/scripts/bundles/desktop.py
+++ b/scripts/bundles/desktop.py
@@ -4,7 +4,6 @@ from __future__ import annotations
import argparse
import json
import os
-import re
import shutil
import subprocess
import sys
@@ -74,14 +73,11 @@ def build(repo: Path, tag: str | None, variant: str, builder_args: list[str],
if capture(["git", "rev-parse", "HEAD"], repo) != commit:
raise ValueError("the build checkout must be at the release tag")
node = shutil.which("node")
- if not node or not shutil.which("uv"):
- raise FileNotFoundError("Node and uv are required")
- banner = capture(["uv", "--version"], repo)
- if not re.search(r"[a-z0-9_]+-[a-z0-9]+-[a-z][a-z0-9-]*", banner):
- raise ValueError(f"uv must report its build triple (official uv 0.12+): {banner}")
+ if not node:
+ raise FileNotFoundError("Node is required")
npm = npm_command(node)
env = {**os.environ, "CI": "true", "PYTHONUTF8": "1", "GITHUB_SHA": commit,
- "HERMES_DESKTOP_VARIANT": variant}
+ "HERMES_DESKTOP_VARIANT": variant, "HERMES_PYTHON": sys.executable}
env["HERMES_BUNDLE_ENV_JSON"] = json.dumps(bundle_env, sort_keys=True)
if commit_build:
env["HERMES_PAYLOAD_VERSION"] = version
diff --git a/scripts/bundles/native.py b/scripts/bundles/native.py
index 83026975699..d40ecc7ef04 100644
--- a/scripts/bundles/native.py
+++ b/scripts/bundles/native.py
@@ -10,7 +10,7 @@ import argparse
from pathlib import Path
from pm.cli import _install_names
-from pm.ensure import _store, _facts, _lockfile, uv as pm_uv
+from pm.ensure import _store, _facts, _lockfile
from pm.lock import Facts
from pm.registry import get_package, walk
from pm.store import current_target
@@ -65,16 +65,16 @@ def stage_uv_cache(source: Path, destination: Path) -> None:
wheel.unlink()
-def stage_pm_runtime(root: Path, uv: Path, python: Path, repo: Path, *, offline: bool = False,
+def stage_pm_runtime(root: Path, python: Path, repo: Path, *, offline: bool = False,
cache: Path | None = None) -> None:
"""Publish the same PM dependency graph as source installs, ready offline."""
- from pm.runtime_stage import stage_runtime
+ from pm import stage_manager_runtime
from scripts.bundles.payload import seal_pm_runtime
destination = root / "pm-runtime"
if destination.exists():
shutil.rmtree(destination)
- stage_runtime(uv, python, destination, project=repo / "pm", offline=offline, cache=cache)
+ stage_manager_runtime(python=python, destination=destination, project=repo / "pm", offline=offline, cache=cache)
seal_pm_runtime(root, python)
@@ -157,11 +157,6 @@ def _stage_native(args) -> int:
shutil.rmtree(entry)
- uv_bin, env = pm_uv()
- if uv_bin is None:
- print("✗ venv: uv did not stage")
- return 1
-
python_fact = _facts().get("python")
if python_fact is None:
print("✗ venv: no staged interpreter to build on")
@@ -173,7 +168,7 @@ def _stage_native(args) -> int:
if python_bin is None:
raise FileNotFoundError("staged Python executable is missing")
cache = Path(os.environ["UV_CACHE_DIR"])
- stage_pm_runtime(out, Path(uv_bin), python_bin, repo_dir, cache=cache)
+ stage_pm_runtime(out, python_bin, repo_dir, cache=cache)
print("✓ pm-runtime (independent locked dependencies)", flush=True)
# Build + sync INSIDE the staged repo: the editable project install
@@ -181,8 +176,7 @@ def _stage_native(args) -> int:
venv_dir = out / "venv"
if venv_dir.exists():
shutil.rmtree(venv_dir)
- env["VIRTUAL_ENV"] = str(venv_dir)
- env.pop("UV_NO_CONFIG", None)
+ env = dict(os.environ)
if current_target().startswith("darwin"):
# python-build-standalone bakes phantom toolchain paths (its build
# dir's llvm-ar) into sysconfig; sdist builds then fail with
@@ -190,12 +184,12 @@ def _stage_native(args) -> int:
# sdist builds at the machine's real toolchain.
env.setdefault("AR", "/usr/bin/ar")
env.setdefault("CC", "clang")
- from scripts.build.python_env import build_python_environment
+ from pm import build_environment
from pm.package import InstallError
try:
- build_python_environment(source=repo_dir, python=python_bin, uv=Path(uv_bin),
- out=venv_dir, env=env, cache=cache, all_extras=True)
+ build_environment(source=repo_dir, python=python_bin, out=venv_dir,
+ env=env, cache=cache, all_extras=True, sealed=True, explicit=True)
except InstallError as exc:
print(f"✗ venv: {exc}")
return 1
diff --git a/scripts/ci/classify_changes.py b/scripts/ci/classify_changes.py
index 1d1d4f27818..a1d3bf54943 100644
--- a/scripts/ci/classify_changes.py
+++ b/scripts/ci/classify_changes.py
@@ -20,7 +20,7 @@ Lanes:
* ``site`` — Docusaurus + generated skill docs.
* ``scan`` — supply-chain scan (Python files, .pth, setup hooks).
* ``deps`` — pyproject.toml dependency bounds check.
-* ``uv_lock`` — ``uv lock --check``. Re-resolves the whole graph against
+* ``uv_lock`` — ``PM lock check``. Re-resolves the whole graph against
PyPI, so a diff that touches neither ``pyproject.toml`` nor ``uv.lock``
must not run it.
* ``npm_lock`` — semantic package-lock.json diff PR comment.
diff --git a/scripts/ci/python_packages.py b/scripts/ci/python_packages.py
new file mode 100644
index 00000000000..330288e9e16
--- /dev/null
+++ b/scripts/ci/python_packages.py
@@ -0,0 +1,41 @@
+"""Prepare isolated CI tools, then export their Python or run it directly.
+
+Requirements precede ``--``; arguments after it run with the selected Python.
+Without a command, export the selection for subsequent GitHub Actions steps.
+"""
+from __future__ import annotations
+
+import argparse
+import os
+import subprocess
+import sys
+
+
+def main(argv: list[str] | None = None) -> int:
+ from pm import ensure_environment
+ from scripts.ci.setup_toolchain import add_path, file_commands, python3_alias
+
+ argv = list(sys.argv[1:] if argv is None else argv)
+ boundary = argv.index("--") if "--" in argv else len(argv)
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("requirements", nargs="+")
+ args = parser.parse_args(argv[:boundary])
+ command = argv[boundary + 1:]
+ if boundary < len(argv) and not command:
+ parser.error("-- requires a Python command")
+ python = ensure_environment("ci-tools", args.requirements, explicit=True)
+ python3_alias(python)
+ if command:
+ environment = {key: value for key, value in os.environ.items()
+ if key not in {"PYTHONHOME", "VIRTUAL_ENV"}}
+ environment.update(HERMES_PYTHON=str(python), VIRTUAL_ENV=str(python.parent.parent))
+ environment["PATH"] = str(python.parent) + os.pathsep + environment.get("PATH", "")
+ return subprocess.call([str(python), *command], env=environment)
+ file_commands("GITHUB_ENV", {"HERMES_PYTHON": python, "VIRTUAL_ENV": python.parent.parent})
+ add_path([str(python.parent)])
+ print(f"CI tools ready: {python}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/ci/setup_toolchain.py b/scripts/ci/setup_toolchain.py
index d6f71a11914..31ce1054649 100644
--- a/scripts/ci/setup_toolchain.py
+++ b/scripts/ci/setup_toolchain.py
@@ -110,6 +110,7 @@ def archive_inputs(args) -> None:
def install(args) -> None:
import subprocess
+ from pm import build_requirements_environment
from pm.cli import _live_progress
from pm.ensure import ensure, env_for
from pm.lock import Facts
@@ -122,39 +123,30 @@ def install(args) -> None:
ensure(name, explicit=True, progress=_live_progress(name))
facts = Facts(facts_path())
target = current_target()
+ public_names = [name for name in names if name != "uv"]
binaries = {
name: get_package(name).binary(store_root() / facts.get(name)["entry"], target)
- for name in names
+ for name in public_names
}
- environment = env_for(*names)
- path = env_for(*names, base_env={})["PATH"].split(os.pathsep)
+ environment = env_for(*public_names)
+ path = env_for(*public_names, base_env={})["PATH"].split(os.pathsep)
exported = {}
- outputs = {f"{name}-path": str(binary) for name, binary in binaries.items()}
+ outputs = {f"{name}-path": str(binaries[name]) for name in public_names}
if "python" in names:
- tool_bin = args.home.resolve() / "bin"
- # A writable command environment keeps callers' uv pip installs out
- # of the verified tool store. On Windows its redirector also supplies
- # python3.exe, which PBS does not ship.
+ # Keep third-party CI tooling out of the verified interpreter store.
+ # PM prepares the empty command environment through its normal builder.
commands = args.home.resolve() / "python" / facts.get("python")["entry"]
if not (commands / "pyvenv.cfg").is_file():
- subprocess.run(
- [str(binaries["uv"]), "venv", "--relocatable", "--python", str(binaries["python"]), str(commands)],
- check=True, env=environment, timeout=120,
- )
+ build_requirements_environment([], out=commands, python=binaries["python"],
+ env=environment, explicit=True)
python = commands / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
python3_alias(python)
path.insert(0, str(python.parent))
outputs["python-path"] = str(python)
exported.update({
"HERMES_PYTHON": python,
- "UV_PYTHON": binaries["python"],
- "UV_PYTHON_DOWNLOADS": "never",
- "UV_CACHE_DIR": uv_cache_dir(),
- "UV_TOOL_DIR": args.home.resolve() / "uv-tools",
- "UV_TOOL_BIN_DIR": tool_bin,
})
outputs["uv-cache-path"] = str(uv_cache_dir())
- path.insert(0, str(tool_bin))
if "npm" in names:
cache = subprocess.check_output(
[str(binaries["npm"]), "config", "get", "cache"],
@@ -170,22 +162,10 @@ def install(args) -> None:
def dependencies(args) -> None:
if args.extras is None:
return
- import subprocess
import tomllib
- from pm.runtime import is_runtime, runtime_command, runtime_environment
-
- if not is_runtime():
- subprocess.run(
- runtime_command(Path(__file__).resolve(),
- ["dependencies", "--home", str(args.home.resolve()),
- "--toolchain", args.toolchain, "--extras", json.dumps(args.extras)]),
- env=runtime_environment(), check=True,
- )
- return
-
from hermes_cli.runtime_paths import selected_venv
- from pm.ensure import sync_venv, uv
+ from pm import build_environment, check_project_lock, sync_venv
from pm.paths import repo_root
project = repo_root()
@@ -193,18 +173,13 @@ def dependencies(args) -> None:
unknown = set(args.extras) - metadata["project"]["optional-dependencies"].keys()
if unknown:
raise ValueError(f"unknown project extras: {sorted(unknown)}")
- uv_bin, environment = uv()
- environment.pop("UV_NO_CONFIG", None) # keep project indexes and exclude-newer
- # PM's frozen sync must not turn a stale project lock into a green job.
- subprocess.run([uv_bin, "lock", "--check"], cwd=project, env=environment, check=True, timeout=1800)
+ # Frozen sync must not turn a stale project lock into a green job.
+ check_project_lock(project, explicit=True)
if "dev" in args.extras:
# Test-only groups must not enter PM facts or a shipped generation.
venv = args.home.resolve() / "test-environment"
- environment["UV_PROJECT_ENVIRONMENT"] = str(venv)
- command = [uv_bin, "sync", "--locked", "--group", "test", "--no-install-project"]
- for extra in args.extras:
- command.extend(["--extra", extra])
- subprocess.run(command, cwd=project, env=environment, check=True, timeout=1800)
+ build_environment(source=project, out=venv, extras=args.extras,
+ groups=["test"], no_install_project=True, explicit=True)
else:
sync_venv(args.extras, explicit=True, plugin_dirs=[])
venv = selected_venv(project)
@@ -214,7 +189,6 @@ def dependencies(args) -> None:
file_commands("GITHUB_ENV", {
"HERMES_PYTHON": python,
"VIRTUAL_ENV": venv,
- "UV_PROJECT_ENVIRONMENT": venv,
"PYTHONPATH": project,
})
file_commands("GITHUB_OUTPUT", {"python-path": python, "venv": venv})
diff --git a/scripts/ci/verify_toolchain.py b/scripts/ci/verify_toolchain.py
index 3055ebfa37d..4a71c41ffe6 100644
--- a/scripts/ci/verify_toolchain.py
+++ b/scripts/ci/verify_toolchain.py
@@ -27,7 +27,7 @@ def main() -> None:
facts = Facts(facts_path())
target = current_target()
rows = {}
- for name in ("python", "python3", "uv", "node", "npm", "npx"):
+ for name in ("python", "python3", "node", "npm", "npx"):
binary = shutil.which(name)
if binary is None:
raise RuntimeError(f"{name} is missing from PATH")
@@ -35,7 +35,7 @@ def main() -> None:
package = {"python3": "python", "npx": "npm"}.get(name, name)
pin = lock.version(package)
expected = pin.partition("+")[0]
- actual = result.split()[1] if package in ("python", "uv") else result.removeprefix("v")
+ actual = result.split()[1] if package == "python" else result.removeprefix("v")
if actual != expected:
raise RuntimeError(f"{name} on PATH is {result}, expected {pin}: {binary}")
entry = store_root() / facts.get(package)["entry"]
@@ -48,11 +48,10 @@ def main() -> None:
raise RuntimeError(f"{name} store was mutated after verification")
rows[name] = {"path": binary, "version": result, "target": target}
if args.extras:
- selected = Facts(runtime_facts_path()).get("venv")
- if selected["extras"] != ["dev"]:
- raise RuntimeError(f"unexpected PM extras: {selected['extras']}")
- if Path(sys.prefix).resolve() != Path(selected["environment"]).resolve():
- raise RuntimeError("PATH Python did not select the PM dependency environment")
+ if Facts(runtime_facts_path()).get("venv") is not None:
+ raise RuntimeError("CI test dependencies must not publish a runtime generation")
+ if Path(sys.prefix).resolve() != Path(os.environ["VIRTUAL_ENV"]).resolve():
+ raise RuntimeError("PATH Python did not select the isolated test environment")
import pytest
import ruamel.yaml
diff --git a/scripts/install.sh b/scripts/install.sh
index f9ebde5df5a..d90053517ae 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -177,8 +177,7 @@ ensure_uv() {
chmod +x "$_entry/uvx" 2>/dev/null || true
rm -rf "$_tmp"
fi
- # Make the staged (or found) uv available to bare `uv` invocations.
- export PATH="$(dirname "$UV_CMD"):$PATH"
+ # Bootstrap keeps the installer private; only UV_CMD invokes it.
if ! "$UV_CMD" --version >/dev/null 2>&1; then
fail "pinned uv staged but does not run on this host"
fi
diff --git a/scripts/run_tests.sh b/scripts/run_tests.sh
index 2e9000e9443..736b1051574 100755
--- a/scripts/run_tests.sh
+++ b/scripts/run_tests.sh
@@ -68,7 +68,7 @@ if [ -z "$VENV_PYTHON" ]; then
VENV_PYTHON="$HERMES_PYTHON"
else
echo "✗ No venv with pytest found. Install dev extras:" >&2
- echo " uv sync --extra dev --group test" >&2
+ echo " python -m pm.build_env --source . --out .venv --extra dev --group test" >&2
if [ -n "$SKIPPED_VENVS" ]; then
echo " (skipped for missing pytest:$SKIPPED_VENVS — install dev extras there, or create $REPO_ROOT/.venv)" >&2
fi
diff --git a/scripts/termux/build_deb.sh b/scripts/termux/build_deb.sh
index f17a26a5548..1bfc200f253 100644
--- a/scripts/termux/build_deb.sh
+++ b/scripts/termux/build_deb.sh
@@ -137,21 +137,20 @@ write_reqs_file(Path(sys.argv[2]), Path(sys.argv[3]))
PYREQS
# The bind mount is runner-owned: the container (any uid) can only write
# into a dir the HOST pre-created with open perms (same as the wheelhouse).
-mkdir -p "$PAYLOAD_ABS/venv" "$PAYLOAD_ABS/pm-runtime"
-chmod 0777 "$PAYLOAD_ABS/venv" "$PAYLOAD_ABS/pm-runtime"
+ASSEMBLY="$(mktemp -d "$PAYLOAD_ABS/.environments-XXXXXX")"
+chmod 0777 "$ASSEMBLY"
# Mount the payload at its REAL on-device path: the venv records
# absolute paths (interpreter symlink, pyvenv.cfg) that must be correct
# on-device from birth -- a /payload alias would bake container paths in.
docker run --rm --platform linux/arm64 \
--user root --network none \
+ -v "$ASSEMBLY:/data/data/com.termux/files/usr/lib/hermes-agent" \
-v "$PAYLOAD_ABS/python:/data/data/com.termux/files/usr/lib/hermes-agent/tools/python" \
-v "$PAYLOAD_ABS/node:/data/data/com.termux/files/usr/lib/hermes-agent/tools/node" \
-v "$PAYLOAD_ABS/uv:/data/data/com.termux/files/usr/lib/hermes-agent/tools/uv" \
-v "$PAYLOAD_ABS/runtime-libs:/data/data/com.termux/files/usr/lib/hermes-agent/runtime-libs" \
-v "$PAYLOAD_ABS/wheelhouse:/data/data/com.termux/files/usr/lib/hermes-agent/wheelhouse" \
-v "$PAYLOAD_ABS/.work:/data/data/com.termux/files/usr/lib/hermes-agent/.work" \
- -v "$PAYLOAD_ABS/venv:/data/data/com.termux/files/usr/lib/hermes-agent/venv" \
- -v "$PAYLOAD_ABS/pm-runtime:/data/data/com.termux/files/usr/lib/hermes-agent/pm-runtime" \
-v "$PAYLOAD_ABS/app:/data/data/com.termux/files/usr/lib/hermes-agent/app:ro" \
"$IMAGE" bash -c '
set -euo pipefail
@@ -165,38 +164,17 @@ docker run --rm --platform linux/arm64 \
# recorded absolute paths are correct on-device from birth.
mkdir -p "$PREFIX" 2>/dev/null || true
PY="$PREFIX/lib/hermes-agent/tools/python$PREFIX/bin/python3.14"
- UV="$PREFIX/lib/hermes-agent/tools/uv$PREFIX/bin/uv"
- # Desktop payload canon: the venv holds the DEPENDENCY tree only;
- # the app runs from its own directory via PYTHONPATH (the wheel
- # build is deliberately blocked in setup.py -- Hermes is not a
- # pip-installable package by design).
- # The payload is mounted at its ON-DEVICE path ($PREFIX/lib/
- # hermes-agent) so every absolute path the venv records --
- # interpreter symlink, pyvenv.cfg home -- is correct after
- # dpkg installs the tree to exactly that location.
- "$UV" venv --python "$PY" "$PREFIX/lib/hermes-agent/venv"
- # The dep graph with markers intact (the installer evaluates
- # them on bionic); documented android build misses skipped --
- # nemo-relay is the only casualty (the relay exporter).
- "$UV" pip install --python "$PREFIX/lib/hermes-agent/venv/bin/python" \
- --offline --no-index --only-binary :all: --find-links "$PREFIX/lib/hermes-agent/wheelhouse" \
- -r "$PREFIX/lib/hermes-agent/.work/resolved-reqs.txt"
- "$UV" pip check --python "$PREFIX/lib/hermes-agent/venv/bin/python"
-
- # PM uses the shared locked builder with the verified bionic wheelhouse.
ROOT="$PREFIX/lib/hermes-agent"
- "$PY" -I -B -c "
-import sys
-from pathlib import Path
-sys.path.insert(0, sys.argv[1])
-from pm.runtime_stage import stage_runtime
-from scripts.bundles.payload import seal_pm_runtime
-root, python, uv = map(Path, sys.argv[2:])
-stage_runtime(uv, python, root / \"pm-runtime\", project=root / \"app/pm\",
- wheelhouse=root / \"wheelhouse\", offline=True)
-seal_pm_runtime(root, python)
-" "$ROOT/app" "$ROOT" "$PY" "$UV"
+ export HERMES_RUNTIME_DIR="$ROOT/tools"
+ mkdir -p "$PREFIX/tmp"
+ HERMES_HOME="$(mktemp -d "$PREFIX/tmp/hermes-pm-XXXXXX")"
+ export HERMES_HOME
+ "$PY" "$ROOT/app/scripts/termux/build_environment.py" assemble \
+ --root "$ROOT" --python "$PY" --requirements "$ROOT/.work/resolved-reqs.txt"
' || fail "venv assembly failed inside the container (offline wheelhouse install)"
+# They were built at the final on-device paths, not at host scratch paths.
+mv "$ASSEMBLY/venv" "$ASSEMBLY/pm-runtime" "$PAYLOAD_ABS/"
+rm -rf "$ASSEMBLY"
# The install-method stamp (code-scoped, next to hermes_cli/): the deb IS
# the Termux apt distribution, and detect_install_method reads this marker
diff --git a/scripts/termux/build_environment.py b/scripts/termux/build_environment.py
new file mode 100644
index 00000000000..61ff4452339
--- /dev/null
+++ b/scripts/termux/build_environment.py
@@ -0,0 +1,78 @@
+"""Wire staged bionic inputs to PM without exposing its installer executable."""
+from __future__ import annotations
+
+import argparse
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+if __package__ in (None, ""):
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+
+
+def prepare_tools(source: Path, root: Path) -> None:
+ from pm.paths import lockfile_path
+ from scripts.bundles.payload import record_tools
+
+ store = root / "tools"
+ store.mkdir(parents=True, exist_ok=True)
+ for name in ("python", "uv"):
+ entry = store / name
+ if entry.absolute() != (source / name).absolute():
+ entry.symlink_to((source / name).resolve(), target_is_directory=True)
+ record_tools(root, lockfile_path(), "linux-arm64-bionic", {name: name for name in ("python", "uv")})
+
+
+def application(root: Path, requirements: Path, python: Path) -> None:
+ from pm import build_requirements_environment
+
+ build_requirements_environment(
+ requirements.read_text(encoding="utf-8").splitlines(), out=root / "venv",
+ python=python, wheelhouse=root / "wheelhouse", offline=True, sealed=True, explicit=True,
+ )
+
+
+def assemble(root: Path, requirements: Path, python: Path) -> None:
+ from pm import stage_manager_runtime
+ from scripts.bundles.payload import seal_pm_runtime
+
+ prepare_tools(root / "tools", root)
+ manager = stage_manager_runtime(
+ python=python, destination=root / "pm-runtime", project=root / "app/pm",
+ wheelhouse=root / "wheelhouse", offline=True,
+ )
+ # The staged manager is complete but not published. Execute the application
+ # build in it before sealing removes its build-time executable links.
+ subprocess.run(
+ [str(manager), "-I", "-B", str(Path(__file__).resolve()), "application",
+ "--root", str(root), "--requirements", str(requirements), "--python", str(python)],
+ check=True,
+ )
+ seal_pm_runtime(root, python)
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("phase", choices=["prepare-tools", "assemble", "application"])
+ parser.add_argument("--root", type=Path, required=True)
+ parser.add_argument("--source-tools", type=Path)
+ parser.add_argument("--requirements", type=Path)
+ parser.add_argument("--python", type=Path)
+ args = parser.parse_args()
+ root = args.root.resolve()
+ os.environ["HERMES_RUNTIME_DIR"] = str(root / "tools")
+ if args.phase == "prepare-tools":
+ if args.source_tools is None:
+ parser.error("prepare-tools requires --source-tools")
+ prepare_tools(args.source_tools, root)
+ else:
+ if args.requirements is None or args.python is None:
+ parser.error("environment assembly requires --requirements and --python")
+ operation = assemble if args.phase == "assemble" else application
+ operation(root, args.requirements.resolve(), args.python.absolute())
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/termux/build_wheels.py b/scripts/termux/build_wheels.py
index e2b5fbe5ca0..b19dbc08fbd 100644
--- a/scripts/termux/build_wheels.py
+++ b/scripts/termux/build_wheels.py
@@ -36,7 +36,6 @@ def parse_args() -> argparse.Namespace:
p.add_argument("--wheelhouse", required=True)
p.add_argument("--retag", required=True, help="path to retag_wheel.py")
p.add_argument("--platform-tag", required=True)
- p.add_argument("--uv", required=True, help="path to the staged uv binary")
return p.parse_args()
@@ -342,7 +341,7 @@ def import_native_modules(build_set: list[str]) -> None:
print(" imported", module, flush=True)
-def wheelhouse_gates(resolved: Path, wheelhouse: Path, build_set: list[str], uv: str) -> None:
+def wheelhouse_gates(resolved: Path, wheelhouse: Path, build_set: list[str]) -> None:
"""Offline install of every marker-admitted dep into ONE clean venv,
shared by both gates (the full offline install runs once, not twice).
@@ -356,21 +355,14 @@ def wheelhouse_gates(resolved: Path, wheelhouse: Path, build_set: list[str], uv:
"""
with tempfile.TemporaryDirectory(prefix="hermes-wheelhouse-gate-") as tmp:
tmp = Path(tmp)
- venv = tmp / "venv"
- subprocess.run(
- [uv, "venv", "--python", sys.executable, str(venv)],
- check=True,
- )
- vp = venv / "bin" / "python"
+ from pm import build_requirements_environment
+
reqs = tmp / "reqs.txt"
write_reqs_file(resolved, reqs)
- subprocess.run(
- [uv, "pip", "install", "--python", str(vp),
- "--only-binary", ":all:", "--no-index",
- "--find-links", str(wheelhouse), "-r", str(reqs)],
- check=True,
+ vp = build_requirements_environment(
+ reqs.read_text(encoding="utf-8").splitlines(), out=tmp / "venv",
+ python=Path(sys.executable), wheelhouse=wheelhouse, offline=True, explicit=True,
)
- subprocess.run([uv, "pip", "check", "--python", str(vp)], check=True)
print(" completeness gate: offline install of the marker-admitted graph OK")
subprocess.run(
[str(vp), str(Path(__file__).resolve()), "--import-modules", *build_set],
@@ -388,7 +380,6 @@ def main() -> int:
import_native_modules(sys.argv[2:])
return 0
args = parse_args()
- uv = str(Path(args.uv))
resolved = Path(args.resolved)
build_set = [l.strip() for l in Path(args.build_set).read_text(encoding="utf-8").splitlines() if l.strip()]
wheelhouse = Path(args.wheelhouse)
@@ -407,7 +398,7 @@ def main() -> int:
repaired = repair_wheel(wheel, library)
if repaired:
print(f" linked {repaired} native extensions to {library.name}: {wheel.name}")
- wheelhouse_gates(resolved, wheelhouse, build_set, uv)
+ wheelhouse_gates(resolved, wheelhouse, build_set)
print(f"wheelhouse complete: {len(list(wheelhouse.glob('*.whl')))} wheels in {wheelhouse}")
return 0
diff --git a/scripts/termux/termux_build.sh b/scripts/termux/termux_build.sh
index 15181801edb..7ac7023647a 100755
--- a/scripts/termux/termux_build.sh
+++ b/scripts/termux/termux_build.sh
@@ -40,16 +40,14 @@ if [ "${1:-}" = "--in-container" ]; then
PAYLOAD_ROOT="${5:-}"
export PREFIX=/data/data/com.termux/files/usr
STAGED_PY="$PAYLOAD_ROOT/python$PREFIX/bin/python3.14"
- STAGED_UV="$PAYLOAD_ROOT/uv$PREFIX/bin/uv"
# The staged binaries' RUNPATHs point at the phone's $PREFIX layout
# (linkerconfig on-device). Inside the container the tree lives at
# $PAYLOAD_ROOT/python$PREFIX, so the dynamic linker needs to be told
# where the payload's libs live before any staged binary runs.
export LD_LIBRARY_PATH="$PAYLOAD_ROOT/python$PREFIX/lib:$PAYLOAD_ROOT/node$PREFIX/lib:$PAYLOAD_ROOT/runtime-libs/lib:$PREFIX/lib"
- if [ -n "$PAYLOAD_ROOT" ] && [ -x "$STAGED_PY" ] && [ -x "$STAGED_UV" ]; then
+ if [ -n "$PAYLOAD_ROOT" ] && [ -x "$STAGED_PY" ]; then
PY="$STAGED_PY"
- UV="$STAGED_UV"
- log "Using the staged payload python ($PY) and uv ($UV)"
+ log "Using the staged payload Python ($PY)"
else
# No payload staged (or missing): refuse. Building against any
# other interpreter (the container's pkg python is 3.14!) ships
@@ -85,7 +83,6 @@ if [ "${1:-}" = "--in-container" ]; then
# Serial builds only -- parallel Rust/C builds OOM arm runners.
export CARGO_BUILD_JOBS=1
export MAKEFLAGS=-j1
- export UV_CONCURRENT_BUILDS=1
# Native extension links need the STAGED payload's libpython: the
# container's own $PREFIX/lib (bootstrap only) is on the default
# -L path, but libpython3.14.so lives in the staged tree. setuptools
@@ -113,26 +110,27 @@ if [ "${1:-}" = "--in-container" ]; then
# at it (nemo-relay's worker-proto otherwise fails codegen).
export PROTOC="$PREFIX/bin/protoc"
export PROTOC_BIN_PATH="$PREFIX/bin/protoc"
- log "Creating the scratch build venv + enforcing toolchain pins (staged uv)"
- # The container runs as its own uid: /out (runner-owned) and /tmp are
- # NOT writable, but the container's own termux prefix IS (provisioning
- # already writes there). Scratch venv under $PREFIX/tmp.
+ log "Preparing the scratch build environment through PM"
mkdir -p "$PREFIX/tmp"
- BUILD_VENV="$PREFIX/tmp/hermes-build-venv"
- "$UV" venv --python "$PY" "$BUILD_VENV" \
- || fail "scratch build venv creation failed"
- # uv venvs ship WITHOUT pip; the sdist build loop shells out to
- # `python -m pip wheel`, which needs pip INSIDE the venv. uv installs
- # it from outside (the only tool that can, cleanly, on bionic).
- "$UV" pip install --python "$BUILD_VENV/bin/python" pip packaging \
- || fail "pip bootstrap into the build venv failed"
- "$UV" pip install --python "$BUILD_VENV/bin/python" "${TOOLCHAIN_PINS[@]}" \
- || fail "toolchain pin enforcement failed"
+ BUILD_ROOT="$(mktemp -d "$PREFIX/tmp/hermes-build-XXXXXX")"
+ BUILD_VENV="$BUILD_ROOT/venv"
+ export HERMES_HOME="$BUILD_ROOT/home"
+ export HERMES_RUNTIME_DIR="$BUILD_ROOT/tools"
+ PYTHONPATH="$(cd "$HERE/../.." && pwd)"
+ export PYTHONPATH
+ "$PY" "$HERE/build_environment.py" prepare-tools \
+ --root "$BUILD_ROOT" --source-tools "$PAYLOAD_ROOT"
+ requirements=(--requirement pip==26.2.1 --requirement packaging==26.0)
+ for requirement in "${TOOLCHAIN_PINS[@]}"; do
+ requirements+=(--requirement "$requirement")
+ done
+ "$PY" -m pm.build_env --out "$BUILD_VENV" --python "$PY" "${requirements[@]}" \
+ || fail "scratch build environment preparation failed"
log "Building the android wheel set from sdist (bionic, payload ABI)"
"$BUILD_VENV/bin/python" -u "$HERE/build_wheels.py" \
--resolved "$RESOLVED" --build-set "$BUILD_SET" \
--wheelhouse "$WHEELHOUSE" --retag "$HERE/retag_wheel.py" \
- --platform-tag "$PLATFORM_TAG" --uv "$UV" \
+ --platform-tag "$PLATFORM_TAG" \
|| fail "wheel building failed"
log "Wheelhouse container phase complete"
# Root-owned outputs: make world-readable BEFORE exiting so the
@@ -160,7 +158,7 @@ done
[ -n "$REPO" ] && [ -n "$OUT" ] && { [ -n "$TAG" ] || [ -n "$COMMIT_MODE" ]; } && { [ -z "$TAG" ] || [ -z "$COMMIT_MODE" ]; } || {
printf 'usage: termux_build.sh --repo <dir> (--tag <tag> | --commit <full-sha>) --out <dir>\n' >&2; exit 2; }
-for tool in uv git curl docker python3; do
+for tool in git curl docker python3; do
command -v "$tool" >/dev/null 2>&1 \
|| fail "missing tool: $tool (CI must provision the pinned toolchain before running this script)"
done
@@ -228,9 +226,9 @@ mkdir -p "$WHEELHOUSE"
rm -f "$OUT_ABS/index.json" "$OUT_ABS/SHA256SUMS" "$WORK/resolved.txt" "$WORK/build_set.txt"
# [d] Resolve the real graph from the tag's own lock.
log "Resolving dependency graph from the tag's uv.lock"
-( cd "$WORK/tree" && uv export --frozen --no-emit-project --extra acp \
- --no-hashes --no-annotate --no-header -o "$WORK/req.txt" ) \
- || fail "uv export failed (frozen lock at $REF)"
+( cd "$REPO_ROOT" && python3 -m pm.build_env --source "$WORK/tree" \
+ --extra acp --export-requirements "$WORK/req.txt" ) \
+ || fail "PM requirements export failed (frozen lock at $REF)"
# Host parsing needs packaging too. Use the release lock, not runner packages.
PACKAGING_SPEC="$(python3 - "$WORK/tree/uv.lock" <<'PY'
import sys, tomllib
@@ -240,7 +238,11 @@ package, = [item for item in packages if item["name"] == "packaging"]
print("packaging==" + package["version"])
PY
)" || fail "locked packaging dependency missing"
-HOST_PY=(uv run --isolated --no-project --python "$(command -v python3)" --with "$PACKAGING_SPEC" python)
+HOST_ENV="$(mktemp -d "$WORK/host-parser-XXXXXX")"
+( cd "$REPO_ROOT" && python3 -m pm.build_env --out "$HOST_ENV/venv" \
+ --python "$(command -v python3)" --requirement "$PACKAGING_SPEC" ) \
+ || fail "host parser environment preparation failed"
+HOST_PY=("$HOST_ENV/venv/bin/python")
RESOLVED="$WORK/resolved.txt"
"${HOST_PY[@]}" "$HERE/build_wheels.py" --normalize "$WORK/req.txt" "$WORK/tree/uv.lock" "$RESOLVED" \
|| fail "failed to normalize requirements"
diff --git a/scripts/termux/validate_installed.py b/scripts/termux/validate_installed.py
index adeb0cacc92..7a8d7881e6b 100644
--- a/scripts/termux/validate_installed.py
+++ b/scripts/termux/validate_installed.py
@@ -127,10 +127,8 @@ def main() -> None:
print("FFMPEG_MEDIA_CONVERSION_OK", flush=True)
run([
str(python), "-c",
- "import pm; import subprocess; from pathlib import Path; "
- "p,e=pm.uv(realize=False); assert p and Path(p).is_file(), p; "
- "subprocess.run([p, '--version'],env=e,check=True); "
- "assert not pm.check(), pm.check(); print('PM_RUNTIME_TOOLS_OK')",
+ "import pm; issues = pm.check(); "
+ "assert not issues, issues; print('PM_RUNTIME_TOOLS_OK')",
], env, home)
result = subprocess.run([str(launcher), "update"], env=env, cwd=home, capture_output=True, text=True, timeout=60)
if result.returncode == 0 or "pkg upgrade hermes-agent" not in result.stdout + result.stderr:
diff --git a/scripts/termux/wheelhouse_cache.py b/scripts/termux/wheelhouse_cache.py
index 8f58e2e629e..2818673ee43 100644
--- a/scripts/termux/wheelhouse_cache.py
+++ b/scripts/termux/wheelhouse_cache.py
@@ -14,7 +14,9 @@ def build_identity(repo: Path, builder: str, platform_tag: str, python_abi: str)
"scripts/termux/runtime_libs.json", "scripts/termux/build_config.sh",
"scripts/termux/termux_build.sh", "scripts/termux/build_wheels.py",
"scripts/termux/retag_wheel.py", "scripts/termux/python_linkage.py",
- "scripts/termux/wheelhouse_cache.py",
+ "scripts/termux/wheelhouse_cache.py", "scripts/termux/build_environment.py",
+ "pm/environment.py", "pm/build_operations.py", "pm/operations.py",
+ "pm/pyproject.toml", "pm/uv.lock",
"scripts/termux/termux-builder.Dockerfile",
)
return {
diff --git a/scripts/tests/test-install-ps1-node-compatibility.ps1 b/scripts/tests/test-install-ps1-node-compatibility.ps1
index b250f796935..af074b2d6eb 100644
--- a/scripts/tests/test-install-ps1-node-compatibility.ps1
+++ b/scripts/tests/test-install-ps1-node-compatibility.ps1
@@ -1,4 +1,4 @@
-# PM owns Node provisioning. This verifies the installer's delegation boundary.
+# PM owns Node provisioning. Verify the pre-Python bootstrap handoff.
$ErrorActionPreference = 'Stop'
$repoRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path))
$installScript = Join-Path $repoRoot 'scripts\install.ps1'
@@ -23,15 +23,21 @@ try {
Assert-True (-not (Test-Path $testRoot)) 'dot-source loads definitions without filesystem writes'
$fakeUv = Join-Path $testRoot 'uv.cmd'
- $argsFile = Join-Path $testRoot 'args.txt'
+ $fakePython = Join-Path $testRoot 'python.cmd'
+ $argsFile = Join-Path $testRoot 'uv-args.txt'
+ $pythonArgsFile = Join-Path $testRoot 'python-args.txt'
New-Item -ItemType Directory -Force -Path (Join-Path $checkout 'pm') | Out-Null
- @'
+ @"
@echo off
-echo %* > "%HERMES_TEST_UV_ARGS%"
+echo %* >> "$argsFile"
+if "%~2"=="find" echo $fakePython
exit /b 0
-'@ | Set-Content -LiteralPath $fakeUv -Encoding Ascii
- $priorArgs = $env:HERMES_TEST_UV_ARGS
- $env:HERMES_TEST_UV_ARGS = $argsFile
+"@ | Set-Content -LiteralPath $fakeUv -Encoding Ascii
+ @"
+@echo off
+echo %* > "$pythonArgsFile"
+exit /b 0
+"@ | Set-Content -LiteralPath $fakePython -Encoding Ascii
function Get-Uv { return $fakeUv }
$failed = $false
@@ -42,19 +48,16 @@ exit /b 0
'{"packages":{"python":{"version":"3.13.2+test"}}}' |
Set-Content -LiteralPath (Join-Path $checkout 'pm\lock.json') -Encoding UTF8
Invoke-BootstrapPm
- $recorded = Get-Content -LiteralPath $argsFile -Raw
- Assert-True ($recorded -match '--no-project') 'uv runs without ambient project discovery'
- Assert-True ($recorded -match '--python 3\.13(\s|$)') 'Python minor comes from the lockfile'
- Assert-True ($recorded -match 'python -m pm\.cli install') 'PM owns the install'
+ $recorded = Get-Content -LiteralPath $argsFile
+ Assert-True ($recorded.Count -eq 2) 'uv only installs and locates bootstrap Python'
+ Assert-True ($recorded[0] -eq 'python install --no-bin 3.13') 'Python minor comes from the lockfile'
+ Assert-True ($recorded[1] -eq 'python find --managed-python --no-project 3.13') 'lookup ignores ambient project discovery'
+ Assert-True ((Get-Content -LiteralPath $pythonArgsFile -Raw).Trim() -eq '-m pm.cli install') 'Python launches PM without a uv parent'
function Get-Uv { throw 'node stage attempted provisioning' }
Stage-NodeDeps
Write-Host 'PASS: node stage performs no separate install'
} finally {
- if (Get-Variable priorArgs -ErrorAction SilentlyContinue) {
- if ($null -eq $priorArgs) { Remove-Item Env:HERMES_TEST_UV_ARGS -ErrorAction SilentlyContinue }
- else { $env:HERMES_TEST_UV_ARGS = $priorArgs }
- }
if (Test-Path $testRoot) { Remove-Item -LiteralPath $testRoot -Recurse -Force }
}
if ($script:Failures) { exit 1 }
diff --git a/tests-js/setup-pm-cache.test.mjs b/tests-js/setup-pm-cache.test.mjs
index cad3935ccaf..6669c3f64e7 100644
--- a/tests-js/setup-pm-cache.test.mjs
+++ b/tests-js/setup-pm-cache.test.mjs
@@ -57,16 +57,16 @@ it('all bundle consumers save on failure, after building, without discarding off
expect(job.steps.slice(setupIndex + 1, saveIndex).some(step => step.run?.includes('bundle'))).toBe(true)
expect(saveStep.if).toBe(`\${{ !cancelled() && steps.${setupStep.id}.outcome == 'success' }}`)
expect(saveStep.with).toEqual({
- uv: `\${{ steps.${setupStep.id}.outputs.uv-path }}`,
+ python: `\${{ steps.${setupStep.id}.outputs.python-path }}`,
path: `\${{ steps.${setupStep.id}.outputs.uv-cache-path }}`,
key: `\${{ steps.${setupStep.id}.outputs.python-cache-key }}`,
})
}
const [prune, upload] = save.runs.steps
expect(prune.if).toBe('${{ !cancelled() }}')
- expect(prune.run).toBe('"$PM_UV" cache prune')
- expect(prune.env.PM_UV).toBe('${{ inputs.uv }}')
- expect(prune.env.UV_CACHE_DIR).toBe('${{ inputs.path }}')
+ expect(prune.run).toBe('"$PM_PYTHON" -m pm.build_env --prune-cache --cache "$PM_CACHE"')
+ expect(prune.env.PM_PYTHON).toBe('${{ inputs.python }}')
+ expect(prune.env.PM_CACHE).toBe('${{ inputs.path }}')
expect(upload.if).toBe(`\${{ !cancelled() && steps.${prune.id}.outcome == 'success' }}`)
expect(upload.uses.split('@')[0]).toBe('actions/cache/save')
expect(upload.with).toEqual({ path: '${{ inputs.path }}', key: '${{ inputs.key }}' })
diff --git a/tests-js/setup-pm-post.test.mjs b/tests-js/setup-pm-post.test.mjs
index 14372441840..9aaaca386e3 100644
--- a/tests-js/setup-pm-post.test.mjs
+++ b/tests-js/setup-pm-post.test.mjs
@@ -16,18 +16,18 @@ it('prunes the saved uv cache at teardown, never during registration', () => {
const state = join(directory, 'state')
const execute = vi.fn(() => ({ status: 0 }))
const cache = join(directory, 'cache with spaces')
- const uv = join(directory, 'locked uv')
- run({ GITHUB_STATE: state, INPUT_UV: uv, INPUT_CACHE: cache }, execute)
+ const python = join(directory, 'prepared Python')
+ run({ GITHUB_STATE: state, INPUT_PYTHON: python, INPUT_CACHE: cache }, execute)
expect(execute).not.toHaveBeenCalled()
const saved = Object.fromEntries(readFileSync(state, 'utf8').trim().split('\n').map(line => {
const index = line.indexOf('=')
return [`STATE_${line.slice(0, index)}`, line.slice(index + 1)]
}))
run({ ...saved, UV_CACHE_DIR: 'a later unrelated cache' }, execute)
- expect(execute).toHaveBeenCalledWith(uv, ['cache', 'prune', '--ci', '--force'], expect.objectContaining({
- env: expect.objectContaining({ UV_CACHE_DIR: cache }),
+ expect(execute).toHaveBeenCalledWith(python, ['-m', 'pm.build_env', '--prune-cache', '--cache', cache, '--ci'], expect.objectContaining({
+ env: expect.objectContaining(saved),
stdio: 'inherit',
}))
execute.mockReturnValueOnce({ status: 1 })
- expect(() => run(saved, execute)).toThrow('uv cache prune failed')
+ expect(() => run(saved, execute)).toThrow('PM cache prune failed')
})
diff --git a/tests/scripts/test_bundle_native.py b/tests/scripts/test_bundle_native.py
index 2242294e9c1..74e38a2e0d5 100644
--- a/tests/scripts/test_bundle_native.py
+++ b/tests/scripts/test_bundle_native.py
@@ -54,17 +54,20 @@ def test_bundle_stages_git_tree_and_runs_native_children_before_manifest(tmp_pat
monkeypatch.setattr(native, "_store", lambda: SimpleNamespace(root=output / "tools", entry=lambda _: target_python.parent))
monkeypatch.setattr(native, "_facts", lambda: SimpleNamespace(get=lambda _: {"entry": "python", "version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"}, entries_in_use=lambda: []))
monkeypatch.setattr(native, "get_package", lambda _: SimpleNamespace(binary=lambda *args: target_python))
- monkeypatch.setattr(native, "pm_uv", lambda: (uv, dict(env)))
+ monkeypatch.setattr("pm.client.is_runtime", lambda: True)
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(uv), Path(sys.executable)))
monkeypatch.setattr(native, "_arch_guard", lambda store: [])
monkeypatch.setattr("scripts.bundles.payload.relativize_links", lambda root: 0)
monkeypatch.setattr("pm.extras.ANCHORS", {"payloadtest": "bundle_probe.present"})
- from scripts.build import python_env
- real_build = python_env.build_python_environment
+ import pm
+ real_build = pm.build_environment
calls = []
witness = tmp_path / "inventory-python.json"
fail_inventory = False
def build(**kwargs):
+ assert "uv" not in kwargs
+ assert kwargs["sealed"] is True
calls.append(kwargs)
assert not (output / "manifest.json").exists()
marker = json.loads((output / "pm-runtime/pm-runtime.json").read_text())
@@ -85,7 +88,7 @@ def test_bundle_stages_git_tree_and_runs_native_children_before_manifest(tmp_pat
(package / "present.py").write_text("", encoding="utf-8")
return result
- monkeypatch.setattr(python_env, "build_python_environment", build)
+ monkeypatch.setattr(pm, "build_environment", build)
monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "original"))
monkeypatch.setenv("UV_CACHE_DIR", str(tmp_path / "cache"))
assert native._stage_native(SimpleNamespace(out=str(output), ref="HEAD")) == 0
@@ -111,7 +114,7 @@ def test_bundle_stages_git_tree_and_runs_native_children_before_manifest(tmp_pat
from pm.package import InstallError
def fail_build(**kwargs):
raise InstallError("venv", "injected failure")
- monkeypatch.setattr(python_env, "build_python_environment", fail_build)
+ monkeypatch.setattr(pm, "build_environment", fail_build)
assert native._stage_native(SimpleNamespace(out=str(output), ref="HEAD")) == 1
assert not (output / "manifest.json").exists()
assert os.environ["HERMES_RUNTIME_DIR"] == str(tmp_path / "original")
diff --git a/tests/scripts/test_commit_bundle_entrypoints.py b/tests/scripts/test_commit_bundle_entrypoints.py
index 91a163d7acb..d909bfea6e1 100644
--- a/tests/scripts/test_commit_bundle_entrypoints.py
+++ b/tests/scripts/test_commit_bundle_entrypoints.py
@@ -25,7 +25,7 @@ def test_desktop_build_reaches_the_managed_payload_with_commit_ref(tmp_path, mon
monkeypatch.setenv("BUILD_NUMBER", "123")
defaults = {"HERMES_GUEST_ONBOARDING": "1", "HERMES_DATA_DIR_SUFFIX": "magic-test", "HERMES_HOME": None}
monkeypatch.setenv("HERMES_BUNDLE_ENV_JSON", json.dumps(defaults))
- monkeypatch.setattr(desktop.shutil, "which", lambda name: name)
+ monkeypatch.setattr(desktop.shutil, "which", lambda name: None if name == "uv" else name)
monkeypatch.setattr(desktop, "npm_command", lambda node: [node, "npm-cli.js"])
monkeypatch.setattr("scripts.build.windows_deps.prepare_windows_environment", lambda **kwargs: dict(kwargs["env"]))
from pm.store import current_target
@@ -33,8 +33,6 @@ def test_desktop_build_reaches_the_managed_payload_with_commit_ref(tmp_path, mon
def capture(argv, cwd):
if argv[0] == "git":
return _git(*argv[1:], cwd=cwd)
- if argv == ["uv", "--version"]:
- return "uv 0.12.0 aarch64-pc-windows-msvc"
if "process.arch" in argv:
return target_arch
return "26.7.0"
@@ -53,6 +51,7 @@ def test_desktop_build_reaches_the_managed_payload_with_commit_ref(tmp_path, mon
assert env.get("HERMES_PAYLOAD_TAG", "") == ""
assert env["HERMES_BUILD_COMMIT"] == sha
assert env["GITHUB_SHA"] == sha
+ assert env["HERMES_PYTHON"] == sys.executable
assert env["HERMES_PAYLOAD_VERSION"] == "0.1.2"
assert json.loads(env["HERMES_BUNDLE_ENV_JSON"]) == defaults
if "scripts.bundles.stage" in argv:
diff --git a/tests/scripts/test_pm_build_consumers.py b/tests/scripts/test_pm_build_consumers.py
new file mode 100644
index 00000000000..95c96138ecc
--- /dev/null
+++ b/tests/scripts/test_pm_build_consumers.py
@@ -0,0 +1,113 @@
+"""Build adapters consume selected Python environments, never install commands."""
+from __future__ import annotations
+
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+
+import pytest
+
+
+def local_toolchain(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path / "home")
+ uv = shutil.which("uv")
+ assert uv, "build integration tests require the dev-shell toolchain"
+ monkeypatch.setattr("pm.client.is_runtime", lambda: True)
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(uv), Path(sys.executable)))
+
+
+def test_ci_setup_exports_no_installer_path_or_policy(tmp_path, monkeypatch, local_toolchain):
+ import importlib
+ from types import SimpleNamespace
+ from scripts.ci import setup_toolchain
+
+ monkeypatch.setattr(setup_toolchain, "packages", lambda _: ["python", "uv"])
+ manager = importlib.import_module("pm.ensure")
+ monkeypatch.setattr(manager, "ensure", lambda *args, **kwargs: None)
+
+ def environment(*names, base_env=None):
+ assert "uv" not in names
+ return {"PATH": str(Path(sys.executable).parent)}
+
+ def package(name):
+ assert name != "uv", "CI must not resolve an installer executable"
+ return SimpleNamespace(binary=lambda *args: Path(sys.executable))
+
+ monkeypatch.setattr(manager, "env_for", environment)
+ monkeypatch.setattr("pm.registry.get_package", package)
+ monkeypatch.setattr("pm.lock.Facts", lambda path: SimpleNamespace(get=lambda name: {"entry": name, "version": "fixture"}))
+ files = {name: tmp_path / name for name in ("GITHUB_ENV", "GITHUB_OUTPUT", "GITHUB_PATH")}
+ for name, path in files.items():
+ monkeypatch.setenv(name, str(path))
+ setup_toolchain.install(SimpleNamespace(toolchain="python", home=tmp_path / "ci"))
+ outputs = dict(line.split("=", 1) for line in files["GITHUB_OUTPUT"].read_text(encoding="utf-8").splitlines())
+ exported = dict(line.split("=", 1) for line in files["GITHUB_ENV"].read_text(encoding="utf-8").splitlines())
+ assert "uv-path" not in outputs
+ assert not any(name.startswith("UV_") for name in exported)
+ assert exported["HERMES_PYTHON"] == outputs["python-path"]
+ assert Path(outputs["python-path"]).parent.as_posix() in files["GITHUB_PATH"].read_text(encoding="utf-8").replace("\\", "/")
+ subprocess.run([outputs["python-path"], "-I", "-c", "import sys; assert sys.prefix != sys.base_prefix"], check=True)
+
+
+def test_ci_packages_exports_python_and_preserves_real_child_exit(tmp_path, monkeypatch, local_toolchain):
+ import pm
+ from scripts.ci import python_packages
+ from tests.pm.test_workspace_build_inputs import _wheel
+
+ wheels = tmp_path / "wheels"
+ wheels.mkdir()
+ _wheel(wheels, "ci_probe", "1.0")
+ python = pm.build_requirements_environment(
+ ["ci-probe==1.0"], out=tmp_path / "prepared", python=Path(sys.executable),
+ wheelhouse=wheels, offline=True, explicit=True,
+ )
+
+ def selected(name, requirements, *, explicit):
+ assert name == "ci-tools" and requirements == ["ci-probe==1.0"] and explicit
+ return python
+
+ monkeypatch.setattr(pm, "ensure_environment", selected)
+ exports, path = tmp_path / "environment", tmp_path / "path"
+ monkeypatch.setenv("GITHUB_ENV", str(exports))
+ monkeypatch.setenv("GITHUB_PATH", str(path))
+ assert python_packages.main(["ci-probe==1.0"]) == 0
+ values = dict(line.split("=", 1) for line in exports.read_text(encoding="utf-8").splitlines())
+ assert values["HERMES_PYTHON"] == str(python)
+ assert values["VIRTUAL_ENV"] == str(python.parent.parent)
+ assert not any(name.startswith("UV_") for name in values)
+ assert path.read_text(encoding="utf-8").strip() == str(python.parent)
+ assert python_packages.main([
+ "ci-probe==1.0", "--", "-I", "-c", "import ci_probe; raise SystemExit(37)",
+ ]) == 37
+
+
+def test_termux_gate_checks_real_offline_wheels_and_application_uses_same_graph(tmp_path, local_toolchain):
+ from pm.package import InstallError
+ from scripts.termux import build_wheels, build_environment
+ from tests.pm.test_workspace_build_inputs import _wheel
+
+ wheels = tmp_path / "wheelhouse"
+ wheels.mkdir()
+ _wheel(wheels, "native_probe", "1.0")
+ resolved = tmp_path / "resolved.txt"
+ resolved.write_text(
+ 'native-probe\t==1.0\t\t\n'
+ 'missing-windows-only\t==1.0\tsys_platform == "win32"\t\n'
+ 'nemo-relay\t==1.0\t\t\n', encoding="utf-8",
+ )
+ # This adapter runs on the actual host; no platform faking is needed.
+ if os.name == "nt":
+ resolved.write_text('native-probe\t==1.0\t\t\n', encoding="utf-8")
+ build_wheels.wheelhouse_gates(resolved, wheels, ["native-probe"])
+ requirements = tmp_path / "requirements.txt"
+ build_wheels.write_reqs_file(resolved, requirements)
+ build_environment.application(tmp_path, requirements, Path(sys.executable))
+ python = tmp_path / "venv" / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
+ subprocess.run([str(python), "-I", "-c", "import native_probe"], check=True)
+ for wheel in wheels.iterdir():
+ wheel.unlink()
+ with pytest.raises(InstallError):
+ build_wheels.wheelhouse_gates(resolved, wheels, ["native-probe"])
diff --git a/tests/scripts/test_pm_runtime_bundle.py b/tests/scripts/test_pm_runtime_bundle.py
index 334b0f5db33..e5f55778fab 100644
--- a/tests/scripts/test_pm_runtime_bundle.py
+++ b/tests/scripts/test_pm_runtime_bundle.py
@@ -20,7 +20,7 @@ def _exercise_relocated_pm_runtime(tmp_path, monkeypatch):
root = tmp_path / "build"
repo = root / "hermes-agent"
source = Path(__file__).resolve().parents[2]
- shutil.copytree(source / "pm", repo / "pm", ignore=shutil.ignore_patterns("__pycache__"))
+ shutil.copytree(source / "pm", repo / "pm", ignore=shutil.ignore_patterns("__pycache__", ".hermes-tmp.*"))
(repo / "hermes_cli").mkdir()
for name in ("__init__.py", "runtime_paths.py", "runtime_state.py"):
shutil.copy2(source / "hermes_cli" / name, repo / "hermes_cli" / name)
@@ -36,10 +36,12 @@ def _exercise_relocated_pm_runtime(tmp_path, monkeypatch):
stage = getattr(native, "stage_pm_runtime", None)
assert callable(stage), "native payload has no isolated PM runtime stage"
cache = tmp_path / "build-cache"
- stage(root, Path(uv), python, repo, cache=cache)
+ monkeypatch.setattr("pm.client._request", lambda *args, **kwargs: pytest.fail("runtime staging must not bootstrap a worker"))
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(uv), Path(sys.executable)))
+ stage(root, python, repo, cache=cache)
assert cache.is_dir()
assert not (tmp_path / "home/cache/uv").exists()
- stage(root, Path(uv), python, repo, offline=True, cache=cache)
+ stage(root, python, repo, offline=True, cache=cache)
(root / "manifest.json").write_text(json.dumps({"repo": "hermes-agent"}))
assert not (repo / ".venv").exists()
moved = tmp_path / "installed elsewhere"
@@ -89,7 +91,7 @@ def test_resident_pm_bypasses_windows_redirector_after_move(tmp_path, monkeypatc
@pytest.mark.parametrize("poison", ["cwd", "global"])
def test_pm_builder_ignores_ambient_uv_configuration(tmp_path, monkeypatch, poison):
- from pm.runtime_stage import stage_runtime
+ from pm import stage_manager_runtime
monkeypatch.setattr(Path, "home", lambda: tmp_path / "home")
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
@@ -102,7 +104,9 @@ def test_pm_builder_ignores_ambient_uv_configuration(tmp_path, monkeypatch, pois
config.write_text('required-version = "<0.1"\n', encoding="utf-8")
uv = shutil.which("uv")
assert uv
- executable = stage_runtime(Path(uv), Path(sys.executable), tmp_path / "runtime")
+ monkeypatch.setattr("pm.client._request", lambda *args, **kwargs: pytest.fail("runtime staging must not bootstrap a worker"))
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(uv), Path(sys.executable)))
+ executable = stage_manager_runtime(python=Path(sys.executable), destination=tmp_path / "runtime")
assert executable.is_file()
@@ -135,19 +139,18 @@ def test_native_stage_builds_pm_before_application_environment(tmp_path, monkeyp
monkeypatch.setattr(native, "_install_names", lambda names: 0)
monkeypatch.setattr(native, "Facts", Facts)
monkeypatch.setattr(native, "_facts", Facts)
- monkeypatch.setattr(native, "pm_uv", lambda: ("uv", {}))
monkeypatch.setattr(native, "_store", lambda: SimpleNamespace(entry=lambda name: tmp_path / "tools" / name))
monkeypatch.setattr(native, "get_package", lambda name: SimpleNamespace(binary=lambda path, target: path / "python"))
cache_dir = tmp_path / "cache"
monkeypatch.setenv("UV_CACHE_DIR", str(cache_dir))
- def staged(root, uv, python, repo, *, cache):
+ def staged(root, python, repo, *, cache):
assert cache == cache_dir
- calls.append((root, uv, python, repo))
+ calls.append((root, python, repo))
raise StopAfterPM
monkeypatch.setattr(native, "stage_pm_runtime", staged)
with pytest.raises(StopAfterPM):
native._stage_native(SimpleNamespace(out=str(tmp_path), ref="HEAD"))
- assert calls == [(tmp_path, Path("uv"), tmp_path / "tools/python/python", tmp_path / "hermes-agent")]
+ assert calls == [(tmp_path, tmp_path / "tools/python/python", tmp_path / "hermes-agent")]
diff --git a/tests/scripts/test_setup_toolchain.py b/tests/scripts/test_setup_toolchain.py
index e7c30f5a304..e14568e20ae 100644
--- a/tests/scripts/test_setup_toolchain.py
+++ b/tests/scripts/test_setup_toolchain.py
@@ -20,9 +20,10 @@ def test_development_setup_keeps_test_groups_out_of_the_runtime(tmp_path, monkey
import shutil
from scripts.ci import setup_toolchain
- from pm.packages import uv_env
+ from pm import lock_project
from tests.pm.test_workspace_build_inputs import _wheel
+ monkeypatch.setattr(Path, "home", lambda: tmp_path / "home")
core = tmp_path / "core"
core.mkdir()
wheels = tmp_path / "wheels"
@@ -37,15 +38,12 @@ def test_development_setup_keeps_test_groups_out_of_the_runtime(tmp_path, monkey
)
uv = shutil.which("uv")
assert uv
- environment = {**uv_env(), "UV_PYTHON": sys.executable, "UV_OFFLINE": "1"}
- environment.pop("UV_NO_CONFIG")
- subprocess.run([uv, "lock"], cwd=core, env=environment, check=True, capture_output=True, timeout=60)
+ monkeypatch.setattr("pm.client.is_runtime", lambda: True)
+ monkeypatch.setattr("pm._uv._toolchain", lambda **kwargs: (Path(uv), Path(sys.executable)))
+ lock_project(core, python=Path(sys.executable), offline=True, explicit=True)
home = tmp_path / "ci-home"
monkeypatch.setenv("HERMES_HOME", str(home))
monkeypatch.setattr("pm.paths.repo_root", lambda: core)
- import importlib
- engine = importlib.import_module("pm.ensure")
- monkeypatch.setattr(engine, "uv", lambda **kwargs: (uv, dict(environment)))
# This test exercises the worker-side CI environment split with offline uv.
# Dispatch into that worker is covered by test_runtime_entrypoints.
monkeypatch.setattr("pm.runtime.is_runtime", lambda: True)