The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
merge: unify shared product builders, caches, and Windows prerequisites
ethernetfea2858c99ac
diff --cc .github/actions/setup-windows-build-deps/action.ymlindex 00000000000,00000000000..e42ecb1c939new file mode 100644--- /dev/null+++ b/.github/actions/setup-windows-build-deps/action.yml@@@ -1,0 -1,0 +1,21 @@@++name: Set up native Windows ARM64 build dependencies++description: Prepare MSVC, SDK, Clang, Rust and static OpenSSL through the shared PowerShell installer.++runs:++ using: composite++ steps:++ - name: Cache ARM64 OpenSSL development files++ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0++ with:++ # Cache libraries and headers only, not a vcpkg checkout or machine state.++ path: C:\vcpkg\installed\arm64-windows-static-md++ key: windows-build-deps-v2-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/windows-build-deps.ps1', 'scripts/build/windows-deps.ps1') }}++++ - name: Initialize the native build environment++ shell: powershell++ env:++ _WINDOWS_BUILD_ACTION: ${{ github.action_path }}++ run: |++ & "$env:_WINDOWS_BUILD_ACTION/../../../scripts/build/windows-deps.ps1" `++ -StateRoot "$env:RUNNER_TEMP/windows-build-deps" `++ -OpenSSLRoot 'C:\vcpkg' `++ -GithubEnv $env:GITHUB_ENV -GithubPath $env:GITHUB_PATHdiff --cc .github/workflows/desktop-bundled-release.ymlindex f4c5eccafdf,64d3a2f1117..a9381b96d8a--- a/.github/workflows/desktop-bundled-release.yml+++ b/.github/workflows/desktop-bundled-release.yml@@@ -342,24 -341,24 +342,9 @@@ jobspayload-signatures-v1-${{ runner.os }}-${{ matrix.target.label }}-payload-signatures-v1-${{ runner.os }}--- - name: Cache vcpkg OpenSSL (arm64)++ - name: Set up native ARM64 build dependenciesif: matrix.target.label == 'win32-arm64'-- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0-- with:-- path: C:\vcpkg\installed\arm64-windows-static-md-- key: vcpkg-openssl-arm64-windows-static-md-${{ runner.os }}---- - name: Install OpenSSL (arm64)-- if: matrix.target.label == 'win32-arm64'-- shell: bash-- run: |-- if [ ! -f "/c/vcpkg/installed/arm64-windows-static-md/lib/libcrypto.lib" ]; then-- "$VCPKG_INSTALLATION_ROOT/vcpkg" install openssl:arm64-windows-static-md-- fi-- {-- printf 'OPENSSL_DIR=C:\\vcpkg\\installed\\arm64-windows-static-md\n'-- printf 'OPENSSL_STATIC=1\n'-- } >> "$GITHUB_ENV"++ uses: ./.github/actions/setup-windows-build-deps- name: Cache pm store# Tag-dispatched runs (every canary) scope actions/cache under the@@@ -482,7 -481,7 +467,6 @@@timeout-minutes: 900env:PYTHONUTF8: '1'-- CC_aarch64_pc_windows_msvc: ${{ matrix.target.label == 'win32-arm64' && 'clang' || '' }}AZURE_SIGN_ENDPOINT: ${{ vars.AZURE_SIGN_ENDPOINT }}AZURE_SIGN_ACCOUNT: ${{ vars.AZURE_SIGN_ACCOUNT }}AZURE_SIGN_PROFILE: ${{ vars.AZURE_SIGN_PROFILE }}diff --cc .github/workflows/pm-bundle.ymlindex 1d7ab07cb54,24940f49862..4bffeb0218b--- a/.github/workflows/pm-bundle.yml+++ b/.github/workflows/pm-bundle.yml@@@ -34,6 -34,6 +34,10 @@@ onpaths:- 'pm/**'- 'scripts/bundles/**'++ - 'scripts/windows-build-deps.ps1'++ - 'scripts/build/windows-deps.ps1'++ - 'scripts/build/windows_deps.py'++ - '.github/actions/setup-windows-build-deps/**'- 'uv.lock'- 'pyproject.toml'- '.github/workflows/pm-bundle.yml'@@@ -92,26 -91,26 +96,10 @@@ jobspath: build/agent-payload/toolskey: pm-store-v2-${{ matrix.target.label }}-${{ hashFiles('pm/lock.json', 'uv.lock') }}-- # win32-arm64 builds cryptography from sdist (no win_arm64 wheel);-- # its Rust core links OpenSSL statically from vcpkg.-- - name: Cache vcpkg OpenSSL (arm64)++ # win32-arm64 builds cryptography and obstore from sdist.++ - name: Set up native ARM64 build dependenciesif: matrix.target.label == 'win32-arm64'-- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0-- with:-- path: C:\vcpkg\installed\arm64-windows-static-md-- key: vcpkg-openssl-arm64-windows-static-md-${{ runner.os }}---- - name: Install OpenSSL (arm64)-- if: matrix.target.label == 'win32-arm64'-- shell: bash-- run: |-- if [ ! -f "/c/vcpkg/installed/arm64-windows-static-md/lib/libcrypto.lib" ]; then-- "$VCPKG_INSTALLATION_ROOT/vcpkg" install openssl:arm64-windows-static-md-- fi-- {-- printf 'OPENSSL_DIR=C:\\vcpkg\\installed\\arm64-windows-static-md\n'-- printf 'OPENSSL_STATIC=1\n'-- } >> "$GITHUB_ENV"++ uses: ./.github/actions/setup-windows-build-deps- name: Pin CMake < 4 for sdist builds# python-olm (matrix extra) builds libolm from sdist on non-Linux@@@ -132,25 -131,17 +120,23 @@@env:# Windows runners default to cp1252; pm prints UTF-8 (✓/✗).PYTHONUTF8: '1'-- # ring/obstore's C sources need clang, not MSVC, on windows-arm64.-- # Scoped to the cargo target triple so every other sdist keeps MSVC.-- CC_aarch64_pc_windows_msvc: ${{ matrix.target.label == 'win32-arm64' && 'clang' || '' }}run: |# Archive what actions/checkout actually checked out. On# pull_request events github.sha names a merge commit that a# force-push invalidates mid-run ("not a tree object").python -m pm.cli bundle \--out build/agent-payload \++ --cache "$UV_CACHE_DIR" \--ref HEAD+ - name: Save warmed Python dependencies even after a staging failure+ if: ${{ !cancelled() && steps.pm.outcome == 'success' }}+ uses: ./.github/actions/save-pm-cache+ with:+ uv: ${{ steps.pm.outputs.uv-path }}+ path: ${{ steps.pm.outputs.uv-cache-path }}+ key: ${{ steps.pm.outputs.python-cache-key }}+# The payload must boot with nothing from this checkout: the staged# venv's interpreter, cwd at the staged REPO (the desktop spawn# convention — sys.path[0] from cwd survives relocation where thediff --cc .github/workflows/pm-toolchain-smoke.ymlindex 9432f640af9,9432f640af9..0f125045824--- a/.github/workflows/pm-toolchain-smoke.yml+++ b/.github/workflows/pm-toolchain-smoke.yml@@@ -33,22 -33,22 +33,10 @@@ jobswith:persist-credentials: false-- # cryptography has no win_arm64 wheel. Its native build uses the-- # same OpenSSL prerequisite as the bundled release, not an x64 Python.-- - name: Cache native OpenSSL++ # The dev extra can build ARM64 sdists during setup-pm itself.++ - name: Set up native ARM64 build dependenciesif: matrix.target == 'win32-arm64'-- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0-- with:-- path: C:\vcpkg\installed\arm64-windows-static-md-- key: vcpkg-openssl-arm64-windows-static-md-${{ runner.os }}-- - name: Install native OpenSSL-- if: matrix.target == 'win32-arm64'-- shell: bash-- run: |-- if [ ! -f /c/vcpkg/installed/arm64-windows-static-md/lib/libcrypto.lib ]; then-- "$VCPKG_INSTALLATION_ROOT/vcpkg" install openssl:arm64-windows-static-md-- fi-- printf 'OPENSSL_DIR=C:\\vcpkg\\installed\\arm64-windows-static-md\nOPENSSL_STATIC=1\n' >> "$GITHUB_ENV"++ uses: ./.github/actions/setup-windows-build-deps- name: Set up tools and dev extra from PMid: pm@@@ -84,7 -84,7 +72,7 @@@- name: Run the PM and action contractsshell: bashrun: |-- scripts/run_tests.sh -j 2 tests/scripts/test_setup_toolchain.py tests/pm/test_pm_core.py tests/pm/test_bootstrap_import_closure.py tests/pm/test_uv_cache.py++ scripts/run_tests.sh -j 2 tests/scripts/test_setup_toolchain.py tests/pm/test_pm_core.py tests/pm/test_bootstrap_import_closure.py tests/pm/test_uv_cache.py tests/pm/test_windows_build_deps.pypython scripts/ci/verify_toolchain.py --extras- name: Upload native setup proofdiff --cc .github/workflows/pm-toolchain.ymlindex 90c3b98c3ca,4c07715877d..c1f5a08e996--- a/.github/workflows/pm-toolchain.yml+++ b/.github/workflows/pm-toolchain.yml@@@ -5,7 -5,6 +5,12 @@@ onpull_request:paths:- '.github/actions/setup-pm/**'+ - '.github/actions/save-pm-cache/**'++ - '.github/actions/setup-windows-build-deps/**'++ - 'scripts/windows-build-deps.ps1'++ - 'scripts/build/windows-deps.ps1'++ - 'scripts/build/windows_deps.py'++ - 'tests/pm/test_windows_build_deps.py'- '.github/workflows/pm-toolchain*.yml'- 'scripts/ci/*toolchain.py'- 'tests/scripts/test_setup_toolchain.py'diff --cc docs/shared-bundle-builds.mdindex 40177b8f850,db2611e7ac0..9e302cd1415--- a/docs/shared-bundle-builds.md+++ b/docs/shared-bundle-builds.md@@@ -19,77 -39,174 +39,181 @@@ Build a desktop distribution from a cheuv run --no-project --python 3.14 python scripts/bundles/desktop.py --tag=vX.Y.Z```- The builder derives console entrypoints from the archived `pyproject.toml`.- It checks the interpreter, dependency tree, and generated launchers before- publishing their relative paths in the payload manifest. The desktop build- bakes this launch contract into its stamp. Electron uses the declared paths- without payload probes, adoption, or repair. Non-bundled builds carry no- placeholder payload. The stamp also declares the update mechanism. Store- packages use `microsoft-store`, and sideload bundles use `app-installer`. The runtime- has no separate Store probe or compatibility fallback.- The MSIX hook reads the declared launcher names- rather than carrying a second entrypoint list. POSIX launchers follow- links to the installed payload and call each declared function directly.- Windows launchers are minted by the payload's own Python, preserving native- architecture and relocation behavior.-- Termux uses the same snapshot, manifest/fact writer, JS asset placement and- POSIX launcher generator. Its package-manager hooks stay in `scripts/termux/`.- Its bionic wheel compilation and offline installation remain target-specific:- a glibc host cannot execute the shipped interpreter, and Termux has a fixed- installation prefix. Native desktop staging instead resolves on the target OS.- Neither path compiles dependencies on the user's machine.-- Electron-specific work stays with Electron: renderer/main-process bundling,- Node native bindings, MSIX metadata, signing, notarization and app packaging.- The after-pack hook invokes the shared Python relocation command instead of- maintaining its own link rewrite algorithm.-- Ordinary bundle staging does not scan user plugin trees. Runtime plugin- admission is a separate PM transaction. Build output cleanup is confined to- its payload store; it must not prune the machine-wide downloader partials.-- ## Target boundaries-- Desktop stages on the target OS and architecture. Its dependency step uses- `uv sync --frozen --all-extras --active` on the staged interpreter.- The complete desktop builder, not `pm bundle` alone, adds prebuilt JS surfaces- and invokes Electron packaging.-- Termux's host scripts run on Linux ARM64. `build_cpython.sh` and `build_node.sh`- stage pinned bionic packages; `stage_runtime_libs.py` supplies their native- library closure. `termux_build.sh` exports the tag's core plus `acp` requirements,- builds the required native wheels in the pinned bionic container, and records- wheelhouse inputs. `build_deb.sh` assembles the environment offline, creates the- APT package, and validates it in a fresh container without network access.- Those container checks do not substitute for Android device acceptance.-- The installed Termux root is `$PREFIX/lib/hermes-agent/`. It contains `app`,- `tools`, `runtime-libs`, `venv`, `bin`, and the PM manifest/facts. Maintainer- hooks manage only the package's CLI symlinks under `$PREFIX/bin` and refuse- foreign launcher conflicts. They do not compile dependencies on install.+ `desktop.py` requires exactly one of `--tag` or `--commit`. Commit builds+ require the full commit SHA and matching checkout HEAD. `--variant` accepts+ `bundled`, `store`, or `light`, with `bundled` as the default. `--repo` selects+ the checkout. Arguments after `--` go to Electron Builder.++ The driver prepares Node dependencies, builds the selected products, and runs+ Electron packaging. The desktop npm build prepares its stamp and native tree+ before the shared desktop compiler. Electron-specific dependency compilation,+ MSIX metadata, signing, notarization, and package formats remain adapter work.++ Stage a native agent with both frontend products, without Electron packaging:++ ```sh+ python -m scripts.bundles.stage --out /work/agent-payload --ref HEAD+ ```++ This command prepares and builds TUI/web products if none are supplied. It+ also accepts `--tui` and `--web` together as prepared product roots. It rejects+ a selection with only one of those arguments. The standalone products have+ explicit input/output contracts in the builder README.++ `--ref` selects the agent source snapshot. Automatic frontend compilation uses+ a temporary snapshot of that same revision. Explicit frontend products must+ come from the selected revision.++ `hermes pm bundle --out /work/agent-payload --ref HEAD` stages native tools,+ the application environment, and the agent. That PM command does not build+ frontends. `npm run payload --workspace apps/desktop` uses the stage driver+ that includes them. Neither command creates an Electron installer.++ For Termux, tools and the wheelhouse are prerequisites:++ ```sh+ python scripts/termux/build.py --repo /work/source --payload /work/termux-payload \+ --out /work/packages --tag vX.Y.Z+ ```++ The Termux driver accepts exactly one of `--tag` or `--commit`. It prepares+ the TUI workspace, calls the shared TUI builder, and passes that product to+ `build_deb.sh`. It does not add the dashboard or replace bionic preparation.++ The CLI contracts are in `scripts/bundles/desktop.py:129–143`,+ `scripts/bundles/stage.py:17–46`, `pm/cli.py:442–444,488–491`, and+ `scripts/termux/build.py:21–62`.++ ## Shared agent and launcher contract++ `AgentInputs` supplies explicit paths and a placement mode:++ - `contained` keeps runtime inputs inside the native payload.+ - `fixed` retains the Docker or Termux installation prefix.+ - `references` keeps installed code and dependencies in separate Nix store paths.++ The assembler derives console commands from `[project.scripts]`. It copies+ source-layout resources and selected frontends, or links explicit reference+ inputs. It writes the completion manifest after structural assembly. Nix also+ receives a command/environment map for its native wrappers.++ The launcher implementation lives in `scripts/build/launchers.py`.+ `launcher_wrapper.py` and `mint_launchers.py` live in that same directory.+ `scripts/bundles/payload.py` owns git snapshots, PM tool facts, PM runtime+ sealing, and portable link handling. It no longer owns frontend placement or+ launcher generation.++ The desktop stamp carries the declared launch paths. Electron consumes that+ contract without payload adoption or repair. Non-bundled builds carry no+ placeholder agent payload. Store packages declare `microsoft-store` as their+ update mechanism. Sideload bundles declare `app-installer`.++ Windows launcher minting runs the payload interpreter. POSIX launchers use+ explicit interpreter, source, and dependency paths. Structural assembly does+ not replace target-native launch tests. A manifest alone does not prove that+ a relocated or signed artifact runs.++ ## Independent PM runtime++ PM dependencies come from `pm/pyproject.toml` and `pm/uv.lock`, not the+ application dependency graph. The application environment and `pm-runtime`+ are separate inputs to agent assembly.++ Native and Docker preparation use `pm.runtime_stage.stage_runtime`. Termux+ uses that function with its offline wheelhouse. Nix uses the independent+ `nix/pm-runtime.nix` derivation. Native sealing records the payload interpreter+ and PM-only site directory in `pm-runtime.json`.++ Resident PM workers run the declared interpreter with `-I -S -B`. They add+ only the declared PM dependency directory before the worker script. They do+ not borrow application dependencies or add PM packages to the caller's+ interpreter. Docker and Nix stamps point to their declared PM runtime.+ These contracts live in `pm/runtime.py:55–88,171–182` and+ `scripts/bundles/payload.py:58–90`.++ Ordinary native staging does not scan user plugin trees. It runs provisioning-in a child with build-owned home, cache, and PM roots. Live PM retains plugin++in a child with temporary home and PM roots plus an explicit persistent build++cache. Windows ARM64 prerequisite preparation runs before HOME isolation and++uses the same provider as source setup and CI. Live PM retains plugin+ admission, generation selection, and transaction state. Both paths use+ `pm.environment.PythonEnvironment` for explicit uv environment construction.++ ## Distribution boundaries and output paths++ | Distribution | Selected products | Current output layout |+ |---|---|---|+ | Desktop bundled/Store | Icons, TUI, web, agent, desktop UI | Products: `apps/desktop/build/products/`. Agent: `apps/desktop/build/agent-payload/`. UI: `apps/desktop/dist/`. Packages: `apps/desktop/release/` |+ | Desktop light | Icons and desktop UI | `apps/desktop/dist/` and `apps/desktop/release/`, without an agent payload |+ | Docker | Icons, TUI, web, agent | Agent at `/opt/hermes`, dependencies at `.venv`, PM at `pm-runtime`, generated commands at `libexec` |+ | Nix TUI | TUI | `$out/lib/hermes-tui/{dist/entry.js,package.json}` |+ | Nix web | Web | `$out/index.html` and assets |+ | Nix agent | Agent with TUI/web references | `$out/bin`, `$out/share/hermes-agent`, `$out/ui-tui`, `manifest.json`, and `command-map.json` |+ | Nix desktop | Icons and desktop UI, with the Nix agent | `$out/share/hermes-desktop` and `$out/bin/hermes-desktop` |+ | Termux | TUI and agent | `OUT/hermes-agent_<version>_aarch64.deb`, installed at `$PREFIX/lib/hermes-agent/` |++ Native payloads contain `hermes-agent`, `tools`, `venv`, `pm-runtime`, `bin`,+ `uv-cache`, and their manifests/facts. Copied frontend assets live at+ `hermes-agent/hermes_cli/tui_dist/` and `hermes-agent/hermes_cli/web_dist/`.+ The TUI asset directory contains `entry.js` and module-mode package metadata.++ Docker keeps its existing TUI product at `/opt/hermes/ui-tui` and web output+ at `/opt/hermes/hermes_cli/web_dist`. The assembler also plants its shared TUI+ asset layout beneath `hermes_cli/tui_dist`. Venv command symlinks preserve the+ paths used by s6 and the privilege-drop shim.++ The Docker frontend stage owns npm dependencies and compilation. The runtime+ stage copies only the frontend products and the locked TypeScript package for+ runtime linting. Node/npm and Photon's separately installed sidecar dependencies+ remain runtime inputs. Python dependency preparation precedes the application+ source copy. Actual cache-hit and layer-size claims require build evidence.++ Nix retains `importNpmLock`, uv2nix, platform overrides, and store references.+ Its builders run during derivation builds, not evaluation. Per-product source+ filters keep frontend, Python, and resource inputs separate. Nix wrappers+ consume the assembler's command map and retain their PATH and extra-Python+ collision policies.++ **Nix wheel policy:** `nix/python.nix:128–135` sets `HERMES_NIX_BUILD=1` only+ for the Hermes derivation. `setup.py:34–72` rejects general Hermes wheel/sdist+ builds. The shared assembler uses the installed Nix code without another copy.+ Other providers use source-layout code and metadata, not a public Hermes wheel.++ Termux retains bionic wheel compilation, offline installation, native library+ paths, and its fixed prefix. Its installed root contains `app`, `tools`,+ `runtime-libs`, `venv`, `pm-runtime`, `bin`, and manifests/facts. APT maintainer+ hooks manage the declared CLI symlinks under `$PREFIX/bin` and refuse foreign+ conflicts. They do not compile dependencies during installation.`stage_apt_repo.py` owns repository metadata and signatures. Stable and canary- suites are `hermes-stable` and `hermes-canary`; package files publish before- signed metadata. Runtime and repository pins are distinct from the native- build-toolchain packages used only inside CI.-- Docker and Nix consume PM pins but do not run this desktop payload assembly.- Docker has its own curated extras and image lifecycle. Nix uses uv2nix and- separate derivations. [Stable release admission](stable-releases.md) coordinates- their acceptance and publication with desktop and Termux packages.-- PM and Docker ship full Chromium, without a separate headless shell. The same- executable serves headed and headless sessions. Browser launchers use the- selected PM executable; direct Playwright callers select the `chromium` channel.- Native staging removes retired package facts and directories from its build- cache. It does not remove browser files from the user's machine-wide store.-- PM retains completed download archives until the package is verified and- published. Normal installs commit package facts before deleting their archives.- Cross-target staging verifies the published entry before deleting its archives.- Failed or paused installs keep downloads for retry. Cleanup leaves unrelated- archives and resumable partials alone. A later repair may download again.+ suites are `hermes-stable` and `hermes-canary`. Package files publish before+ signed metadata. [Stable release admission](stable-releases.md) coordinates+ acceptance and publication across distributions.++ ## Cache ownership++ PM binary download archives and the native uv wheel cache have different+ consumers. They are not interchangeable cleanup targets.++ - PM retains completed downloads until package verification and publication.+ Successful installs remove their exact fetch archives. Failures retain+ downloads for retry. Cleanup leaves unrelated partials alone.+ - Native staging prunes obsolete entries only in its build-owned tool store.+ It does not prune the user's machine-wide store.+ - Native staging retains `uv-cache/` for offline mutable-environment rebuilds.+ It keeps extracted wheel entries but removes wheel ZIPs beneath `sdists-v*`+ so native signing can reach the extracted binaries.++- PM-runtime and application builds share the provider's persistent uv cache.++ CI restores/saves that cache, not the temporary build HOME. Failed builds++ retain completed wheels. Only v2 keys are restored; there is no legacy fallback.++ Plain `uv cache prune` removes dangling entries without discarding offline++ wheel inputs. It does not remove all historical versions or enforce a size cap.+ - Icon preparation uses its own `SOURCE/.cache/icon-build`. Its build-only+ dependencies do not belong in the native application cache.+ - Frontend `node_modules` is a provider input, not a frontend product.+ Docker's runtime TypeScript and Photon selections are separate exceptions.++ The native cache behavior is in `scripts/bundles/native.py:55–65,202–216`.+ Removing all caches from a payload can break offline environment reconstruction.## Pinned binary inputsdiff --cc pm/cli.pyindex 68bcc79acc6,68bcc79acc6..66790aa4804--- a/pm/cli.py+++ b/pm/cli.py@@@ -488,6 -488,6 +488,7 @@@ def main(argv=None) -> intp = sub.add_parser("bundle", help="stage a payload (repo+store+facts+relocatable venv) into --out")p.add_argument("--out", required=True)p.add_argument("--ref", help="git ref for the repo snapshot (default HEAD)")++ p.add_argument("--cache", type=Path, help="persistent uv build cache (default: output sibling .uv-cache)")p.set_defaults(func=cmd_bundle)p = sub.add_parser("status", help="print the latest pm sync receipt (machine-readable)")diff --cc pm/environment.pyindex 00000000000,5f0b38085b5..e48a5336230mode 000000,100644..100644--- a/pm/environment.py+++ b/pm/environment.py@@@ -1,0 -1,152 +1,152 @@@+ """Explicit uv construction, independent of PM tool discovery and live selection.++ Callers own the destination, source/workspace, cache and publication lifecycle.+ This module neither discovers profiles nor modifies the process environment.+ """+ from __future__ import annotations++ import codecs+ from collections.abc import Mapping, Sequence+ from dataclasses import dataclass+ import io+ import os+ from pathlib import Path+ import subprocess+ import tempfile+ import time+ from typing import TextIO++ from pm.package import InstallError+++ def _run_streaming(command: list[str], *, cwd: Path, env: dict[str, str],+ timeout: int, output: TextIO) -> subprocess.CompletedProcess:+ """Keep CI progress live, a bounded diagnostic tail, and a wall-clock timeout."""+ deadline = time.monotonic() + timeout+ proc = subprocess.Popen(command, cwd=str(cwd), env=env, stdout=subprocess.PIPE,- stderr=subprocess.STDOUT, text=True, errors="replace", bufsize=0)++ stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace", bufsize=0)+ pipe = proc.stdout+ assert isinstance(pipe, io.TextIOWrapper) # Popen was given stdout=PIPE and text=True.+ tail = ""+ try:+ # A descendant can keep stdout open after proc exits. Nonblocking reads+ # bound that drain without leaving a thread stuck in readline()/close().+ # PM's Python >=3.14 supports nonblocking pipes on Windows as well as POSIX.+ os.set_blocking(pipe.fileno(), False)+ decoder = io.IncrementalNewlineDecoder(+ codecs.getincrementaldecoder(pipe.encoding)(errors="replace"), translate=True,+ )+ while True:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise subprocess.TimeoutExpired(command, timeout, stderr=tail)+ try:+ data = os.read(pipe.fileno(), 65536)+ except BlockingIOError:+ time.sleep(min(.05, remaining))+ continue+ text = decoder.decode(data, final=not data)+ if text:+ tail = (tail + text)[-2000:]+ output.write(text)+ output.flush()+ if not data:+ break+ # EOF can precede process exit; it does not grant another timeout budget.+ try:+ code = proc.wait(timeout=max(0, deadline - time.monotonic()))+ except subprocess.TimeoutExpired:+ raise subprocess.TimeoutExpired(command, timeout, stderr=tail) from None+ except BaseException:+ proc.kill()+ proc.wait(timeout=5)+ raise+ finally:+ pipe.close()+ return subprocess.CompletedProcess(command, code, "", tail)+++ @dataclass(frozen=True, kw_only=True)+ class PythonEnvironment:+ uv: Path+ python: Path+ destination: Path+ cache: Path+ env: Mapping[str, str]+ offline: bool = False+ output: TextIO | None = None++ @property+ def executable(self) -> Path:+ return self.destination / ("Scripts/python.exe" if os.name == "nt" else "bin/python")++ def _run(self, args: list[str], *, cwd: Path, timeout: int) -> subprocess.CompletedProcess:+ # The caller supplies policy (PM already sanitizes it via pm.ensure.uv).+ # Preserve intentional index credentials/settings; only explicit routing+ # inputs and project-config visibility override this child environment.+ env = {key: value for key, value in self.env.items() if key not in (+ "VIRTUAL_ENV", "PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP", "PYTHONEXECUTABLE",+ "UV_WORKING_DIR", "UV_PROJECT", "UV_CONFIG_FILE", "UV_NO_CONFIG",+ "UV_MANAGED_PYTHON", "UV_NO_MANAGED_PYTHON", "UV_SYSTEM_PYTHON",+ )}+ env.update(UV_PYTHON=str(self.python), UV_PROJECT_ENVIRONMENT=str(self.destination),+ UV_CACHE_DIR=str(self.cache), UV_PYTHON_DOWNLOADS="never")+ with tempfile.TemporaryDirectory(prefix="pm-uv-config-") as config:+ env.update(XDG_CONFIG_HOME=config, XDG_CONFIG_DIRS=config)+ command = [str(self.uv), *args]+ if self.offline:+ command.append("--offline")+ if self.output is not None:+ return _run_streaming(command, cwd=cwd, env=env, timeout=timeout, output=self.output)+ return subprocess.run(command, cwd=str(cwd), env=env, capture_output=True,- text=True, timeout=timeout)++ text=True, encoding="utf-8", errors="replace", timeout=timeout)++ def create(self) -> None:+ """Create at the final destination; callers must not move a live venv."""+ self.destination.parent.mkdir(parents=True, exist_ok=True)+ result = self._run(+ ["venv", "--relocatable", "--no-project", "--no-config",+ "--python", str(self.python), str(self.destination)],+ cwd=self.destination.parent, timeout=120,+ )+ if result.returncode:+ raise InstallError("venv", f"uv venv failed: {result.stderr[-600:]}")++ def sync(self, source: Path, *, extras: Sequence[str] = (), frozen: bool = True,+ all_extras: bool = False, no_install_project: bool = False) -> None:+ """Install the root and every member; resolve only in a writable workspace.++ ``frozen=False`` is reserved for the caller-owned generated workspace,+ never the original project's lock. Seed/replay policy belongs to PM.+ """+ from pm.workspace import classify_uv_failure++ if not frozen:+ locked = self._run(["lock", "--python", str(self.python)], cwd=source, timeout=1800)+ if locked.returncode:+ raise classify_uv_failure("lock", locked.returncode, locked.stderr or locked.stdout)+ # Locking members alone is insufficient: plain sync only installs root deps.+ command = ["sync", "--frozen", "--all-packages", "--python", str(self.python)]+ if all_extras:+ command.append("--all-extras")+ if no_install_project:+ # --all-packages has no single selected project in uv, so+ # --no-install-project alone does not exclude the root. Name it+ # explicitly without dropping member dependencies or installations.+ import tomllib++ project = tomllib.loads((source / "pyproject.toml").read_text(encoding="utf-8-sig"))+ command += ["--no-install-project", "--no-install-package", project["project"]["name"]]+ for extra in sorted(set(extras)):+ command += ["--extra", extra]+ result = self._run(command, cwd=source, timeout=1800)+ if result.returncode:+ raise classify_uv_failure("sync", result.returncode, result.stderr or result.stdout)++ def check(self) -> None:+ result = self._run(+ ["pip", "check", "--no-config", "--python", str(self.executable)],+ cwd=self.destination.parent, timeout=60,+ )+ if result.returncode:+ raise InstallError("venv", f"dependency validation failed: {result.stderr[-600:]}")diff --cc pm/runtime_stage.pyindex 6d3675c2dec,ab2b3aa7610..f95506dcd60--- a/pm/runtime_stage.py+++ b/pm/runtime_stage.py@@@ -13,7 -13,7 +13,7 @@@ from pm.package import InstallErrodef stage_runtime(uv: Path, python: Path, destination: Path, *,project: Path | None = None, offline: bool = False,-- wheelhouse: Path | None = None) -> Path:++ wheelhouse: Path | None = None, cache: Path | None = None) -> Path:"""Build at the final path; the caller owns publication and its marker.The scratch project prevents uv from discovering the application's workspace.@@@ -26,7 -26,7 +26,7 @@@destination = destination.absolute()executable = destination / ("Scripts/python.exe" if os.name == "nt" else "bin/python")env = runtime_environment()-- env["UV_CACHE_DIR"] = str(uv_cache_dir())++ env["UV_CACHE_DIR"] = str(uv_cache_dir() if cache is None else cache.absolute())env["UV_PROJECT_ENVIRONMENT"] = str(destination)env["UV_PYTHON"] = str(python)destination.parent.mkdir(parents=True, exist_ok=True)diff --cc scripts/build/README.mdindex 00000000000,4cbf9b8fd09..7e42ea0188dmode 000000,100644..100644--- a/scripts/build/README.md+++ b/scripts/build/README.md@@@ -1,0 -1,296 +1,321 @@@+ # Shared product builders++ These modules compile frontends and assemble a runnable agent from prepared+ inputs. They do not replace npm, uv, PM, or Nix.+ [Shared bundle builds](../../docs/shared-bundle-builds.md) describes the+ providers and distribution adapters.++ This reference describes the current interfaces, not completed artifact+ acceptance. A successful parser or helper test does not prove a distribution+ build or a target-native runtime.++ ## Ownership++ | 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 |+ | 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+ builders, they can access package registries. There is no universal installer,+ all-products dispatcher, or cross-platform Python environment.++ ## Prepared JavaScript workspace++ Run commands from the repository root. Replace the absolute example paths with+ build-owned paths.++ ```sh+ node scripts/build/node-deps.mjs --source /work/source \+ --workspace ui-tui --workspace web+ ```++ `--source` and at least one `--workspace` are required. A workspace can be its+ locked path or package name. The provider deduplicates the selection and runs+ one root `npm ci` operation. It includes root dependencies, development+ dependencies, and optional dependencies. It checks Node/npm against the root+ `engines` declarations. npm lifecycle scripts remain enabled.++ The prepared source needs these inputs:++ - Root `package.json` and `package-lock.json`.+ - Selected workspace manifests and their required `file:` dependency sources.+ - Source files and configuration for the selected product.+ - Resolved dependencies in workspace-local or root `node_modules`.++ Request the complete workspace union once. A later, narrower `npm ci` can+ remove dependencies that another product needs. This provider modifies the+ prepared workspace. It does not build a frontend or publish a completion stamp.+ Nix supplies dependencies through `importNpmLock` instead of this command.++ ## Frontend products++ ```sh+ node scripts/build/tui.mjs --source /work/source --out /work/products/tui+ node scripts/build/web.mjs --source /work/source \+ --icons /work/products/icons --out /work/products/web+ node scripts/build/desktop.mjs --source /work/source \+ --icons /work/products/icons --stamp /work/install-stamp.json \+ --native-deps /work/native-deps --out /work/products/desktop+ ```++ | Builder | Required CLI arguments | Additional CLI arguments | Product contents |+ |---|---|---|---|+ | `tui.mjs` | `--source`, `--out` | None | `dist/entry.js` and `package.json` with `type: module` |+ | `web.mjs` | `--source`, `--out`, `--icons` | None | `index.html`, Vite assets, and public assets |+ | `desktop.mjs` | `--source`, `--out`, `--icons`, `--stamp`, `--native-deps` | `--typecheck`, `--platform` | Renderer assets, `electron-main.mjs`, `electron-preload.js`, and native `node_modules` |++ Each output is the product directory itself. The desktop output is a `dist`+ directory, not an application package. The exported functions are `buildTui`,+ `buildWeb`, and `buildDesktop`. They return output paths, not a new provenance+ manifest.++ The compilers resolve modules from the supplied workspace. They do not run+ npm, uv, PM installation, or icon preparation. TypeScript/Vite scratch files+ stay outside source inputs. Compilation uses a private output directory next+ to the destination. A successful compile replaces the destination. A failed+ compile leaves the previous product in place and reports failure. Its presence+ alone does not prove that the latest build succeeded.++ Existing arbitrary output directories require the builder's `.hermes-product`+ marker. Files, symlinks, and source directories are rejected. The exact npm+ destinations (`ui-tui/dist`, `hermes_cli/web_dist`, `apps/desktop/dist`, and+ `apps/desktop/build/native-deps`) remain rebuildable without a prior marker.+ Other in-tree products live beneath `.build/` or `apps/desktop/build/products/`.++ ### Icons and native inputs++ `--icons` names the generator's output root, not a directory of loose icons.+ The web builder reads `web/public/` beneath it and requires `favicon.ico`.+ The desktop builder reads `apps/desktop/public/` beneath it and requires+ `apple-touch-icon.png`.++ Run the generator with a prepared `icon-build` Python environment:++ ```sh+ python scripts/generate_icons.py --source /work/source --out /work/products/icons+ python scripts/generate_icons.py --source /work/source --out /work/products/icons --check+ ```++ The generator reads artwork from `SOURCE/assets` and writes its declared paths+ beneath `OUT`. These paths also include desktop packaging, website, and+ bootstrap-installer assets. `--check` regenerates targets in memory and checks+ output image properties. It does not compare output bytes with regenerated bytes.+ The generator writes targets directly, not through the frontend+ publication helper.++ The convenience wrapper prepares the locked environment and can access the+ network:++ ```sh+ node scripts/generate-icons.mjs --source /work/source --out /work/products/icons+ ```++ It uses the isolated `icon-build` dependency group and+ `SOURCE/.cache/icon-build`. Both icon commands accept `--check`. Without+ explicit paths, they use the source checkout as the output root.++ The desktop native tree contains prepared packages, including `node-pty` with+ its compiled binding. macOS also requires `get-windows/main`. The provider owns+ the architecture and Electron ABI match. `--platform` defaults to the running+ Node platform and controls native-file checks. It does not cross-compile a+ binding. `--typecheck` enables the desktop renderer TypeScript check and defaults+ to false. The web builder always runs its TypeScript project check.++ The supplied install stamp controls the desktop main/preload build identity.+ The compiler does not create an install stamp, build the dashboard, package+ Electron, or sign native files.++ ### Source-development entrypoints++ Existing npm commands use these recipes:++ ```sh+ npm run build --workspace ui-tui+ npm run build --workspace web+ npm run build --workspace apps/desktop+ ```++ | Command | Output | Preparation outside the product compiler |+ |---|---|---|+ | TUI build | `ui-tui/dist/entry.js` | Existing installed workspace dependencies |+ | Web build | `hermes_cli/web_dist/` | npm `prebuild` prepares icons |+ | Desktop build | `apps/desktop/dist/` | Icons, root-install assertion, install stamp, and native-dependency staging |++ TUI and web scripts support a no-argument development mode. Explicit product+ mode requires the arguments in the earlier table. The desktop product script+ 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 \+ --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` |+ | `--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.+++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`)++selects the persistent cache explicitly. Direct staging also accepts the++provider's `UV_CACHE_DIR`; otherwise it uses the output parent's `.uv-cache`.++The PM runtime and application dependency builds receive this same cache.++CI's `setup-pm` restores it and `save-pm-cache` prunes/saves it after the build,++including a failed build. Cache keys use only the v2 namespace, without legacy++fallback. The packaged `uv-cache/` is a copy, not the writable build cache.++++### Windows ARM64 build prerequisites++++`scripts/windows-build-deps.ps1` owns Visual Studio ARM64, Clang, Rust, and++static OpenSSL preparation. Source setup calls its initializer. Native build++adapters use `scripts/build/windows-deps.ps1` through `windows_deps.py`, before++isolating HOME or compiling Node/Python dependencies. CI uses the same script++through `setup-windows-build-deps`, with an OpenSSL cache outside the product.++The product compilers and assembler do not install these prerequisites.++++The PowerShell entrypoint accepts `-StateRoot` for persistent build-tool state++and `-EnvironmentFile` for its prepared environment. The Python adapter passes++that environment only to build children. Rust's original toolchain homes stay++explicit, so temporary HOME isolation cannot hide an initialized toolchain.++CI exports the same compiler, SDK, Rust, and OpenSSL environment to later steps.++Warm OpenSSL reuse validates both static libraries and its development header.+++ ## Runnable agent assembly++ ```sh+ python -m scripts.build.agent --inputs /work/agent-inputs.json --out /work/agent+ ```++ The only builder arguments are `--inputs` and `--out`. Python entrypoints also+ accept argparse's `-h`/`--help`. The library interface is+ `assemble(AgentInputs(...), out)`. The input JSON rejects unknown fields.++ ### Input fields++ All supplied filesystem input paths must be absolute and exist. `repo` and+ `bin_dir` are output-relative names, not filesystem inputs.++ | Field | Required | Meaning |+ |---|---|---|+ | `project` | Yes | `pyproject.toml` with static project metadata and `[project.scripts]` |+ | `code` | Yes | Prepared source tree, or installed code root for reference placement |+ | `repo` | Yes | Code/resource location beneath `OUT`, such as `hermes-agent`, `.`, or `share/hermes-agent` |+ | `placement` | Yes | `contained`, `fixed`, or `references` |+ | `target` | Yes | `linux-x64`, `linux-arm64`, `darwin-x64`, `darwin-arm64`, `win32-x64`, `win32-arm64`, or `linux-arm64-bionic` |+ | `python` | Yes | Prepared target interpreter file |+ | `site_packages` | Yes | Prepared application dependency directory |+ | `environment` | Yes | Prepared application environment root |+ | `pm_runtime` | Yes | Independent PM runtime directory with `pm-runtime.json` |+ | `bin_dir` | No | One output-relative directory name. Default: `bin` |+ | `tools` | No | Prepared runtime tool directory. The manifest defaults to `tools` if omitted |+ | `command_dir` | For `references` | Directory of prepared commands declared by the project |+ | `resources` | No | Resource-name to directory mapping |+ | `frontends` | No | `tui` and/or `web` product paths |+ | `ref` | No | Source identity copied to the completion manifest |+ | `stamp` | No | Prepared install stamp copied to `OUT/repo/install-stamp.json` |+ | `features` | No | Prepared feature inventory copied to `OUT/enabled-features.json` |+ | `env` | No | Additional environment values in the reference-placement command map |++ Recognized resource names are `skills`, `optional-skills`, `plugins`, `locales`,+ and `optional-mcps`. Distribution adapters supply the required resources.+ The generic assembler does not infer a missing resource mapping. TUI inputs+ require `dist/entry.js` and `package.json`. Web inputs require `index.html`.++ The PM marker supplies `python` and `sitePackages` paths relative to its runtime+ directory, or absolute store references. These paths must resolve to real+ inputs. If a supplied stamp declares `nix` or `docker`, its `pmRuntime` must+ match the supplied PM runtime. The assembler does not create that environment.++ ### Placement and output++ - **`contained`:** The provider prepares the interpreter, dependencies, PM+ runtime, and tools inside `OUT`. Assembly copies source/resources, plants+ frontends, and calls the portable link helper.+ - **`fixed`:** The provider owns final-prefix preparation. Assembly copies or+ reuses source/resources and generates launchers without portable relocation.+ Docker and Termux use this placement.+ - **`references`:** Assembly references installed code and commands without+ copying Python code or replacing wheel metadata. It links explicit resources+ and frontends, then emits `command-map.json`. Nix creates its native wrappers+ from this map.++ Source-layout placement writes project distribution metadata without building+ a Hermes wheel. It also writes `site_packages/hermes-agent.pth` with a relative+ code path. Source-layout placement therefore requires an output-owned dependency+ directory, including in `fixed` mode. Reference placement does not write this file.++ Commands derive from `[project.scripts]`, not a second command+ list. POSIX launchers use the supplied runtime paths. Windows launcher minting+ runs the target interpreter and therefore needs a runnable native environment.+ A target label alone does not prove ABI compatibility.++ For copied frontends, the assembler places TUI files at+ `OUT/repo/hermes_cli/tui_dist/` and web files at+ `OUT/repo/hermes_cli/web_dist/`. Reference placement links TUI at `OUT/ui-tui`+ and web at `OUT/repo/web_dist` and records their environment bindings.++ After structural assembly, `manifest.json` records `schema`, `target`, `repo`,+ `venv`, `store`, `launchers`, and `runtime`, plus `ref` when supplied. Its+ `runtime` contains `repoDir`, `toolsDir`, `storePython`, `sitePackages`, and+ `commands`. Reference placement also emits command sources, destinations,+ entrypoints, and environment values in `command-map.json`.++ Agent assembly modifies its output in place. It removes old completion records+ before work and writes the manifest last. This is not the frontend builder's+ atomic-directory publication contract. A failed assembly can leave partial+ files. The manifest is not evidence of a target-native launch or signed-package+ acceptance.++ ## Implementation references++ These locations define the interfaces described here:++ | Contract | Source |+ |---|---|+ | Frontend arguments and publication | `frontend-common.mjs:31–79` |+ | TUI product and development output | `tui.mjs:25–103` |+ | 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` |+ | 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` |++ ## Verification still required++ Parser checks and source inspection establish the documented call shapes.+ They do not establish offline compilation, cache reuse, or runtime success.+ Artifact acceptance still needs these checks:++ - Real frontend builds from immutable prepared inputs without network access.+ - Standalone TUI interaction and dashboard assets/backend behavior.+ - Native Electron bindings under the packaged Electron version.+ - Agent CLI, ACP, plugins, and catalogs from an unrelated working directory.+ - Native payload relocation and offline mutable-environment reconstruction.+ - Docker runtime probes as its non-root user and layer-content inspection.+ - Actual Nix builds and commands through store-reference wrappers.+ - Fresh network-disabled bionic installation and Android device acceptance.++ Docker/Nix build execution belongs to the distribution verification work, not+ this documentation pass. No build-pass claim follows from this reference.diff --cc scripts/build/windows-deps.ps1index 00000000000,00000000000..35c5c171937new file mode 100644--- /dev/null+++ b/scripts/build/windows-deps.ps1@@@ -1,0 -1,0 +1,44 @@@++# Build-only prerequisites; setup-hermes.ps1 uses the same installer functions.++param(++ [Parameter(Mandatory = $true)][string]$StateRoot,++ [string]$OpenSSLRoot,++ [string]$EnvironmentFile,++ [string]$GithubEnv,++ [string]$GithubPath++)++$ErrorActionPreference = 'Stop'++++$before = @{}++Get-ChildItem Env: | ForEach-Object { $before[$_.Name] = $_.Value }++. (Join-Path $PSScriptRoot '..\windows-build-deps.ps1')++Initialize-HermesArm64BuildTools -StateRoot $StateRoot -OpenSSLRoot $OpenSSLRoot++++$after = @{}++Get-ChildItem Env: | ForEach-Object { $after[$_.Name] = $_.Value }++$utf8 = New-Object System.Text.UTF8Encoding($false)++if ($EnvironmentFile) {++ # The caller owns this temporary file: it includes the inherited environment.++ [IO.File]::WriteAllText($EnvironmentFile, ($after | ConvertTo-Json -Compress), $utf8)++}++if ($GithubEnv) {++ foreach ($name in ($after.Keys | Sort-Object)) {++ # GitHub rejects writes to its own variables (and NODE_OPTIONS).++ if ($name -match '^(GITHUB_|RUNNER_)' -or $name -eq 'NODE_OPTIONS') { continue }++ if ($name -eq 'PATH' -and $GithubPath) { continue }++ # Rust homes must stay explicit when a later child isolates HOME.++ if ($name -notin @('CARGO_HOME', 'RUSTUP_HOME') -and++ $before.ContainsKey($name) -and $before[$name] -ceq $after[$name]) { continue }++ $delimiter = 'hermes_' + [Guid]::NewGuid().ToString('N')++ [IO.File]::AppendAllText($GithubEnv, "$name<<$delimiter`n$($after[$name])`n$delimiter`n", $utf8)++ }++}++if ($GithubPath) {++ # The runner prepends each line. Reverse only new entries so their compiler++ # search order survives, without replacing the caller's inherited PATH.++ $inherited = @($before['PATH'] -split ';')++ $added = @($after['PATH'] -split ';' | Where-Object { $_ -and $_ -notin $inherited } | Select-Object -Unique)++ [array]::Reverse($added)++ foreach ($entry in $added) {++ [IO.File]::AppendAllText($GithubPath, "$entry`n", $utf8)++ }++}diff --cc scripts/build/windows_deps.pyindex 00000000000,00000000000..bfa603e7b47new file mode 100644--- /dev/null+++ b/scripts/build/windows_deps.py@@@ -1,0 -1,0 +1,29 @@@++"""Prepare native Windows build inputs without changing the caller's process."""++from __future__ import annotations++++from collections.abc import Mapping++import json++from pathlib import Path++import shutil++import subprocess++import tempfile++++++def prepare_windows_environment(*, source: Path, state: Path, env: Mapping[str, str]) -> dict[str, str]:++ """The distribution adapter decides whether this target needs ARM64 tools."""++ shell = shutil.which("powershell", path=env.get("PATH")) or shutil.which("pwsh", path=env.get("PATH"))++ if shell is None:++ raise FileNotFoundError("PowerShell is required to prepare Windows ARM64 build dependencies")++ state.mkdir(parents=True, exist_ok=True)++ with tempfile.TemporaryDirectory(prefix="environment-", dir=state) as scratch:++ output = Path(scratch) / "environment.json"++ subprocess.run(++ [shell, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File",++ str(source / "scripts/build/windows-deps.ps1"), "-StateRoot", str(state),++ "-EnvironmentFile", str(output)],++ cwd=source, env=dict(env), check=True,++ )++ prepared = json.loads(output.read_text(encoding="utf-8-sig"))++ if not isinstance(prepared, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k, v in prepared.items()):++ raise ValueError("Windows build dependency provider returned an invalid environment")++ return prepareddiff --cc scripts/bundles/desktop.pyindex 31868318f88,37e7f06cee3..e943080d996--- a/scripts/bundles/desktop.py+++ b/scripts/bundles/desktop.py@@@ -94,16 -91,9 +91,13 @@@ def build(repo: Path, tag: str | None,node_arch = capture([node, "-p", "process.arch"], repo)if node_arch != target.split("-")[1]:raise ValueError(f"Node {node_arch} does not match build target {target}")- stamp = json.dumps({"lock": hashlib.sha256((repo / "package-lock.json").read_bytes()).hexdigest(),- "node": capture([node, "--version"], repo),- "npm": capture([*npm, "--version"], repo), "target": target}, sort_keys=True)- stamp_path = repo / "node_modules/.install-stamp"- if not stamp_path.is_file() or stamp_path.read_text(encoding="utf-8-sig") != stamp:- stamp_path.unlink(missing_ok=True)- run([*npm, "ci", "--no-audit", "--no-fund", "--fetch-retries=5", "--prefer-offline"], cwd=repo, env=env)- stamp_path.write_text(stamp, encoding="utf-8")- # Use the installed semver implementation for package.json's actual grammar.- run([node, "-e", "const s=require('semver'),p=require('./package.json'); for(const [n,v] of [['node',process.versions.node],['npm',process.argv[1]]]) if(!s.satisfies(v,p.engines[n])) throw Error(n+' violates '+p.engines[n])", capture([*npm, "--version"], repo)], cwd=repo, env=env)++ if target == "win32-arm64":++ from scripts.build.windows_deps import prepare_windows_environment++++ env = prepare_windows_environment(source=repo, state=repo / "apps/desktop/build/.build-deps", env=env)+ workspaces = ["apps/desktop"] + ([] if variant == "light" else ["ui-tui", "web"])+ run([node, "scripts/build/node-deps.mjs", "--source", str(repo),+ *[arg for workspace in workspaces for arg in ("--workspace", workspace)]], cwd=repo, env=env)payload = repo / "apps/desktop/build/agent-payload"if variant == "light":shutil.rmtree(payload, ignore_errors=True)diff --cc scripts/bundles/native.pyindex 0053f407277,88aac8d95d7..83026975699--- a/scripts/bundles/native.py+++ b/scripts/bundles/native.py@@@ -61,7 -65,7 +65,8 @@@ def stage_uv_cache(source: Path, destinwheel.unlink()--def stage_pm_runtime(root: Path, uv: Path, python: Path, repo: Path, *, offline: bool = False) -> None:++def stage_pm_runtime(root: Path, uv: 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_runtimefrom scripts.bundles.payload import seal_pm_runtime@@@ -69,19 -73,30 +74,36 @@@destination = root / "pm-runtime"if destination.exists():shutil.rmtree(destination)-- stage_runtime(uv, python, destination, project=repo / "pm", offline=offline)++ stage_runtime(uv, python, destination, project=repo / "pm", offline=offline, cache=cache)seal_pm_runtime(root, python)def stage_native(args) -> int:- previous = os.environ.get("HERMES_RUNTIME_DIR")- try:- return _stage_native(args)- finally:- if previous is None:- os.environ.pop("HERMES_RUNTIME_DIR", None)- else:- os.environ["HERMES_RUNTIME_DIR"] = previous- """Provision in a child with build-owned HOME/cache/PM roots."""++ """Isolate HOME and PM state, but retain the provider's reusable build cache."""+ out = Path(args.out).resolve()+ out.mkdir(parents=True, exist_ok=True)+ (out / "manifest.json").unlink(missing_ok=True)+ root = Path(__file__).resolve().parents[2]++ cache = Path(getattr(args, "cache", None) or os.environ.get("UV_CACHE_DIR") or out.parent / ".uv-cache").resolve()++ base_env = dict(os.environ)++ if current_target() == "win32-arm64":++ from scripts.build.windows_deps import prepare_windows_environment++++ base_env = prepare_windows_environment(source=root, state=out.parent / ".build-deps", env=base_env)+ with tempfile.TemporaryDirectory(prefix=".build-", dir=out) as work:- env = {**os.environ, "HOME": work, "USERPROFILE": work,++ env = {**base_env, "HOME": work, "USERPROFILE": work,+ "HERMES_HOME": str(Path(work) / ".hermes"),+ "HERMES_RUNTIME_DIR": str(out / "tools"),+ "HERMES_PYTHON_SRC_ROOT": str(root),+ "XDG_CACHE_HOME": str(Path(work) / "cache"),+ "XDG_CONFIG_HOME": str(Path(work) / "config"),- "UV_CACHE_DIR": str(Path(work) / "uv-cache"),++ "UV_CACHE_DIR": str(cache),+ "PYTHONPATH": os.pathsep.join([str(root), *filter(None, sys.path)])}+ command = [sys.executable, "-B", "-m", "scripts.bundles.native", "--out", str(out),+ "--ref", args.ref or "HEAD", "--source", str(root)]+ for name, product in getattr(args, "frontends", {}).items():+ command += [f"--{name}", str(product)]+ return subprocess.run(command, cwd=root, env=env).returncodedef _stage_native(args) -> int:@@@ -146,7 -163,9 +170,10 @@@_store().entry(python_fact["entry"]), current_target())- stage_pm_runtime(out, Path(uv_bin), python_bin, repo_dir)+ if python_bin is None:+ raise FileNotFoundError("staged Python executable is missing")- stage_pm_runtime(out, Path(uv_bin), python_bin, repo_dir)++ cache = Path(os.environ["UV_CACHE_DIR"])++ stage_pm_runtime(out, Path(uv_bin), python_bin, repo_dir, cache=cache)print("✓ pm-runtime (independent locked dependencies)", flush=True)# Build + sync INSIDE the staged repo: the editable project install@@@ -163,16 -182,17 +190,16 @@@# sdist builds at the machine's real toolchain.env.setdefault("AR", "/usr/bin/ar")env.setdefault("CC", "clang")- for cmd in (- [uv_bin, "venv", "--relocatable", "--python", str(python_bin), str(venv_dir)],- [uv_bin, "sync", "--frozen", "--all-extras", "--active"],- ):- print(f" venv: $ {' '.join(cmd)}", flush=True)- code, tail = _run_live(cmd, cwd=repo_dir, env=env)- if code != 0:- print(f"✗ venv: {' '.join(cmd[1:3])} failed:\n{tail}")- return 1- print("✓ venv (relocatable, all extras, on the staged interpreter)")+ from scripts.build.python_env import build_python_environment+ from pm.package import InstallError+- cache = Path(os.environ["UV_CACHE_DIR"])+ try:+ build_python_environment(source=repo_dir, python=python_bin, uv=Path(uv_bin),+ out=venv_dir, env=env, cache=cache, all_extras=True)+ except InstallError as exc:+ print(f"✗ venv: {exc}")+ return 1+ print("✓ venv (all extras, on the staged interpreter)")# Inventory the staged interpreter before publishing the bundle contract.from pm.features import FeatureProbeError, installed_extras, write_featuresdiff --cc scripts/bundles/stage.pyindex e530e15383b,be8e478b684..a552abaa850--- a/scripts/bundles/stage.py+++ b/scripts/bundles/stage.py@@@ -16,14 -18,35 +18,36 @@@ def main(argv=None) -> intparser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--out", required=True)parser.add_argument("--ref", default="HEAD")- args = parser.parse_args()- code = stage_native(args)- if code:- return code- root = Path(args.out).resolve()- manifest = json.loads((root / "manifest.json").read_text(encoding="utf-8-sig"))- stage_launchers(root, manifest)- return 0++ parser.add_argument("--cache", type=Path, help="persistent uv build cache")+ parser.add_argument("--tui", type=Path)+ parser.add_argument("--web", type=Path)+ args = parser.parse_args(argv)+ if bool(args.tui) != bool(args.web):+ parser.error("supply both --tui and --web products, or neither to build them")+ out = Path(args.out).resolve()+ out.mkdir(parents=True, exist_ok=True)+ (out / "manifest.json").unlink(missing_ok=True)+ if args.tui is not None:+ args.frontends = {"tui": args.tui.resolve(), "web": args.web.resolve()}+ return stage_native(args)+ node = shutil.which("node")+ if node is None:+ raise FileNotFoundError("Node is required to build frontend products")+ with tempfile.TemporaryDirectory(prefix="hermes-products-") as temp:+ products = Path(temp)+ source = products / "source"+ from scripts.bundles.payload import snapshot+ snapshot(ROOT, args.ref, source)+ commands = [+ ["scripts/build/node-deps.mjs", "--source", str(source), "--workspace", "ui-tui", "--workspace", "web"],+ ["scripts/generate-icons.mjs", "--source", str(source), "--out", str(products / "icons")],+ ["scripts/build/tui.mjs", "--source", str(source), "--out", str(products / "tui")],+ ["scripts/build/web.mjs", "--source", str(source), "--icons", str(products / "icons"), "--out", str(products / "web")],+ ]+ for command in commands:+ subprocess.run([node, *command], cwd=ROOT, check=True)+ args.frontends = {"tui": products / "tui", "web": products / "web"}+ return stage_native(args)if __name__ == "__main__":diff --cc scripts/windows-build-deps.ps1index 3aaf6aeb2f4,00000000000..67bea20790cmode 100644,000000..100644--- a/scripts/windows-build-deps.ps1+++ b/scripts/windows-build-deps.ps1@@@ -1,152 -1,0 +1,163 @@@+# Native build dependencies are separate from PM's application environment.+function Invoke-HermesBuildCommand {+ param([string]$Command, [string[]]$Arguments)+ $executable = (Get-Command $Command -CommandType Application -ErrorAction Stop).Source+ $previousPreference = $ErrorActionPreference+ try {+ $ErrorActionPreference = 'Continue'+ & $executable @Arguments | Out-Host+ $code = $LASTEXITCODE+ } finally { $ErrorActionPreference = $previousPreference }+ if ($code -ne 0) { throw "$Command failed with exit code $code" }+}++function Install-HermesArm64OpenSSL {+ param([string]$Vcpkg, [string]$Root)+ $prefix = Join-Path $Root 'installed\arm64-windows-static-md'+ $required = @('include\openssl\ssl.h', 'lib\libcrypto.lib', 'lib\libssl.lib')+ $missing = @($required | Where-Object { -not (Test-Path -LiteralPath (Join-Path $prefix $_) -PathType Leaf) })+ if ($missing.Count) {+ Write-Host 'Installing static ARM64 OpenSSL development libraries via vcpkg...'+ Invoke-HermesBuildCommand $Vcpkg @('install', 'openssl:arm64-windows-static-md', '--classic', '--disable-metrics', "--x-install-root=$(Join-Path $Root 'installed')")+ } else {+ Write-Host "ARM64 OpenSSL development libraries found: $prefix"+ }+ foreach ($relative in $required) {+ if (-not (Test-Path -LiteralPath (Join-Path $prefix $relative) -PathType Leaf)) {+ throw "OpenSSL installation is damaged: $prefix\$relative is missing. Repair the openssl:arm64-windows-static-md package in $Root, then rerun setup."+ }+ }+ return $prefix+}++function Get-HermesArm64VisualStudio {+ $vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"+ if (-not (Test-Path -LiteralPath $vswhere)) { return $null }+ $found = & $vswhere -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.ARM64 -property installationPath+ if ($LASTEXITCODE -ne 0) { throw 'Visual Studio discovery failed' }+ return ($found | Select-Object -First 1)+}++function Get-HermesClang {+ param([string]$VisualStudio)+ $command = Get-Command clang.exe -ErrorAction SilentlyContinue+ if ($command) { return $command.Source }+ $candidates = @((Join-Path $env:ProgramFiles 'LLVM\bin\clang.exe'))+ if ($VisualStudio) {+ $candidates += @(+ (Join-Path $VisualStudio 'VC\Tools\Llvm\ARM64\bin\clang.exe'),+ (Join-Path $VisualStudio 'VC\Tools\Llvm\bin\clang.exe')+ )+ }+ return ($candidates | Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } | Select-Object -First 1)+}++function Initialize-HermesArm64BuildTools {- param([string]$StateRoot)++ param([string]$StateRoot, [string]$OpenSSLRoot)++ if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) {++ throw 'ARM64 build dependencies require Windows.'++ }+ $buildRoot = Join-Path $StateRoot 'build-tools'+ New-Item -ItemType Directory -Force -Path $buildRoot | Out-Null+ $vs = Get-HermesArm64VisualStudio+ $clangPath = Get-HermesClang -VisualStudio $vs+ if (-not $vs -or -not $clangPath) {+ $identity = [Security.Principal.WindowsIdentity]::GetCurrent()+ $principal = New-Object Security.Principal.WindowsPrincipal($identity)+ if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {+ throw 'ARM64 C++ or Clang build tools are missing. Run setup-hermes.ps1 once in an Administrator PowerShell to install them.'+ }+ $installer = Join-Path $buildRoot 'vs-buildtools.exe'+ Invoke-WebRequest -UseBasicParsing 'https://aka.ms/vs/17/release/vs_BuildTools.exe' -OutFile $installer+ $signature = Get-AuthenticodeSignature -LiteralPath $installer+ if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch 'O=Microsoft Corporation(?:,|$)') {+ throw 'Visual Studio installer does not have a valid Microsoft signature'+ }+ $installArgs = @(+ '--quiet', '--wait', '--norestart', '--nocache',+ '--add', 'Microsoft.VisualStudio.Workload.VCTools', '--includeRecommended',+ '--add', 'Microsoft.VisualStudio.Component.VC.Tools.ARM64',+ '--add', 'Microsoft.VisualStudio.Component.VC.Llvm.Clang'+ )+ if ($vs) { $installArgs = @('modify', '--installPath', ('"' + $vs + '"')) + $installArgs }+ $install = Start-Process -FilePath $installer -ArgumentList $installArgs -Wait -PassThru+ if ($install.ExitCode -notin @(0, 3010)) { throw "Visual Studio installation failed: $($install.ExitCode)" }+ $vs = Get-HermesArm64VisualStudio+ if (-not $vs) { throw 'ARM64 C++ build tools remain unavailable. Restart Windows if the installer requested it.' }+ $clangPath = Get-HermesClang -VisualStudio $vs+ if (-not $clangPath) { throw 'The Clang compiler is still missing after Visual Studio setup.' }+ }+ Write-Host "ARM64 C++ build tools found: $vs"+ $devCmd = Join-Path $vs 'Common7\Tools\VsDevCmd.bat'+ # The batch file configures SDK, compiler, and linker paths only for this setup process.+ $startInfo = New-Object System.Diagnostics.ProcessStartInfo+ $startInfo.FileName = $env:ComSpec+ $startInfo.Arguments = "/d /s /c `"`"$devCmd`" -no_logo -arch=arm64 -host_arch=arm64 >nul && set`""+ $startInfo.UseShellExecute = $false+ $startInfo.RedirectStandardOutput = $true+ $process = [System.Diagnostics.Process]::Start($startInfo)+ $lines = $process.StandardOutput.ReadToEnd() -split "`r?`n"+ $process.WaitForExit()+ if ($process.ExitCode -ne 0) { throw 'Could not initialize the ARM64 Visual Studio developer environment' }+ foreach ($line in $lines) {+ if ($line -match '^([^=]+)=(.*)$') { Set-Item -LiteralPath "env:$($matches[1])" -Value $matches[2] }+ }+ if (-not (Get-Command cl.exe -ErrorAction SilentlyContinue)) { throw 'ARM64 C++ compiler is unavailable after environment setup' }+- $cargoBin = Join-Path $HOME '.cargo\bin'++ # Child builds isolate HOME/USERPROFILE. Keep Rust anchored to the homes++ # used here, including caller-selected locations.++ if (-not $env:CARGO_HOME) { $env:CARGO_HOME = Join-Path $HOME '.cargo' }++ if (-not $env:RUSTUP_HOME) { $env:RUSTUP_HOME = Join-Path $HOME '.rustup' }++ $env:CARGO_HOME = [IO.Path]::GetFullPath($env:CARGO_HOME)++ $env:RUSTUP_HOME = [IO.Path]::GetFullPath($env:RUSTUP_HOME)++ $cargoBin = Join-Path $env:CARGO_HOME 'bin'+ $env:PATH = "$cargoBin;$env:PATH"+ $rustup = Get-Command rustup.exe -ErrorAction SilentlyContinue+ if (-not $rustup) {+ $installer = Join-Path $buildRoot 'rustup-init.exe'+ $url = 'https://static.rust-lang.org/rustup/archive/1.28.2/aarch64-pc-windows-msvc/rustup-init.exe'+ Invoke-WebRequest -UseBasicParsing $url -OutFile $installer+ if ((Get-FileHash -Algorithm SHA256 $installer).Hash.ToLowerInvariant() -ne 'de9f7d29ccd39efa59a3dda3ec363b396e09b92681229b9b8f6aaa4c84285e9c') {+ throw 'rustup installer SHA256 mismatch'+ }+ Invoke-HermesBuildCommand $installer @('-y', '--no-modify-path', '--profile', 'minimal', '--default-toolchain', '1.98.0-aarch64-pc-windows-msvc')+ $rustup = Get-Command rustup.exe -ErrorAction Stop+ }+ $rustc = Get-Command rustc.exe -ErrorAction SilentlyContinue+ $rustInfo = if ($rustc) { (& $rustc.Source -vV) -join "`n" } else { '' }+ if ($rustInfo -notmatch 'host: aarch64-pc-windows-msvc') {+ Invoke-HermesBuildCommand $rustup.Source @('toolchain', 'install', '1.98.0-aarch64-pc-windows-msvc', '--profile', 'minimal')+ $env:RUSTUP_TOOLCHAIN = '1.98.0-aarch64-pc-windows-msvc'+ }+ Write-Host 'ARM64 Rust toolchain ready'++ $env:CC_aarch64_pc_windows_msvc = $clangPath+ Write-Host "ARM64 Rust C compiler: $clangPath"++ $vcpkgRoot = $null+ $vcpkgCommand = Get-Command vcpkg.exe -ErrorAction SilentlyContinue+ $candidates = @($env:VCPKG_ROOT, $env:VCPKG_INSTALLATION_ROOT)+ if ($vcpkgCommand) { $candidates += Split-Path $vcpkgCommand.Source }+ $candidates += @((Join-Path $env:SystemDrive 'vcpkg'), (Join-Path $buildRoot 'vcpkg'))+ foreach ($candidate in $candidates) {+ # Visual Studio also ships a manifest-only vcpkg without a ports tree.+ if ($candidate -and (Test-Path -LiteralPath (Join-Path $candidate 'vcpkg.exe')) -and+ (Test-Path -LiteralPath (Join-Path $candidate 'ports\openssl\portfile.cmake'))) {+ $vcpkgRoot = $candidate+ break+ }+ }+ if (-not $vcpkgRoot) {+ $vcpkgRoot = Join-Path $buildRoot 'vcpkg'+ if (-not (Test-Path -LiteralPath (Join-Path $vcpkgRoot '.git'))) {+ Invoke-HermesBuildCommand 'git' @('clone', 'https://github.com/microsoft/vcpkg.git', $vcpkgRoot)+ Invoke-HermesBuildCommand 'git' @('-C', $vcpkgRoot, 'checkout', '--detach', '00c5775211f45cd08b37fce0484b4cb940e422ab')+ }+ Invoke-HermesBuildCommand (Join-Path $vcpkgRoot 'bootstrap-vcpkg.bat') @('-disableMetrics')+ }+ $env:VCPKG_ROOT = $vcpkgRoot- $env:OPENSSL_DIR = Install-HermesArm64OpenSSL -Vcpkg (Join-Path $vcpkgRoot 'vcpkg.exe') -Root $vcpkgRoot++ # The install tree can be cached independently of the discovered checkout.++ if (-not $OpenSSLRoot) { $OpenSSLRoot = $vcpkgRoot }++ $env:OPENSSL_DIR = Install-HermesArm64OpenSSL -Vcpkg (Join-Path $vcpkgRoot 'vcpkg.exe') -Root $OpenSSLRoot+ $env:OPENSSL_STATIC = '1'+}diff --cc tests/pm/test_windows_build_deps.pyindex 5758c9a8b56,00000000000..622e10d3a4fmode 100644,000000..100644--- a/tests/pm/test_windows_build_deps.py+++ b/tests/pm/test_windows_build_deps.py@@@ -1,89 -1,0 +1,264 @@@+"""Native PowerShell prerequisite selection without downloading build tools."""+from pathlib import Path++import json+import os+import shutil+import subprocess++import pytest+++pytestmark = pytest.mark.platforms("windows")+HELPER = Path(__file__).resolve().parents[2] / "scripts" / "windows-build-deps.ps1"++ENTRYPOINT = HELPER.parent / "build" / "windows-deps.ps1"++++++def _powershell(script, *args, env=None):++ env = dict(os.environ) if env is None else env++ env.setdefault("SystemRoot", r"C:\Windows")++ env.setdefault("ComSpec", str(Path(env["SystemRoot"]) / "System32/cmd.exe"))++ env.setdefault("PATHEXT", ".COM;.EXE;.BAT;.CMD")++ env.setdefault("SystemDrive", Path(env["SystemRoot"]).drive)++ shell = shutil.which("powershell") or str(++ Path(env["SystemRoot"]) / "System32/WindowsPowerShell/v1.0/powershell.exe"++ )++ return subprocess.run(++ [shell, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",++ "-File", str(script), *map(str, args)],++ capture_output=True, text=True, encoding="utf-8", errors="replace", env=env, timeout=30,++ )++++++def _github_environment(path):++ lines = iter(path.read_text(encoding="utf-8").splitlines())++ values = {}++ for line in lines:++ name, delimiter = line.split("<<", 1)++ value = []++ for line in lines:++ if line == delimiter:++ break++ value.append(line)++ else:++ raise AssertionError(f"unterminated GitHub environment value: {name}")++ values[name.upper()] = "\n".join(value)++ return values++++++def test_entrypoint_exports_child_environment_and_only_github_deltas(tmp_path):++ """The file protocol preserves Unicode, multiline SDK values and PATH order."""++ entry = tmp_path / "scripts" / "build" / ENTRYPOINT.name++ entry.parent.mkdir(parents=True)++ shutil.copyfile(ENTRYPOINT, entry)++ # Replace only the installer boundary; the wrapper runs as a real child.++ (entry.parent.parent / HELPER.name).write_text(r'''++function Initialize-HermesArm64BuildTools {++ param([string]$StateRoot, [string]$OpenSSLRoot)++ if (-not $StateRoot -or -not $OpenSSLRoot) { throw 'missing build roots' }++ if ($env:FAIL_BUILD_SETUP) { throw 'fixture installer failed' }++ $env:INCLUDE = 'sdk include ' + [char]0x03bb + "`nsecond line=with equals"++ $env:LIB = Join-Path $StateRoot 'sdk lib'++ $env:WindowsSdkDir = Join-Path $StateRoot 'SDK'++ $env:OPENSSL_DIR = Join-Path $OpenSSLRoot 'installed\arm64-windows-static-md'++ $env:OPENSSL_STATIC = '1'++ $env:CC_aarch64_pc_windows_msvc = Join-Path $StateRoot 'clang.exe'++ $env:PATH = (Join-Path $StateRoot 'cargo bin') + ';' + (Join-Path $StateRoot 'compiler bin') + ';' + $env:PATH++ $env:GITHUB_FIXTURE = 'must not be published'++ $env:RUNNER_FIXTURE = 'must not be published'++ $env:NODE_OPTIONS = 'must not be published'++}++''', encoding="utf-8")++ env = dict(os.environ)++ env.update(CARGO_HOME=str(tmp_path / "caller cargo"), RUSTUP_HOME=str(tmp_path / "caller rustup"),++ RUSTUP_TOOLCHAIN="caller-toolchain", UNCHANGED_BUILD_SENTINEL="inherited")++ state = tmp_path / "state with spaces"++ openssl = tmp_path / "common openssl"++ result_file = tmp_path / "environment.json"++ github_env = tmp_path / "github-env"++ github_path = tmp_path / "github-path"++ github_env.write_text("EARLIER_STEP<<end\nkeep\nend\n", encoding="utf-8")++ earlier_path = str(tmp_path / "earlier bin")++ github_path.write_text(earlier_path + "\n", encoding="utf-8")++ result = _powershell(entry, "-StateRoot", state, "-OpenSSLRoot", openssl,++ "-EnvironmentFile", result_file, "-GithubEnv", github_env,++ "-GithubPath", github_path, env=env)++ assert result.returncode == 0, result.stdout + result.stderr++ child = {key.upper(): value for key, value in json.loads(result_file.read_text(encoding="utf-8")).items()}++ assert child["INCLUDE"] == "sdk include λ\nsecond line=with equals"++ assert child["RUSTUP_TOOLCHAIN"] == env["RUSTUP_TOOLCHAIN"]++ published = _github_environment(github_env)++ assert published["EARLIER_STEP"] == "keep"++ for name in ("CARGO_HOME", "RUSTUP_HOME", "LIB", "INCLUDE", "WINDOWSSDKDIR",++ "OPENSSL_DIR", "OPENSSL_STATIC", "CC_AARCH64_PC_WINDOWS_MSVC"):++ assert published[name] == child[name]++ for name in ("CARGO_HOME", "RUSTUP_HOME", "UNCHANGED_BUILD_SENTINEL"):++ assert child[name] == env[name]++ assert "UNCHANGED_BUILD_SENTINEL" not in published++ assert not any(name.startswith(("GITHUB_", "RUNNER_")) for name in published)++ assert "NODE_OPTIONS" not in published++ assert "PATH" not in published++ # Reproduce the runner's per-line prepend; inherited PATH is left intact.++ path_lines = github_path.read_text(encoding="utf-8").splitlines()++ assert path_lines[0] == earlier_path++ inherited_path = next(value for key, value in env.items() if key.upper() == "PATH")++ next_path = inherited_path++ for item in path_lines[1:]:++ next_path = item + ";" + next_path++ assert next_path == child["PATH"]++++ # Without GITHUB_PATH the complete PATH belongs in the env-file instead.++ env_only = tmp_path / "env-only"++ result = _powershell(entry, "-StateRoot", state, "-OpenSSLRoot", openssl,++ "-GithubEnv", env_only, env=env)++ assert result.returncode == 0, result.stdout + result.stderr++ assert _github_environment(env_only)["PATH"] == child["PATH"]++++ failed_file = tmp_path / "failed.json"++ result = _powershell(entry, "-StateRoot", state, "-OpenSSLRoot", openssl,++ "-EnvironmentFile", failed_file, env={**env, "FAIL_BUILD_SETUP": "1"})++ assert result.returncode != 0++ assert "fixture installer failed" in result.stderr++ assert not failed_file.exists()++++[email protected]("rust_homes", ["default", "explicit"])++def test_initializer_preserves_rust_homes_and_shared_openssl_without_downloads(tmp_path, rust_homes):++ """Real cmd.exe imports the SDK; the warm installer never acquires tools."""++ script = tmp_path / "initialize.ps1"++ script.write_text(r'''++param([string]$Helper, [string]$Root, [string]$Homes)++$ErrorActionPreference = 'Stop'++. $Helper++$vs = Join-Path $Root 'VS with spaces'++$devDir = Join-Path $vs 'Common7\Tools'++New-Item -ItemType Directory -Force $devDir | Out-Null++[IO.File]::WriteAllText((Join-Path $devDir 'VsDevCmd.bat'), "@echo off`r`nset INCLUDE=fixture SDK include`r`nset LIB=fixture SDK lib`r`n")++$rustcPath = Join-Path $Root 'rustc.cmd'++[IO.File]::WriteAllText($rustcPath, "@echo off`r`necho host: aarch64-pc-windows-msvc`r`n")++$vcpkg = Join-Path $Root 'vcpkg checkout'++$openssl = Join-Path $Root 'separate shared openssl'++$prefix = Join-Path $openssl 'installed\arm64-windows-static-md'++New-Item -ItemType Directory -Force (Join-Path $vcpkg 'ports\openssl'), (Join-Path $prefix 'lib'), (Join-Path $prefix 'include\openssl') | Out-Null++[IO.File]::WriteAllText((Join-Path $vcpkg 'vcpkg.exe'), 'fixture')++[IO.File]::WriteAllText((Join-Path $vcpkg 'ports\openssl\portfile.cmake'), 'fixture')++foreach ($relative in @('lib\libcrypto.lib', 'lib\libssl.lib', 'include\openssl\ssl.h')) {++ [IO.File]::WriteAllText((Join-Path $prefix $relative), 'fixture')++}++function Get-HermesArm64VisualStudio { return $vs }++function Get-HermesClang { param([string]$VisualStudio); return (Join-Path $vs 'clang.exe') }++function Get-Command {++ param([string]$Name)++ switch ($Name) {++ 'cl.exe' { return [pscustomobject]@{Source = (Join-Path $vs 'cl.exe')} }++ 'rustup.exe' { return [pscustomobject]@{Source = (Join-Path $Root 'rustup.exe')} }++ 'rustc.exe' { return [pscustomobject]@{Source = $rustcPath} }++ 'vcpkg.exe' { return $null }++ default { throw "Unexpected command discovery: $Name" }++ }++}++function Invoke-HermesBuildCommand { throw 'Unexpected installation' }++function Invoke-WebRequest { throw 'Unexpected download' }++Remove-Item Env:VCPKG_ROOT -ErrorAction SilentlyContinue++$env:VCPKG_INSTALLATION_ROOT = $vcpkg++$env:RUSTUP_TOOLCHAIN = 'caller-selected-toolchain'++if ($Homes -eq 'explicit') {++ $cargoHome = Join-Path $Root 'custom cargo'++ $rustupHome = Join-Path $Root 'custom rustup'++ $env:CARGO_HOME = $cargoHome++ $env:RUSTUP_HOME = $rustupHome++} else {++ Remove-Item Env:CARGO_HOME, Env:RUSTUP_HOME -ErrorAction SilentlyContinue++ $cargoHome = Join-Path $HOME '.cargo'++ $rustupHome = Join-Path $HOME '.rustup'++}++$inheritedPath = $env:PATH++Initialize-HermesArm64BuildTools -StateRoot $Root -OpenSSLRoot $openssl++if ($env:CARGO_HOME -ne $cargoHome -or $env:RUSTUP_HOME -ne $rustupHome) { throw 'Rust homes lost' }++if ($env:RUSTUP_TOOLCHAIN -ne 'caller-selected-toolchain') { throw 'Caller Rust toolchain lost' }++if ($env:PATH -ne ((Join-Path $cargoHome 'bin') + ';' + $inheritedPath)) { throw 'PATH lost or reordered' }++if ($env:OPENSSL_DIR -ne $prefix -or $env:OPENSSL_STATIC -ne '1') { throw 'Wrong OpenSSL tree' }++if ($env:INCLUDE -ne 'fixture SDK include' -or $env:LIB -ne 'fixture SDK lib') { throw 'SDK environment lost' }++if ($env:CC_aarch64_pc_windows_msvc -ne (Join-Path $vs 'clang.exe')) { throw 'Compiler lost' }++Write-Output 'PASS'++''', encoding="utf-8")++ result = _powershell(script, HELPER, tmp_path, rust_homes)++ assert result.returncode == 0, result.stdout + result.stderr++ assert "PASS" in result.stdout+++def test_openssl_installs_once_and_rejects_damaged_shared_install(tmp_path):+ script = tmp_path / "check.ps1"+ script.write_text(r'''+param([string]$Helper, [string]$Root)+$ErrorActionPreference = 'Stop'+. $Helper+$prefix = Join-Path $Root 'installed\arm64-windows-static-md'+function Invoke-HermesBuildCommand {+ param([string]$Command, [string[]]$Arguments)+ if ($Arguments[0] -ne 'install' -or $Arguments[1] -ne 'openssl:arm64-windows-static-md') {+ throw 'incorrect installation request'+ }+ if ($Arguments -notcontains '--classic') { throw 'manifest mode was not disabled' }+ $script:calls += 1+ if ($script:calls -gt 1) { return } # vcpkg trusts its installed database on subsequent requests.+ New-Item -ItemType Directory -Force (Join-Path $prefix 'lib'), (Join-Path $prefix 'include\openssl') | Out-Null+ foreach ($relative in @('lib\libcrypto.lib', 'lib\libssl.lib', 'include\openssl\ssl.h')) {+ [IO.File]::WriteAllText((Join-Path $prefix $relative), 'fixture')+ }+}+$calls = 0+$first = Install-HermesArm64OpenSSL -Vcpkg 'fixture-vcpkg' -Root $Root+$second = Install-HermesArm64OpenSSL -Vcpkg 'fixture-vcpkg' -Root $Root+if ($calls -ne 1 -or $first -ne $prefix -or $second -ne $prefix) { throw 'warm setup installed twice' }+Remove-Item (Join-Path $prefix 'include\openssl\ssl.h')+$rejected = $false+try { Install-HermesArm64OpenSSL -Vcpkg 'fixture-vcpkg' -Root $Root } catch {+ if ($_.Exception.Message -notmatch 'installation is damaged') { throw }+ $rejected = $true+}+if (-not $rejected -or $calls -ne 2) { throw 'damaged install was accepted' }+Write-Output 'PASS'+''', encoding="utf-8")+ env = dict(os.environ)+ env.setdefault("SystemRoot", r"C:\Windows")+ shell = shutil.which("powershell") or str(Path(env["SystemRoot"]) / "System32/WindowsPowerShell/v1.0/powershell.exe")+ result = subprocess.run(+ [shell, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", str(script), str(HELPER), str(tmp_path)],+ capture_output=True, text=True, encoding="utf-8", errors="replace", env=env, timeout=30,+ )+ assert result.returncode == 0, result.stdout + result.stderr+ assert "PASS" in result.stdout+++def test_native_build_command_preserves_failures_and_spaces(tmp_path):+ script = tmp_path / "native.ps1"+ script.write_text(r'''+param([string]$Helper, [string]$Root)+$ErrorActionPreference = 'Stop'+. $Helper+$command = Join-Path $Root 'child with spaces.cmd'+[IO.File]::WriteAllText($command, "@echo off`r`necho native-progress 1>&2`r`nexit /b 19`r`n")+$failed = $false+try { Invoke-HermesBuildCommand $command @() } catch {+ if ($_.Exception.Message -notmatch 'exit code 19') { throw }+ $failed = $true+}+if (-not $failed -or $ErrorActionPreference -ne 'Stop') { throw 'failure or shell preference was lost' }+[IO.File]::WriteAllText($command, "@echo off`r`necho native-progress 1>&2`r`nexit /b 0`r`n")+Invoke-HermesBuildCommand $command @()+$failed = $false+try { Invoke-HermesBuildCommand (Join-Path $Root 'absent.exe') @() } catch { $failed = $true }+if (-not $failed) { throw 'missing executable was accepted after a successful command' }+Write-Output 'PASS'+''', encoding="utf-8")+ env = dict(os.environ)+ env.setdefault("SystemRoot", r"C:\Windows")+ env.setdefault("ComSpec", str(Path(env["SystemRoot"]) / "System32/cmd.exe"))+ env.setdefault("PATHEXT", ".COM;.EXE;.BAT;.CMD")+ shell = shutil.which("powershell") or str(Path(env["SystemRoot"]) / "System32/WindowsPowerShell/v1.0/powershell.exe")+ result = subprocess.run(+ [shell, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", str(script), str(HELPER), str(tmp_path)],+ capture_output=True, text=True, encoding="utf-8", errors="replace", env=env, timeout=30,+ )+ assert result.returncode == 0, result.stdout + result.stderr+ assert "PASS" in result.stdoutdiff --cc tests/pm/test_workspace_output_encoding.pyindex 52d79340c81,00000000000..f5ba05cc552mode 100644,000000..100644--- a/tests/pm/test_workspace_output_encoding.py+++ b/tests/pm/test_workspace_output_encoding.py@@@ -1,97 -1,0 +1,98 @@@+"""Captured package-tool output must not depend on the host's ANSI code page."""++import importlib+import locale+import os+import subprocess+import sys++import pytest++import pm.workspace as ws+from pm.package import InstallError+++def legacy_locale_child(monkeypatch):+ # The canonical runner enables UTF-8 mode. Pin only subprocess's default+ # encoding seam to a legacy locale; keep the real host and pipe I/O.+ monkeypatch.setattr(locale, "getencoding", lambda: "cp1252")+ monkeypatch.setattr(subprocess, "_text_encoding", locale.getencoding)+ real_run = subprocess.run++ def run(*, stdout=b"", stderr=b"", returncode=0, **kwargs):+ script = (+ "import sys; "+ f"sys.stdout.buffer.write({stdout!r}); "+ f"sys.stderr.buffer.write({stderr!r}); "+ f"sys.exit({returncode})"+ )+ return real_run([sys.executable, "-c", script], **kwargs)++ return run++[email protected]("stage", ["lock", "sync"])[email protected]("stream", ["stdout", "stderr"])[email protected]("suffix", [b"", b"\xff"], ids=["utf8", "invalid-byte"])+def test_uv_failure_retains_utf8_build_diagnostic(+ tmp_path, monkeypatch, legacy_locale_child, stage, stream, suffix+):+ diagnostic = "🔍 cryptography: OpenSSL headers not found"+ raw = diagnostic.encode("utf-8") + suffix + b"\n"+ expected = diagnostic + ("�" if suffix else "")+ monkeypatch.setattr(ws, "_generate_pyproject", lambda *a, **k: (tmp_path, False))+ monkeypatch.setattr(+ importlib.import_module("pm.ensure"), "uv",- lambda **kwargs: (sys.executable, dict(os.environ)),++ lambda **kwargs: (sys.executable, {**os.environ, "UV_PYTHON": sys.executable,++ "UV_CACHE_DIR": str(tmp_path / "cache")}),+ )+ completed = []++ def run_uv(cmd, **kwargs):+ # Successful lock output must also be decoded before sync can run.+ output = {stream: raw} if cmd[1] == stage else {"stdout": raw, "stderr": raw}+ result = legacy_locale_child(+ **output, returncode=17 if cmd[1] == stage else 0, **kwargs+ )+ completed.append(result)+ return result++ monkeypatch.setattr(ws.subprocess, "run", run_uv)+ with pytest.raises(InstallError) as excinfo:+ ws.lock_and_sync([], venv_dir=tmp_path / "venv", root=tmp_path)++ assert type(excinfo.value) is InstallError # A build error is not a resolver conflict.+ assert excinfo.value.cause == f"uv {stage} exited 17: {expected}"+ assert getattr(completed[-1], stream) == expected + "\n"++[email protected]("install_cmd", ["ci", "install"])[email protected]("stream", ["stdout", "stderr"])[email protected]("returncode", [0, 17])+def test_node_sidecar_retains_output_and_exit_status(+ tmp_path, monkeypatch, legacy_locale_child, install_cmd, stream, returncode+):+ (tmp_path / "package.json").write_text("{}", encoding="utf-8")+ if install_cmd == "ci":+ (tmp_path / "package-lock.json").write_text("{}", encoding="utf-8")+ monkeypatch.setattr(+ importlib.import_module("pm.ensure"), "lazy_installs_allowed", lambda: True+ )+ diagnostic = "🔍 node-gyp: build toolchain unavailable"+ raw = diagnostic.encode("utf-8") + b"\xff\n"+ completed = []++ def run_npm(cmd, **kwargs):+ result = legacy_locale_child(**{stream: raw}, returncode=returncode, **kwargs)+ completed.append(result)+ return result++ error = ws.install_node_sidecar(tmp_path, npm_bin=sys.executable, runner=run_npm)++ expected = diagnostic + "�"+ if returncode:+ assert error == f"npm {install_cmd} exited {returncode}: {expected}"+ else:+ assert error is None+ assert getattr(completed[-1], stream) == expected + "\n"diff --cc tests/scripts/test_bundle_native.pyindex f72c570ab83,c4362ef0913..2242294e9c1--- a/tests/scripts/test_bundle_native.py+++ b/tests/scripts/test_bundle_native.py@@@ -64,28 -70,31 +70,32 @@@ def test_bundle_stages_git_tree_and_runmarker = json.loads((output / "pm-runtime/pm-runtime.json").read_text())assert (output / "pm-runtime" / marker["python"]).resolve() == target_pythonassert (output / "pm-runtime" / marker["sitePackages"]).is_dir()- result = real_run(argv, cwd=cwd, env=env)- if argv[1] == "sync" and result[0] == 0:- site = site_packages(output / "venv")- if fail_inventory:- shutil.rmtree(site)- else:- package = site / "bundle_probe"- package.mkdir()- (package / "__init__.py").write_text(- "import json, pathlib, sys\n"- f"pathlib.Path({str(witness)!r}).write_text(json.dumps(sys.executable), encoding='utf-8')\n",- encoding="utf-8",- )- (package / "present.py").write_text("", encoding="utf-8")+ result = real_build(**kwargs)+ site = site_packages(output / "venv")+ if fail_inventory:+ shutil.rmtree(site)+ else:+ package = site / "bundle_probe"+ package.mkdir()+ (package / "__init__.py").write_text(+ "import json, pathlib, sys\n"+ f"pathlib.Path({str(witness)!r}).write_text(json.dumps(sys.executable), encoding='utf-8')\n",+ encoding="utf-8",+ )+ (package / "present.py").write_text("", encoding="utf-8")return result- monkeypatch.setattr(native, "_run_live", child)+ monkeypatch.setattr(python_env, "build_python_environment", build)monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "original"))- assert native.stage_native(SimpleNamespace(out=str(output), ref="HEAD")) == 0- assert calls == ["venv", "sync"]+ monkeypatch.setenv("UV_CACHE_DIR", str(tmp_path / "cache"))+ assert native._stage_native(SimpleNamespace(out=str(output), ref="HEAD")) == 0+ assert calls[0]["all_extras"] is True++ assert calls[0]["cache"] == tmp_path / "cache"assert (output / "hermes-agent/pyproject.toml").is_file()- assert json.loads((output / "manifest.json").read_text())["repo"] == "hermes-agent"+ manifest = json.loads((output / "manifest.json").read_text())+ assert manifest["repo"] == "hermes-agent"+ command = "bin/probe.exe" if os.name == "nt" else "bin/probe"+ assert manifest["runtime"]["commands"] == {"probe": command}feature_file = output / "enabled-features.json"assert json.loads(feature_file.read_text(encoding="utf-8"))["extras"] == ["payloadtest"]assert Path(json.loads(witness.read_text(encoding="utf-8"))) == target_python@@@ -163,3 -183,16 +184,49 @@@ def test_staged_cache_installs_built_whcapture_output=True, text=True, check=True, timeout=30,)assert probe.stdout.strip() == "installed from cached wheel"+++ def test_native_dispatch_isolates_process_state_on_real_child_failure(tmp_path, monkeypatch):++ # Compiler provisioning has its own native test; this probe must stop++ # at the invalid revision without installing tools on a developer host.++ monkeypatch.setattr("scripts.build.windows_deps.prepare_windows_environment", lambda **kwargs: dict(kwargs["env"]))+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "user-home"))+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "user-tools"))+ before = dict(os.environ)+ out = tmp_path / "output"+ assert native.stage_native(SimpleNamespace(out=str(out), ref="missing-build-test-ref")) != 0+ assert dict(os.environ) == before+ assert not (tmp_path / "user-home").exists()+ assert not (tmp_path / "user-tools").exists()+ assert not (out / "manifest.json").exists()+ assert not list(out.glob(".build-*"))++++++def test_native_dispatch_keeps_cache_across_failed_children(tmp_path, monkeypatch):++ monkeypatch.setattr("scripts.build.windows_deps.prepare_windows_environment", lambda **kwargs: dict(kwargs["env"]))++ out = tmp_path / "payload"++ cache = tmp_path / "persistent-cache"++ monkeypatch.setenv("UV_CACHE_DIR", str(tmp_path / "ambient-cache"))++ original = dict(os.environ)++ run = subprocess.run++ attempts = []++++ def child(command, *, cwd, env):++ assert command[command.index("-m") + 1] == "scripts.bundles.native"++ assert Path(env["UV_CACHE_DIR"]) == cache++ attempts.append(Path(env["HOME"]))++ # Run a real child using the actual dispatch environment. Its cache++ # write must survive the failing process and temporary-HOME cleanup.++ return run([sys.executable, "-c",++ "import os,sys; from pathlib import Path; "++ "p=Path(os.environ['UV_CACHE_DIR']); p.mkdir(exist_ok=True); "++ "f=p/'reused'; f.write_text(f.read_text()+'x' if f.exists() else 'x'); sys.exit(17)"],++ cwd=cwd, env=env)++++ monkeypatch.setattr(native.subprocess, "run", child)++ for _ in range(2):++ assert native.stage_native(SimpleNamespace(out=out, ref="HEAD", cache=cache)) == 17++ assert (cache / "reused").read_text() == "xx"++ assert all(not home.exists() for home in attempts)++ assert not (tmp_path / "ambient-cache").exists()++ assert dict(os.environ) == originaldiff --cc tests/scripts/test_commit_bundle_entrypoints.pyindex 5b95cea9b5b,62ffbad20b8..d7047ab0c94--- a/tests/scripts/test_commit_bundle_entrypoints.py+++ b/tests/scripts/test_commit_bundle_entrypoints.py@@@ -25,6 -25,6 +25,7 @@@ def test_desktop_build_reaches_the_manamonkeypatch.setenv("BUILD_NUMBER", "123")monkeypatch.setattr(desktop.shutil, "which", lambda name: 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_targettarget_arch = current_target().split("-")[1]def capture(argv, cwd):diff --cc tests/scripts/test_pm_runtime_bundle.pyindex 4e6dbe1e69f,32ce253cb5c..334b0f5db33--- a/tests/scripts/test_pm_runtime_bundle.py+++ b/tests/scripts/test_pm_runtime_bundle.py@@@ -35,8 -35,8 +35,11 @@@ def _exercise_relocated_pm_runtime(tmp_shutil.copy2(Path(sys._base_executable).resolve(), python)stage = getattr(native, "stage_pm_runtime", None)assert callable(stage), "native payload has no isolated PM runtime stage"-- stage(root, Path(uv), python, repo)-- stage(root, Path(uv), python, repo, offline=True)++ cache = tmp_path / "build-cache"++ stage(root, Path(uv), 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)(root / "manifest.json").write_text(json.dumps({"repo": "hermes-agent"}))assert not (repo / ".venv").exists()moved = tmp_path / "installed elsewhere"@@@ -133,7 -136,7 +139,11 @@@ def test_native_stage_builds_pm_before_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"))-- def staged(root, uv, python, repo):++ cache_dir = tmp_path / "cache"++ monkeypatch.setenv("UV_CACHE_DIR", str(cache_dir))++++ def staged(root, uv, python, repo, *, cache):++ assert cache == cache_dircalls.append((root, uv, python, repo))raise StopAfterPM