Skip to content

The agent that grows with you

refactor(activate): split interactive activation from running a command in the env

ethernetb4d5092d3fd5
diff --git a/AGENTS.md b/AGENTS.md
index 951b3abc9d9..d563e2473f4 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -202,7 +202,8 @@ source ./activate # provisions/syncs PM tools + dependencies, then activates
```
Select an isolated development `HERMES_HOME` and `HERMES_RUNTIME_DIR` first;
see `website/docs/reference/package-management.md#developer-workflow`.
-PowerShell: `. .\activate.ps1`. `deactivate` restores the prior environment.
+PowerShell: `. .\activate.ps1`. `deactivate` restores the prior
+environment. Non-interactive callers run under `scripts/run-in-hermes-env CMD...` instead of sourcing.
For tests, use the independent test environment in `CONTRIBUTING.md` (or Nix);
PM activation's `PYTHONPATH` does not survive the test runner's environment scrub.
`scripts/run_tests.sh` probes `.venv`, then `venv`, then `$HOME/.hermes/hermes-agent/venv`
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 23da815b0e2..37613a9ca94 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -150,6 +150,9 @@ syncs tools and Python dependencies before adding them to the shell. It does not
install JS workspaces or rewrite launchers and shell configuration. `deactivate`
restores the prior shell environment and removes the function.
+To run one command in the environment without activating a shell, use
+`scripts/run-in-hermes-env CMD...`.
+
### Manual development and test environment
Use the [PM developer workflow](website/docs/reference/package-management.md#developer-workflow) to prepare Python 3.14 (`>=3.14,<3.15`) first.
diff --git a/activate b/activate
index ce5a7938b4c..fb2bfdf2413 100755
--- a/activate
+++ b/activate
@@ -1,17 +1,20 @@
#!/usr/bin/env bash
# ============================================================================
-# venv-style activation for the Hermes dev environment (pm-managed tools).
+# venv-style activation of the Hermes dev environment for an interactive shell.
#
# source ./activate (bash / zsh, repo root)
# .\activate.ps1 (PowerShell)
#
-# Emits the composed pm env (PATH + tool vars) into the CURRENT shell, with
+# Applies the composed pm env (PATH + tool vars) to the CURRENT shell, with
# save/restore: `deactivate` undoes exactly what activation changed.
#
# `hermes` becomes a shell function for this checkout. It runs only while the
# shell is inside this worktree and refuses outside it, so a sibling worktree
# keeps its own command. A prompt prefix names the worktree.
#
+# Scripts and other processes do not source this: they run under
+# `scripts/run-in-hermes-env`. Both build on scripts/_activation.sh.
+#
# Sync through setup before selecting the environment. PM owns freshness;
# activation does not maintain a second dependency stamp. It trusts the
# recorded tool digest instead of re-hashing every entry. `hermes pm
@@ -42,17 +45,17 @@ if [ -n "$_hermes_expect_extras" ]; then
unset _hermes_arg _hermes_test_env _hermes_expect_extras
return 2 2>/dev/null || exit 2
fi
-# Setup runs in a child: failures must not exit or partially activate the
-# caller's shell, and activation must not republish launchers or shell config.
-if ! (
- unset PYTHONHOME PYTHONPATH VIRTUAL_ENV
- bash "$_HERMES_REPO/setup-hermes.sh" --runtime-only "$_hermes_test_env"
-) >&2; then
+unset _hermes_arg _hermes_expect_extras
+
+# shellcheck source=scripts/_activation.sh
+. "$_HERMES_REPO/scripts/_activation.sh"
+
+if ! hermes_sync "$_HERMES_REPO" "$_hermes_test_env"; then
printf '%s\n' 'activate: setup failed; shell environment unchanged' >&2
- unset _hermes_arg _hermes_test_env _hermes_expect_extras
+ unset _hermes_test_env
return 1 2>/dev/null || exit 1
fi
-unset _hermes_arg _hermes_test_env _hermes_expect_extras
+unset _hermes_test_env
# Guard against double-sourcing: venv activate precedent (re-activating is a
# no-op re-save; we keep it idempotent by deactivating first). Key on the
@@ -62,38 +65,12 @@ if [ "$(type -t deactivate 2>/dev/null)" = "function" ]; then
deactivate
fi
-# Bootstrap Python only emits the environment; it does not install anything.
-_hermes_repo="$_HERMES_REPO"
-_hermes_py=""
-for _hermes_candidate in "$_hermes_repo/.venv/bin/python" "$_hermes_repo/.venv/Scripts/python.exe" \
- "$_hermes_repo/venv/bin/python" "$_hermes_repo/venv/Scripts/python.exe"; do
- [ -x "$_hermes_candidate" ] && { _hermes_py="$_hermes_candidate"; break; }
-done
-if [ -z "$_hermes_py" ]; then
- for _hermes_store in "${HERMES_RUNTIME_DIR:-}" "$_hermes_repo/../tools" "${HERMES_HOME:-$HOME/.hermes}/tools"; do
- [ -n "$_hermes_store" ] || continue
- for _hermes_candidate in "$_hermes_store"/python-*/bin/python3 "$_hermes_store"/python-*/python.exe "$_hermes_store"/python-*/bin/python "$_hermes_store"/python-*/bin/python.exe; do
- [ -x "$_hermes_candidate" ] && { _hermes_py="$_hermes_candidate"; break; }
- done
- [ -n "$_hermes_py" ] && break
- done
-fi
-if [ -z "$_hermes_py" ]; then
- echo "activate: no bootstrap Python found; run setup-hermes.sh" >&2
- return 1 2>/dev/null || exit 1
-fi
-
-# --- emit export lines from `pm env` ---
-_hermes_json="$(PYTHONHOME= PYTHONPATH="$_hermes_repo" "$_hermes_py" -m pm.environments)"
-if [ -z "$_hermes_json" ] || [ "${_hermes_json#*{}" = "$_hermes_json" ]; then
- echo "activate: could not read pm env (run ./setup-hermes.sh first)" >&2
- unset _hermes_repo _hermes_os _hermes_arch _hermes_target _hermes_store _hermes_py _hermes_json
+_hermes_script="$(hermes_compose_env "$_HERMES_REPO")" || {
+ echo "activate: could not compose the environment (see above)" >&2
+ unset _hermes_script
return 1 2>/dev/null || exit 1
-fi
-
-_hermes_keys="$(printf '%s' "$_hermes_json" | "$_hermes_py" -c 'import json,sys; print(" ".join(json.load(sys.stdin)))' \
- | tr ' ' '\n' | grep -E '^[A-Za-z_][A-Za-z0-9_]*$' | tr '\n' ' ')"
-[ -n "$_hermes_keys" ] || _hermes_keys="PATH"
+}
+_hermes_keys="$(printf '%s\n' "$_hermes_script" | sed -n 's/^export \([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p' | tr '\n' ' ')"
# --- snapshot what we are about to change (deactivate restores this) ---
# __HERMES_ACTIVATED is part of the composed env below (it carries the
@@ -104,38 +81,15 @@ for _hermes_k in $_hermes_keys; do
eval "__HERMES_SAVED_$_hermes_k=\"\${$_hermes_k+set}\""
eval "__HERMES_PRIOR_$_hermes_k=\${$_hermes_k-__HERMES_UNSET__}"
done
-
-# Resolved before the export below replaces PATH.
-_hermes_cygpath="$(command -v cygpath 2>/dev/null || :)"
-
-eval "$(printf '%s' "$_hermes_json" | "$_hermes_py" -c '
-import json, sys, shlex, re
-for k, v in json.load(sys.stdin).items():
- # Windows carries names like ProgramFiles(ARM) that are not valid
- # bash identifiers — skip them (they pass through untouched).
- if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", k):
- continue
- print("export %s=%s" % (k, shlex.quote(str(v))))')"
-
-# The MSYS/Cygwin runtime hands a native Windows Python these variables in
-# Windows form (`C:\a;C:\b`) and converts them back only for its own children.
-# Exported verbatim, bash splits PATH on ':' and finds no commands.
-if [ -n "$_hermes_cygpath" ]; then
- PATH="$("$_hermes_cygpath" -u -p "$PATH")"
- for _hermes_k in HOME TMPDIR TMP TEMP; do
- if [ -n "${!_hermes_k-}" ]; then
- printf -v "$_hermes_k" '%s' "$("$_hermes_cygpath" -u "${!_hermes_k}")"
- fi
- done
-fi
+hermes_apply_env "$_hermes_script"
# This checkout, not whichever `hermes` PATH finds. A function beats PATH, an
# alias, and a hashed command, including the MSIX execution alias.
-__HERMES_WORKTREE="$_hermes_repo"
+__HERMES_WORKTREE="$_HERMES_REPO"
# The branch names the worktree. A checkout cannot share a branch with another.
-__HERMES_WORKTREE_NAME="$(git -C "$_hermes_repo" rev-parse --abbrev-ref HEAD 2>/dev/null || :)"
+__HERMES_WORKTREE_NAME="$(git -C "$_HERMES_REPO" rev-parse --abbrev-ref HEAD 2>/dev/null || :)"
if [ -z "$__HERMES_WORKTREE_NAME" ] || [ "$__HERMES_WORKTREE_NAME" = HEAD ]; then
- __HERMES_WORKTREE_NAME="$(basename "$_hermes_repo")"
+ __HERMES_WORKTREE_NAME="$(basename "$_HERMES_REPO")"
fi
__HERMES_SAVED_PS1="${PS1-__HERMES_UNSET__}"
__HERMES_SAVED_PROMPT_COMMAND="${PROMPT_COMMAND-__HERMES_UNSET__}"
@@ -220,6 +174,7 @@ deactivate() {
# remember the key list for deactivate (kept out of the loop vars above)
__HERMES_KEY_LIST="$_hermes_keys"
-unset _hermes_repo _hermes_os _hermes_arch _hermes_target _hermes_store \
- _hermes_py _hermes_json _hermes_keys _hermes_k _hermes_entry _hermes_venvpy \
- _hermes_winarch _hermes_top _hermes_cygpath
+# The composition library is not part of the user's shell.
+unset -f hermes_sync hermes_bootstrap_python hermes_compose_env hermes_apply_env \
+ hermes_activation_current hermes_ensure_env
+unset _HERMES_REPO _hermes_script _hermes_keys _hermes_k _hermes_top
diff --git a/pm/environments.py b/pm/environments.py
index 85ff4801601..401c18f6176 100644
--- a/pm/environments.py
+++ b/pm/environments.py
@@ -6,9 +6,12 @@ any dependency from that environment has been imported.
"""
from __future__ import annotations
+import argparse
import hashlib
import json
import os
+import re
+import shlex
from pathlib import Path
from hermes_constants import get_default_hermes_root, project_venv_dir
@@ -50,13 +53,13 @@ def runtime_facts_path(project_root: Path) -> Path:
return install_state_dir(project_root) / "facts.json"
-# The files that decide the dependency set. `scripts/_hermes-python` re-activates
+# The files that decide the dependency set. `scripts/run-in-hermes-env` re-syncs
# when any of them differs in mtime from its stamp under activation_inputs_dir.
ACTIVATION_INPUTS = ("uv.lock", "pyproject.toml", "pm/lock.json")
def activation_inputs_dir(project_root: Path) -> Path:
- """Beside facts.json, so the prologue finds it from ``$__HERMES_ACTIVATED``."""
+ """Beside facts.json, so the runner finds it from ``$__HERMES_ACTIVATED``."""
return install_state_dir(project_root) / "inputs"
@@ -72,7 +75,7 @@ def record_activation_inputs(stamps: Path, mtimes: dict[str, int], project_root:
Recorded on every successful install, including no-op syncs: a checkout that
rewrites an input without changing it moves the mtime, and only this record
- brings the stamp back to equal. The prologue compares for equality, not order,
+ brings the stamp back to equal. The runner compares for equality, not order,
because switching branches can move an input's mtime in either direction.
"""
import shutil
@@ -380,7 +383,7 @@ def activation_environment(project_root: Path) -> dict[str, str]:
# environment was composed against, so a consumer learns that it inherited
# an activated shell and which checkout/profile that shell came from. Its
# directory also holds activation_inputs_dir, the input-mtime stamps
- # `scripts/_hermes-python` compares against to decide staleness.
+ # `scripts/_activation.sh` compares against to decide staleness.
env["__HERMES_ACTIVATED"] = str(runtime_facts_path(project_root))
# The suite's interpreter (pm.testenv): an isolated side environment, so it
# never appears on PYTHONPATH/PATH above. scripts/run_tests.sh reads it.
@@ -392,5 +395,26 @@ def activation_environment(project_root: Path) -> dict[str, str]:
return env
+_SHELL_IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
+
+
+def shell_exports(env: dict[str, str]) -> str:
+ """The composed environment as a POSIX shell script.
+
+ Windows carries names like ``ProgramFiles(ARM)`` that no shell can assign;
+ they pass through untouched instead of failing the whole script.
+ """
+ return "\n".join(f"export {name}={shlex.quote(str(value))}" for name, value in env.items()
+ if _SHELL_IDENTIFIER.fullmatch(name))
+
+
+def main(argv: list[str] | None = None) -> None:
+ parser = argparse.ArgumentParser(description="Print the composed activation environment.")
+ parser.add_argument("--format", choices=["json", "sh"], default="json")
+ options = parser.parse_args(argv)
+ env = activation_environment(Path(__file__).resolve().parents[1])
+ print(json.dumps(env) if options.format == "json" else shell_exports(env))
+
+
if __name__ == "__main__":
- print(json.dumps(activation_environment(Path(__file__).resolve().parents[1])))
+ main()
diff --git a/scripts/_activation.py b/scripts/_activation.py
index 9abda84ae26..c794e48862f 100644
--- a/scripts/_activation.py
+++ b/scripts/_activation.py
@@ -21,34 +21,11 @@ load before the environment it checks for exists.
Activating from the shebang
---------------------------
-A POSIX script can activate for itself, so ``./scripts/foo.py`` works from any
-cwd with no manual ``source``. The shebang points at ``scripts/_hermes-python``,
-a real repo script that sources ``activate`` and execs the interpreter on the
-same file::
-
- #!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/_hermes-python" "$0" "$@"'
-
-The kernel appends the invoking script as the last argument, and ``bash -c``
-binds it to ``$0`` — so the prologue finds the target relative to itself and
-the shebang stays independent of the cwd. ``$BASH`` for the second hop keeps it
-free of both the exec bit and a ``PATH`` lookup.
-
-Activation is not re-run when the inherited environment is still current. pm
-records one stamp per dependency input (``uv.lock``, ``pyproject.toml``,
-``pm/lock.json``) beside the installed-state file that ``__HERMES_ACTIVATED``
-names, each carrying the exact mtime that input had when the install was last
-verified against it (``pm.environments.record_activation_inputs``). The
-prologue re-activates when any input's mtime *differs* from its stamp: newer
-or older, since switching branches can move it either way. ``[ -nt ]`` and
-``[ -ot ]`` are bash builtins, so the check costs no process spawn. Every
-successful activation records again, including no-op syncs, so a checkout that
-touches an input without changing it costs one re-activation and then settles.
-
-Two constraints worth knowing: the line is 83 bytes (a shebang must stay under
-127), and ``/usr/bin/env -S`` is GNU and newer-BSD — verify it if an older
-macOS or BSD is a target. macOS's stock bash 3.2 compares whole seconds, so an
-input rewritten within the same second as its recorded mtime goes unnoticed
-there. Windows keeps using ``python scripts\\foo.py`` with the guard.
+A POSIX script can run itself in the environment, so ``./scripts/foo.py`` works
+from any cwd with no manual ``source``: its shebang hands the file to
+``scripts/run-in-hermes-env`` (the line, staleness rules and portability limits
+are documented there). Windows keeps using ``python scripts\\foo.py`` with the
+guard.
"""
from __future__ import annotations
diff --git a/scripts/_activation.sh b/scripts/_activation.sh
index 6763917ad0d..f00c5224d18 100644
--- a/scripts/_activation.sh
+++ b/scripts/_activation.sh
@@ -1,5 +1,12 @@
-# Sourced, never executed: the activation staleness check shared by
-# scripts/_hermes-python (the shebang prologue) and scripts/run_tests.sh.
+# Sourced, never executed: how a POSIX shell gets the Hermes dev environment.
+# `activate` (interactive, reversible) and `scripts/run-in-hermes-env` (a child
+# process, one-way) both build on it; neither owns any of it.
+#
+# hermes_sync REPO [FLAG] bring the install up to date (setup-hermes.sh)
+# hermes_compose_env REPO print the composed environment as an `sh` script
+# hermes_apply_env SCRIPT evaluate that script into this shell
+# hermes_activation_current REPO is the inherited environment still REPO's?
+# hermes_ensure_env REPO sync, compose and apply unless it is current
#
# pm records, beside the installed-state file named by __HERMES_ACTIVATED, one
# stamp per dependency input carrying the exact mtime that input had when the
@@ -7,9 +14,74 @@
# Any input whose mtime DIFFERS from its stamp (newer or older, since a branch
# switch can move it either way) means the inherited environment may not match
# its inputs. `-nt`/`-ot` are bash builtins, so the check costs no process
-# spawn, and every successful activation re-records, so one re-activation
-# settles it. Missing stamps or inputs, a dangling sentinel or a literal "1"
-# all read as stale.
+# spawn, and every successful sync re-records, so one re-sync settles it.
+# Missing stamps or inputs, a dangling sentinel or a literal "1" all read as
+# stale, and so does an install that did not build the test environment:
+# every environment this library composes includes it.
+
+# hermes_sync REPO [--test-environment[=EXTRAS]]: run setup in a child, so a
+# failure cannot exit or half-change the caller's shell and setup never
+# republishes launchers or shell config. Progress goes to stderr.
+hermes_sync() {
+ local repo="$1" test_environment="${2:---test-environment}"
+ (
+ unset PYTHONHOME PYTHONPATH VIRTUAL_ENV
+ bash "$repo/setup-hermes.sh" --runtime-only "$test_environment"
+ ) >&2
+}
+
+# hermes_bootstrap_python REPO: print the interpreter that can run pm before
+# any dependency is importable. It only emits the environment; it installs nothing.
+hermes_bootstrap_python() {
+ local repo="$1" store candidate
+ for candidate in "$repo/.venv/bin/python" "$repo/.venv/Scripts/python.exe" \
+ "$repo/venv/bin/python" "$repo/venv/Scripts/python.exe"; do
+ [ -x "$candidate" ] && { printf '%s\n' "$candidate"; return 0; }
+ done
+ for store in "${HERMES_RUNTIME_DIR:-}" "$repo/../tools" "${HERMES_HOME:-$HOME/.hermes}/tools"; do
+ [ -n "$store" ] || continue
+ for candidate in "$store"/python-*/bin/python3 "$store"/python-*/python.exe \
+ "$store"/python-*/bin/python "$store"/python-*/bin/python.exe; do
+ [ -x "$candidate" ] && { printf '%s\n' "$candidate"; return 0; }
+ done
+ done
+ return 1
+}
+
+# hermes_compose_env REPO: print the environment of the installed state as an
+# `sh` script.
+hermes_compose_env() {
+ local repo="$1" python script
+ python="$(hermes_bootstrap_python "$repo")" || {
+ echo "no bootstrap Python found; run setup-hermes.sh" >&2
+ return 1
+ }
+ script="$(PYTHONHOME= PYTHONPATH="$repo" "$python" -m pm.environments --format sh)" &&
+ [ -n "$script" ] || {
+ echo "could not read pm env (run ./setup-hermes.sh first)" >&2
+ return 1
+ }
+ printf '%s\n' "$script"
+}
+
+# hermes_apply_env SCRIPT: evaluate a script from `hermes_compose_env REPO`.
+hermes_apply_env() {
+ # Resolved before the eval replaces PATH.
+ local cygpath name
+ cygpath="$(command -v cygpath 2>/dev/null || :)"
+ eval "$1"
+ # The MSYS/Cygwin runtime hands a native Windows Python these variables in
+ # Windows form (`C:\a;C:\b`) and converts them back only for its own
+ # children. Exported verbatim, bash splits PATH on ':' and finds no commands.
+ if [ -n "$cygpath" ]; then
+ PATH="$("$cygpath" -u -p "$PATH")"
+ for name in HOME TMPDIR TMP TEMP; do
+ if [ -n "${!name-}" ]; then
+ printf -v "$name" '%s' "$("$cygpath" -u "${!name}")"
+ fi
+ done
+ fi
+}
# hermes_activation_current REPO: status 0 when the inherited environment
# matches REPO's current inputs.
@@ -19,7 +91,7 @@ hermes_activation_current() {
# activate.ps1 records a Windows path; Git Bash accepts it with slashes.
sentinel="${__HERMES_ACTIVATED//\\//}"
stamps="${sentinel%/*}/inputs"
- [ -f "$stamps/.project-root" ] || return 1
+ [ -f "$stamps/.project-root" ] && [ -f "$stamps/.test-environment" ] || return 1
local owner="$repo" recorded
recorded="$(< "$stamps/.project-root")"
if command -v cygpath >/dev/null 2>&1; then
@@ -40,11 +112,15 @@ hermes_activation_current() {
[ "$stamped" = 1 ]
}
-# hermes_ensure_activated REPO: source REPO/activate unless the inherited
-# environment is current. `--` passes no options: `source` without arguments
-# would hand activate the CALLER's positional parameters.
-hermes_ensure_activated() {
- hermes_activation_current "$1" && return 0
- # shellcheck source=/dev/null
- . "$1/activate" --
+# hermes_ensure_env REPO: leave this shell with REPO's environment, doing
+# nothing when the inherited one is current.
+hermes_ensure_env() {
+ local repo="$1" script
+ hermes_activation_current "$repo" && return 0
+ hermes_sync "$repo" || {
+ echo "setup failed" >&2
+ return 1
+ }
+ script="$(hermes_compose_env "$repo")" || return 1
+ hermes_apply_env "$script"
}
diff --git a/scripts/_hermes-python b/scripts/_hermes-python
deleted file mode 100755
index 45091f68bf1..00000000000
--- a/scripts/_hermes-python
+++ /dev/null
@@ -1,32 +0,0 @@
-#!/usr/bin/env bash
-# Run a repo Python script under the activated Hermes environment.
-#
-# Shebang target for POSIX scripts:
-# #!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/_hermes-python" "$0" "$@"'
-#
-# The kernel appends the invoking script, so `$1` is the Python file to run
-# and `$@` its arguments. Activates when there is no environment to inherit, or
-# when the inherited one no longer matches its inputs (scripts/_activation.sh);
-# then execs the interpreter on the same file, so tracebacks and __file__ point
-# at the real script.
-set -u
-
-target=${1:-}
-if [ -z "$target" ]; then
- printf 'usage: %s <script.py> [args...]\n' "$0" >&2
- exit 2
-fi
-shift
-
-_here="$(cd "$(dirname "$target")" && pwd)"
-while [ "$_here" != / ] && [ ! -f "$_here/activate" ]; do _here="$(dirname "$_here")"; done
-if [ ! -f "$_here/activate" ]; then
- printf '%s: no activate script above %s\n' "$0" "$target" >&2
- exit 1
-fi
-
-# shellcheck source=scripts/_activation.sh
-. "$_here/scripts/_activation.sh"
-hermes_ensure_activated "$_here" || exit 1
-
-exec python3 "$target" "$@"
diff --git a/scripts/build_model_catalog.py b/scripts/build_model_catalog.py
index 2f8ed642fd6..296af286e2d 100755
--- a/scripts/build_model_catalog.py
+++ b/scripts/build_model_catalog.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/_hermes-python" "$0" "$@"'
+#!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/run-in-hermes-env" python3 "$0" "$@"'
"""Build the Hermes Model Catalog — a centralized JSON manifest of curated models.
This script reads the in-repo hardcoded curated lists (``OPENROUTER_MODELS``,
diff --git a/scripts/build_skills_index.py b/scripts/build_skills_index.py
index 8b07329a91f..a26aac24a85 100755
--- a/scripts/build_skills_index.py
+++ b/scripts/build_skills_index.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/_hermes-python" "$0" "$@"'
+#!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/run-in-hermes-env" python3 "$0" "$@"'
"""Build the Hermes Skills Index — a centralized JSON catalog of all skills.
This script crawls every skill source (skills.sh, GitHub taps, official,
diff --git a/scripts/dump_desktop_slash_registry.py b/scripts/dump_desktop_slash_registry.py
index a692d4c704f..37a81171674 100755
--- a/scripts/dump_desktop_slash_registry.py
+++ b/scripts/dump_desktop_slash_registry.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/_hermes-python" "$0" "$@"'
+#!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/run-in-hermes-env" python3 "$0" "$@"'
"""Regenerate apps/desktop/src/lib/desktop-slash-registry.json from COMMAND_REGISTRY.
Run after changing any ``desktop=`` value or alias in ``hermes_cli/commands.py``;
diff --git a/scripts/gen-bootstrap-pins.py b/scripts/gen-bootstrap-pins.py
index 9e856bfbea2..448386b0dd9 100755
--- a/scripts/gen-bootstrap-pins.py
+++ b/scripts/gen-bootstrap-pins.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/_hermes-python" "$0" "$@"'
+#!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/run-in-hermes-env" python3 "$0" "$@"'
"""Generate the bootstrap pin fragments inside the installers.
The installers bootstrap uv (and, on Windows, git) BEFORE any checkout
diff --git a/scripts/gen_gateway_contracts.py b/scripts/gen_gateway_contracts.py
index d95520d3f8e..61fecf93868 100755
--- a/scripts/gen_gateway_contracts.py
+++ b/scripts/gen_gateway_contracts.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/_hermes-python" "$0" "$@"'
+#!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/run-in-hermes-env" python3 "$0" "$@"'
"""Render ``tui_gateway/contracts`` into TypeScript and OpenRPC.
Python-only (the Python CI lane has no Node): Pydantic's ``model_json_schema()`` output is walked
diff --git a/scripts/profile-tui.py b/scripts/profile-tui.py
index f6f0ce41443..0497ffbb955 100755
--- a/scripts/profile-tui.py
+++ b/scripts/profile-tui.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/_hermes-python" "$0" "$@"'
+#!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/run-in-hermes-env" python3 "$0" "$@"'
"""Drive the Hermes TUI under HERMES_DEV_PERF and summarize the pipeline.
Usage:
diff --git a/scripts/release.py b/scripts/release.py
index ae7d01be311..703c1a0e935 100755
--- a/scripts/release.py
+++ b/scripts/release.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/_hermes-python" "$0" "$@"'
+#!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/run-in-hermes-env" python3 "$0" "$@"'
"""Hermes Agent release entrypoint.
Stable releases use the ``release``, ``publish``, and ``abandon`` subcommands.
diff --git a/scripts/render-builds-table.py b/scripts/render-builds-table.py
index ab558e38fd5..543222cf5cd 100755
--- a/scripts/render-builds-table.py
+++ b/scripts/render-builds-table.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/_hermes-python" "$0" "$@"'
+#!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/run-in-hermes-env" python3 "$0" "$@"'
"""Render the release download tables into <!-- HERMES_BUILDS_TABLE -->, and
the same rows as standalone pages in the bucket.
diff --git a/scripts/run-in-hermes-env b/scripts/run-in-hermes-env
new file mode 100755
index 00000000000..c2da3b218fe
--- /dev/null
+++ b/scripts/run-in-hermes-env
@@ -0,0 +1,32 @@
+#!/usr/bin/env bash
+# Run a command in the Hermes dev environment, whatever shell or cwd it is
+# launched from: `scripts/run-in-hermes-env CMD [ARGS...]`.
+#
+# The environment is the one `activate` would give a shell, applied to this
+# process only and then exec'd into CMD, so nothing leaks back and nothing has
+# to be sourced or deactivated. It is synced first when there is none to
+# inherit or the inherited one no longer matches its inputs
+# (scripts/_activation.sh).
+#
+# Shebang for repo Python scripts, so `./scripts/foo.py` works from any cwd:
+# #!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/run-in-hermes-env" python3 "$0" "$@"'
+# The kernel appends the invoking script, and `bash -c` binds it to `$0`, so
+# the shebang finds this file relative to the script and is independent of the
+# cwd. `$BASH` for the second hop keeps it free of both the exec bit and a
+# `PATH` lookup. The line must stay under 127 bytes, and `env -S` is GNU and
+# newer-BSD; verify it if an older macOS or BSD is a target.
+# macOS's stock bash 3.2 compares mtimes in whole seconds, so an input rewritten
+# within the same second as its recorded stamp goes unnoticed there.
+set -u
+
+if [ "$#" -eq 0 ]; then
+ printf 'usage: %s CMD [ARGS...]\n' "$0" >&2
+ exit 2
+fi
+
+_here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+# shellcheck source=scripts/_activation.sh
+. "$_here/_activation.sh"
+hermes_ensure_env "$(dirname "$_here")" || exit 1
+
+exec "$@"
diff --git a/scripts/run_tests.sh b/scripts/run_tests.sh
index 8fcc4294f48..e38984d4b83 100755
--- a/scripts/run_tests.sh
+++ b/scripts/run_tests.sh
@@ -11,7 +11,7 @@
# * Env vars blanked (conftest.py also does this, but this
# is belt-and-suspenders for anyone running pytest outside our
# conftest path — e.g. on a single file)
-# * The activated checkout's test environment (activates when needed)
+# * The checkout's test environment (via scripts/run-in-hermes-env when needed)
#
# Usage:
# scripts/run_tests.sh # full suite
@@ -38,11 +38,13 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
# ── Locate python ───────────────────────────────────────────────────────────
-# The suite runs under the activated checkout's isolated test environment
-# (pm.testenv: `activate` builds it beside the checkout's install state, and CI
-# activates the same way). An inherited activation is re-checked against its
-# inputs (scripts/_activation.sh) and re-sourced when stale, so a branch switch
-# or lock edit never runs the suite against the previous dependency set.
+# The suite runs under the checkout's isolated test environment (pm.testenv),
+# and only there: unless the inherited environment is current for this
+# checkout, this script re-executes itself under scripts/run-in-hermes-env,
+# which syncs and applies it. That holds however the script is launched
+# (`scripts/run_tests.sh`, `bash scripts/run_tests.sh`, from CI or a shell), so
+# a branch switch or lock edit never runs the suite against the previous
+# dependency set.
#
# Without an activation, an explicit HERMES_PYTHON that has pytest is honored:
# the Nix devShell's editable venv and CI's minimal installer lanes provide
@@ -55,22 +57,14 @@ if [ -z "${__HERMES_ACTIVATED:-}" ] && _has_pytest "${HERMES_PYTHON:-}"; then
PYTHON="$HERMES_PYTHON"
echo "▶ not activated — using HERMES_PYTHON: $PYTHON"
else
- test_stamp="${__HERMES_ACTIVATED:-}"
- test_stamp="${test_stamp//\\//}"
- if ! hermes_activation_current "$REPO_ROOT" ||
- [ ! -f "${test_stamp%/*}/inputs/.test-environment" ] ||
- ! _has_pytest "${__HERMES_TEST_PYTHON:-}"; then
- echo "▶ activating $REPO_ROOT (environment missing or stale)" >&2
- # activate is written for interactive shells, not errexit/nounset.
- set +euo pipefail
- # shellcheck source=/dev/null
- . "$REPO_ROOT/activate" --
- activated=$?
- set -euo pipefail
- if [ "$activated" != 0 ]; then
- echo "error: activation failed (see above)" >&2
+ if ! hermes_activation_current "$REPO_ROOT"; then
+ if [ -n "${__HERMES_TESTS_REEXEC:-}" ]; then
+ echo "error: run-in-hermes-env did not produce a current environment for $REPO_ROOT" >&2
exit 1
fi
+ echo "▶ environment missing or stale for $REPO_ROOT — re-running under run-in-hermes-env" >&2
+ export __HERMES_TESTS_REEXEC=1
+ exec "$SCRIPT_DIR/run-in-hermes-env" "$BASH" "${BASH_SOURCE[0]}" "$@"
fi
PYTHON="${__HERMES_TEST_PYTHON:-}"
if ! _has_pytest "$PYTHON"; then
diff --git a/scripts/validate_plugin_catalog.py b/scripts/validate_plugin_catalog.py
index 8179eaf5f31..2b9d58aadc6 100755
--- a/scripts/validate_plugin_catalog.py
+++ b/scripts/validate_plugin_catalog.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/_hermes-python" "$0" "$@"'
+#!/usr/bin/env -S bash -c 'exec "$BASH" "$(dirname "$0")/run-in-hermes-env" python3 "$0" "$@"'
"""Standalone structural validator for plugin-catalog entry files.
Validates ``plugin-catalog/*.yaml`` catalog entries and
diff --git a/tests/pm/activation_support.py b/tests/pm/activation_support.py
new file mode 100644
index 00000000000..d33bd692d54
--- /dev/null
+++ b/tests/pm/activation_support.py
@@ -0,0 +1,273 @@
+"""Fixtures shared by the shell-activation tests.
+
+An isolated checkout holds the real activation scripts, the real PM environment
+reader and fake installed artifacts. Setup is replaced at its process boundary:
+the stub records each sync and publishes a selected environment. Nothing here
+sources the working checkout or runs its installer against the developer's home.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shlex
+import shutil
+import subprocess
+import sys
+import textwrap
+from pathlib import Path
+
+from pm.store import current_target
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+ACTIVATE = REPO_ROOT / "activate"
+ACTIVATE_PS1 = REPO_ROOT / "activate.ps1"
+SETUP_HERMES_SH = REPO_ROOT / "setup-hermes.sh"
+SETUP_HERMES_PS1 = REPO_ROOT / "setup-hermes.ps1"
+CANARY = "HERMES_PM_ACTIVATE_CANARY"
+
+
+def posix(path: Path) -> str:
+ return str(path).replace("\\", "/")
+
+
+def bash() -> str:
+ """A bash CreateProcess can start. conftest blanks SystemRoot/ComSpec
+ and the hermetic runner's PATH may resolve `bash` to the MSIX payload
+ copy under ``C:\\Program Files\\WindowsApps\\...`` (WinError 5 outside
+ its package context) or miss entirely — prefer a conventional install
+ (same pattern as the bootstrap version-stamp tests' _git_exe)."""
+ found = shutil.which("bash")
+ if found and "windowsapps" not in str(found).lower():
+ return found
+ if sys.platform == "win32":
+ pf = Path(os.environ.get("ProgramFiles", r"C:\Program Files"))
+ for rel in (("Git", "bin", "bash.exe"), ("Git", "usr", "bin", "bash.exe")):
+ cand = pf.joinpath(*rel)
+ if cand.exists():
+ return str(cand)
+ return found or "bash"
+
+
+def child_env() -> dict:
+ env = os.environ.copy()
+ if sys.platform == "win32":
+ env.setdefault("SystemRoot", r"C:\Windows")
+ env.setdefault("ComSpec", r"C:\Windows\system32\cmd.exe")
+ # PowerShell 5.1 silently fails to launch children through `&`
+ # without PATHEXT (empty output, exit 0) — the hermetic runner
+ # drops it, so every powershell-invoking child env needs it back.
+ env.setdefault(
+ "PATHEXT",
+ ".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC",
+ )
+ return env
+
+
+def spawnable_python() -> Path:
+ """An interpreter this process can actually CreateProcess. The hermetic
+ runner's venv python can be an emulated x64 binary on an arm64 host
+ (WinError 5 on every spawn), or a macOS venv shim that stops working
+ after activation sanitizes its parent environment. Prefer the venv's
+ base interpreter, then whichever python can run a trivial child; last
+ resort is sys.executable."""
+ candidates: list[Path] = []
+ for env_name in ("HERMES_TEST_PYTHON",):
+ val = os.environ.get(env_name)
+ if val:
+ candidates.append(Path(val))
+ exe = Path(sys.executable)
+ if "windowsapps" in str(exe).lower():
+ candidates.append(exe) # native packaged python — spawnable by path
+ else:
+ base = Path(getattr(sys, "_base_executable", "") or exe)
+ if base != exe:
+ candidates.append(base)
+ candidates.append(exe)
+ for cand in candidates:
+ if can_spawn(cand):
+ return cand
+ return exe
+
+
+def can_spawn(python: Path) -> bool:
+ try:
+ r = subprocess.run(
+ [str(python), "-c", "print(1)"],
+ capture_output=True,
+ text=True,
+ timeout=30,
+ env=child_env(),
+ )
+ return r.returncode == 0
+ except Exception:
+ return False
+
+
+def fake_store(tmp_path: Path) -> tuple[Path, Path]:
+ """A store laid out like pm's: facts.json marking the python package
+ installed (identity matches pm/lock.json) with a canary env export, and
+ an entry whose interpreter is a wrapper that runs the real python."""
+ lock = json.loads(
+ (REPO_ROOT / "pm" / "lock.json").read_text(encoding="utf-8-sig")
+ )["packages"]
+ target = current_target()
+ python_pkg = lock["python"]
+ sha = python_pkg["artifacts"][target]["sha256"]
+
+ store = tmp_path / "store"
+ entry = store / f"python-{python_pkg['version']}-{target}"
+ entry.mkdir(parents=True)
+
+ # The store interpreter only needs to run `python -m pm.cli env` —
+ # delegate to a real, spawnable interpreter via a #!/bin/sh wrapper (a
+ # copied CPython would miss its DLLs/stdlib; the wrapper is the honest
+ # minimal fake). sys.executable can be an emulated x64 python on an
+ # arm64 host that cannot CreateProcess children at all — resolve a
+ # spawnable interpreter instead (see spawnable_python). The wrapper
+ # works even named python.exe because activate execs it through
+ # bash/MSYS, which honors #!-scripts regardless of suffix.
+ interpreter = entry / ("python.exe" if sys.platform.startswith("win") else "bin/python3")
+ interpreter.parent.mkdir(parents=True, exist_ok=True)
+ real = spawnable_python()
+ wrapper = "#!/bin/sh\nexec '%s' \"$@\"\n" % posix(real)
+ interpreter.write_text(wrapper, encoding="utf-8")
+ interpreter.chmod(0o755)
+
+ (store / "facts.json").write_text(
+ json.dumps(
+ {
+ "schema": 1,
+ "packages": {
+ "python": {
+ "entry": entry.name,
+ "version": python_pkg["version"],
+ "env": {CANARY: "env-ok"},
+ "target": target,
+ "artifacts": [sha],
+ }
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+ return store, entry
+
+
+def isolated_checkout(tmp_path: Path) -> Path:
+ root = tmp_path / "checkout with spaces"
+ root.mkdir()
+ shutil.copytree(REPO_ROOT / "pm", root / "pm", ignore=shutil.ignore_patterns("__pycache__"))
+ (root / "hermes_cli").mkdir()
+ (root / "scripts").mkdir()
+ for relative in ("activate", "activate.ps1", "scripts/_activation.sh",
+ "hermes_constants.py", "hermes_cli/__init__.py",
+ "pm/environments.py", "hermes_cli/runtime_state.py"):
+ shutil.copy2(REPO_ROOT / relative, root / relative)
+ # Environment-only tests do not exercise provisioning; the runtime tests
+ # replace these stubs with a publisher that records and applies each sync.
+ (root / "setup-hermes.sh").write_text(
+ 'test "$#" = 2 && test "$1" = --runtime-only && case "$2" in --test-environment*) ;; *) exit 2 ;; esac\n',
+ encoding="utf-8",
+ )
+ (root / "setup-hermes.ps1").write_text(
+ "param([switch]$RuntimeOnly)\nif (-not $RuntimeOnly) { exit 2 }\n", encoding="utf-8",
+ )
+ return root
+
+
+def bash_env(store: Path) -> dict:
+ env = child_env()
+ home = store.parent / "home"
+ home.mkdir(exist_ok=True)
+ env.update(HOME=posix(home), USERPROFILE=str(home), HERMES_HOME=posix(home / "hermes"))
+ for key in ("PYTHONHOME", "PYTHONPATH", "VIRTUAL_ENV", "BASH_ENV", "__HERMES_ACTIVATED"):
+ env.pop(key, None)
+ env["HERMES_RUNTIME_DIR"] = posix(store)
+ # Keep the real env out of the composed pm output so the canary export
+ # is the only thing activate adds beyond the ambient environment.
+ env.pop(CANARY, None)
+ return env
+
+
+def powershell() -> str | None:
+ for name in ("pwsh", "powershell"):
+ found = shutil.which(name)
+ if found and "windowsapps" not in str(found).lower():
+ return found
+ # Prefer the conventional System32 host over an MSIX-packaged one
+ # (same WinError-5-outside-package-context class as bash()); also the
+ # fallback when the hermetic runner's PATH misses both names.
+ if sys.platform == "win32":
+ cand = (
+ Path(os.environ.get("SystemRoot", r"C:\Windows"))
+ / "System32" / "WindowsPowerShell" / "v1.0" / "powershell.exe"
+ )
+ if cand.exists():
+ return str(cand)
+ return None
+
+
+def sync_checkout(tmp_path: Path):
+ root = isolated_checkout(tmp_path)
+ env = bash_env(tmp_path / "store")
+ python = spawnable_python()
+ # The setup seam publishes a bootstrap and a selected generation. PM's
+ # freshness algorithms have their own tests; here a warm setup call is a
+ # no-op and activation must still call it, rather than cache its own answer.
+ (root / "sync.py").write_text(textwrap.dedent('''\
+ import json, os, pathlib, shutil, sys
+ from pm.environments import runtime_facts_path, site_packages
+ root = pathlib.Path(__file__).parent
+ record = {"argv": sys.argv[1:], "python_env": {
+ key: os.environ.get(key) for key in ("PYTHONHOME", "PYTHONPATH", "VIRTUAL_ENV")}}
+ with (root / "calls.jsonl").open("a", encoding="utf-8") as stream:
+ stream.write(json.dumps(record) + "\\n")
+ assert all(value is None for value in record["python_env"].values()), record
+ assert sys.argv[1:] == ["runtime-only", "--trust-recorded", "--test-environment"], record
+ print("setup progress")
+ if (root / "fail").exists():
+ sys.exit(42)
+ bootstrap = root / ".venv"
+ if not bootstrap.exists():
+ shutil.copytree(root / "prepared-bootstrap", bootstrap)
+ # Windows PowerShell's Set-Content writes a BOM.
+ generation = (root / "input").read_text(encoding="utf-8-sig").strip()
+ facts = runtime_facts_path(root)
+ selected = facts.parent / "environments" / generation / "venv"
+ if not selected.exists():
+ site_packages(selected).mkdir(parents=True)
+ (selected / "pyvenv.cfg").write_text("home = fixture", encoding="utf-8")
+ facts.write_text(json.dumps({"packages": {"venv": {"environment": str(selected)}}}), encoding="utf-8")
+ with (root / "builds").open("a", encoding="utf-8") as stream:
+ stream.write(generation + "\\n")
+ '''), encoding="utf-8")
+ (root / "input").write_text("first", encoding="utf-8")
+ if os.name == "nt":
+ subprocess.run(
+ [str(python), "-m", "venv", "--without-pip", str(root / "prepared-bootstrap")],
+ check=True, capture_output=True, env=env, timeout=60,
+ )
+ else:
+ binary = root / "prepared-bootstrap" / "bin" / "python"
+ binary.parent.mkdir(parents=True)
+ binary.write_text(f"#!/bin/sh\nexec {shlex.quote(str(python))} \"$@\"\n", encoding="utf-8")
+ binary.chmod(0o755)
+ # Activation's contract with setup is the runtime-only switch; setup
+ # itself maps that to PM's --trust-recorded install.
+ (root / "setup-hermes.sh").write_text(
+ 'test "$#" = 2 && test "$1" = --runtime-only && test "$2" = --test-environment || exit 2\n'
+ f'cd {shlex.quote(str(root))} || exit 3\n'
+ f'exec {shlex.quote(str(python))} sync.py runtime-only --trust-recorded --test-environment\n', encoding="utf-8",
+ )
+ (root / "setup-hermes.ps1").write_text(
+ "param([switch]$RuntimeOnly)\n"
+ "if (-not $RuntimeOnly) { exit 2 }\n"
+ "$ErrorActionPreference = 'Stop'\n"
+ "$record = @{pid=$PID; executable=(Get-Process -Id $PID).Path; "
+ "argv=[Environment]::GetCommandLineArgs()}\n"
+ "$record | ConvertTo-Json -Compress | Add-Content -LiteralPath \"$PSScriptRoot\\ps-calls.jsonl\"\n"
+ "Set-Location -LiteralPath $PSScriptRoot\n"
+ f"& '{python}' sync.py runtime-only --trust-recorded --test-environment\nexit $LASTEXITCODE\n", encoding="utf-8",
+ )
+ return root, env
diff --git a/tests/pm/test_activate_scripts.py b/tests/pm/test_activate_scripts.py
index f93ea56f17f..1f65dd1a234 100644
--- a/tests/pm/test_activate_scripts.py
+++ b/tests/pm/test_activate_scripts.py
@@ -1,215 +1,46 @@
-"""Run the real activation scripts with setup replaced at its process boundary.
+"""``activate`` / ``activate.ps1``: an interactive shell takes on the environment and gives it back.
-The isolated checkout uses the real PM environment reader and fake installed
-artifacts. Setup records each sync and publishes a selected environment; no test
-sources the working checkout or runs its installer against the developer's home.
+What a process launched under ``scripts/run-in-hermes-env`` sees is covered in
+tests/scripts/test_run_in_hermes_env.py; how the environment is composed, in
+test_environment_script.py.
"""
from __future__ import annotations
-import json
-import os
-import shutil
import subprocess
-import sys
from pathlib import Path
import pytest
-from pm.store import current_target
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-ACTIVATE = REPO_ROOT / "activate"
-ACTIVATE_PS1 = REPO_ROOT / "activate.ps1"
-SETUP_HERMES_SH = REPO_ROOT / "setup-hermes.sh"
-SETUP_HERMES_PS1 = REPO_ROOT / "setup-hermes.ps1"
-CANARY = "HERMES_PM_ACTIVATE_CANARY"
-
-
-def _posix(path: Path) -> str:
- return str(path).replace("\\", "/")
-
-
-def _bash() -> str:
- """A bash CreateProcess can start. conftest blanks SystemRoot/ComSpec
- and the hermetic runner's PATH may resolve `bash` to the MSIX payload
- copy under ``C:\\Program Files\\WindowsApps\\...`` (WinError 5 outside
- its package context) or miss entirely — prefer a conventional install
- (same pattern as the bootstrap version-stamp tests' _git_exe)."""
- found = shutil.which("bash")
- if found and "windowsapps" not in str(found).lower():
- return found
- if sys.platform == "win32":
- pf = Path(os.environ.get("ProgramFiles", r"C:\Program Files"))
- for rel in (("Git", "bin", "bash.exe"), ("Git", "usr", "bin", "bash.exe")):
- cand = pf.joinpath(*rel)
- if cand.exists():
- return str(cand)
- return found or "bash"
-
-
-def _child_env() -> dict:
- env = os.environ.copy()
- if sys.platform == "win32":
- env.setdefault("SystemRoot", r"C:\Windows")
- env.setdefault("ComSpec", r"C:\Windows\system32\cmd.exe")
- # PowerShell 5.1 silently fails to launch children through `&`
- # without PATHEXT (empty output, exit 0) — the hermetic runner
- # drops it, so every powershell-invoking child env needs it back.
- env.setdefault(
- "PATHEXT",
- ".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC",
- )
- return env
-
-
-def _spawnable_python() -> Path:
- """An interpreter this process can actually CreateProcess. The hermetic
- runner's venv python can be an emulated x64 binary on an arm64 host
- (WinError 5 on every spawn), or a macOS venv shim that stops working
- after activation sanitizes its parent environment. Prefer the venv's
- base interpreter, then whichever python can run a trivial child; last
- resort is sys.executable."""
- candidates: list[Path] = []
- for env_name in ("HERMES_TEST_PYTHON",):
- val = os.environ.get(env_name)
- if val:
- candidates.append(Path(val))
- exe = Path(sys.executable)
- if "windowsapps" in str(exe).lower():
- candidates.append(exe) # native packaged python — spawnable by path
- else:
- base = Path(getattr(sys, "_base_executable", "") or exe)
- if base != exe:
- candidates.append(base)
- candidates.append(exe)
- for cand in candidates:
- if _can_spawn(cand):
- return cand
- return exe
-
-
-def _can_spawn(python: Path) -> bool:
- try:
- r = subprocess.run(
- [str(python), "-c", "print(1)"],
- capture_output=True,
- text=True,
- timeout=30,
- env=_child_env(),
- )
- return r.returncode == 0
- except Exception:
- return False
-
-
-def _fake_store(tmp_path: Path) -> tuple[Path, Path]:
- """A store laid out like pm's: facts.json marking the python package
- installed (identity matches pm/lock.json) with a canary env export, and
- an entry whose interpreter is a wrapper that runs the real python."""
- lock = json.loads(
- (REPO_ROOT / "pm" / "lock.json").read_text(encoding="utf-8-sig")
- )["packages"]
- target = current_target()
- python_pkg = lock["python"]
- sha = python_pkg["artifacts"][target]["sha256"]
-
- store = tmp_path / "store"
- entry = store / f"python-{python_pkg['version']}-{target}"
- entry.mkdir(parents=True)
-
- # The store interpreter only needs to run `python -m pm.cli env` —
- # delegate to a real, spawnable interpreter via a #!/bin/sh wrapper (a
- # copied CPython would miss its DLLs/stdlib; the wrapper is the honest
- # minimal fake). sys.executable can be an emulated x64 python on an
- # arm64 host that cannot CreateProcess children at all — resolve a
- # spawnable interpreter instead (see _spawnable_python). The wrapper
- # works even named python.exe because activate execs it through
- # bash/MSYS, which honors #!-scripts regardless of suffix.
- interpreter = entry / ("python.exe" if sys.platform.startswith("win") else "bin/python3")
- interpreter.parent.mkdir(parents=True, exist_ok=True)
- real = _spawnable_python()
- wrapper = "#!/bin/sh\nexec '%s' \"$@\"\n" % _posix(real)
- interpreter.write_text(wrapper, encoding="utf-8")
- interpreter.chmod(0o755)
-
- (store / "facts.json").write_text(
- json.dumps(
- {
- "schema": 1,
- "packages": {
- "python": {
- "entry": entry.name,
- "version": python_pkg["version"],
- "env": {CANARY: "env-ok"},
- "target": target,
- "artifacts": [sha],
- }
- },
- }
- ),
- encoding="utf-8",
- )
- return store, entry
-
-
-def _isolated_checkout(tmp_path: Path) -> Path:
- root = tmp_path / "checkout with spaces"
- root.mkdir()
- shutil.copytree(REPO_ROOT / "pm", root / "pm", ignore=shutil.ignore_patterns("__pycache__"))
- (root / "hermes_cli").mkdir()
- for relative in ("activate", "activate.ps1", "hermes_constants.py", "hermes_cli/__init__.py",
- "pm/environments.py", "hermes_cli/runtime_state.py"):
- shutil.copy2(REPO_ROOT / relative, root / relative)
- # Environment-only tests do not exercise provisioning; the runtime tests
- # replace these stubs with a publisher that records and applies each sync.
- (root / "setup-hermes.sh").write_text(
- 'test "$#" = 2 && test "$1" = --runtime-only && case "$2" in --test-environment*) ;; *) exit 2 ;; esac\n',
- encoding="utf-8",
- )
- (root / "setup-hermes.ps1").write_text(
- "param([switch]$RuntimeOnly)\nif (-not $RuntimeOnly) { exit 2 }\n", encoding="utf-8",
- )
- return root
-
-
-def _bash_env(store: Path) -> dict:
- env = _child_env()
- home = store.parent / "home"
- home.mkdir(exist_ok=True)
- env.update(HOME=_posix(home), USERPROFILE=str(home), HERMES_HOME=_posix(home / "hermes"))
- for key in ("PYTHONHOME", "PYTHONPATH", "VIRTUAL_ENV", "BASH_ENV", "__HERMES_ACTIVATED"):
- env.pop(key, None)
- env["HERMES_RUNTIME_DIR"] = _posix(store)
- # Keep the real env out of the composed pm output so the canary export
- # is the only thing activate adds beyond the ambient environment.
- env.pop(CANARY, None)
- return env
+from tests.pm.activation_support import (
+ ACTIVATE, ACTIVATE_PS1, CANARY, SETUP_HERMES_PS1, SETUP_HERMES_SH, bash, bash_env,
+ child_env, fake_store, isolated_checkout, posix, powershell, spawnable_python,
+)
def test_bash_scripts_pass_syntax_check():
for script in (ACTIVATE, SETUP_HERMES_SH):
result = subprocess.run(
- [_bash(), "-n", _posix(script)], capture_output=True, text=True, env=_child_env()
+ [bash(), "-n", posix(script)], capture_output=True, text=True, env=child_env()
)
assert result.returncode == 0, f"{script.name}: {result.stderr}"
@pytest.mark.platforms("windows")
def test_source_activate_exports_the_pm_env(tmp_path: Path):
- root = _isolated_checkout(tmp_path)
- store, _ = _fake_store(tmp_path)
+ root = isolated_checkout(tmp_path)
+ store, _ = fake_store(tmp_path)
script = (
- f'source "{_posix(root / "activate")}" && '
+ f'source "{posix(root / "activate")}" && '
f'test -n "$__HERMES_ACTIVATED" && '
f'printf "%s" "${CANARY}"'
)
result = subprocess.run(
- [_bash(), "-c", script],
+ [bash(), "-c", script],
capture_output=True,
text=True,
- cwd=_posix(tmp_path),
- env=_bash_env(store),
+ cwd=posix(tmp_path),
+ env=bash_env(store),
)
assert result.returncode == 0, result.stderr
assert result.stdout == "env-ok"
@@ -220,21 +51,21 @@ def test_activate_exports_the_sentinel_to_child_processes(tmp_path: Path):
"""Repo scripts read activation from the environment, so the sentinel must
survive into an exec'd child (a plain shell variable would not), and
deactivate must take it back out."""
- root = _isolated_checkout(tmp_path)
- store, _ = _fake_store(tmp_path)
+ root = isolated_checkout(tmp_path)
+ store, _ = fake_store(tmp_path)
script = (
- f'source "{_posix(root / "activate")}" && '
+ f'source "{posix(root / "activate")}" && '
f'"$BASH" -c \'test -n "$__HERMES_ACTIVATED"\' && '
f'deactivate && '
f'! "$BASH" -c \'test -n "$__HERMES_ACTIVATED"\' && '
f'echo exported-then-cleared'
)
result = subprocess.run(
- [_bash(), "-c", script],
+ [bash(), "-c", script],
capture_output=True,
text=True,
- cwd=_posix(tmp_path),
- env=_bash_env(store),
+ cwd=posix(tmp_path),
+ env=bash_env(store),
)
assert result.returncode == 0, result.stderr
assert result.stdout.strip() == "exported-then-cleared"
@@ -242,21 +73,21 @@ def test_activate_exports_the_sentinel_to_child_processes(tmp_path: Path):
@pytest.mark.platforms("windows")
def test_deactivate_restores_the_prior_shell(tmp_path: Path):
- root = _isolated_checkout(tmp_path)
- store, _ = _fake_store(tmp_path)
+ root = isolated_checkout(tmp_path)
+ store, _ = fake_store(tmp_path)
script = (
- f'source "{_posix(root / "activate")}" && deactivate && '
+ f'source "{posix(root / "activate")}" && deactivate && '
f'test -z "${{{CANARY}+set}}" && '
f'test -z "${{__HERMES_ACTIVATED+set}}" && '
f"! declare -F deactivate >/dev/null && "
f'echo restored'
)
result = subprocess.run(
- [_bash(), "-c", script],
+ [bash(), "-c", script],
capture_output=True,
text=True,
- cwd=_posix(tmp_path),
- env=_bash_env(store),
+ cwd=posix(tmp_path),
+ env=bash_env(store),
)
assert result.returncode == 0, result.stderr
assert result.stdout.strip() == "restored"
@@ -267,39 +98,39 @@ def test_activate_leaves_the_shell_paths_in_posix_form(tmp_path: Path):
"""The pm env is read by a native Windows Python, which sees PATH, HOME and
the temp variables in Windows form. Exported verbatim, `C:\\a;C:\\b` left
bash without a usable PATH, so every command after activation failed."""
- root = _isolated_checkout(tmp_path)
- store, _ = _fake_store(tmp_path)
+ root = isolated_checkout(tmp_path)
+ store, _ = fake_store(tmp_path)
script = (
'prior_home="$HOME" prior_tmp="$TMP" && '
- f'source "{_posix(root / "activate")}" && '
+ f'source "{posix(root / "activate")}" && '
'command -v basename >/dev/null && '
'case "$PATH" in *";"*|*"\\\\"*) exit 3;; esac && '
'test "$HOME" = "$prior_home" && test "$TMP" = "$prior_tmp" && '
'echo posix'
)
result = subprocess.run(
- [_bash(), "-c", script],
+ [bash(), "-c", script],
capture_output=True,
text=True,
- cwd=_posix(tmp_path),
- env=_bash_env(store),
+ cwd=posix(tmp_path),
+ env=bash_env(store),
)
assert result.returncode == 0, result.stderr
assert result.stdout.strip() == "posix"
def test_activate_fails_cleanly_without_a_store(tmp_path: Path):
- env = _bash_env(tmp_path / "empty-store")
- isolated = _isolated_checkout(tmp_path) / "activate"
+ env = bash_env(tmp_path / "empty-store")
+ isolated = isolated_checkout(tmp_path) / "activate"
script = (
- f'source "{_posix(isolated)}" 2>/dev/null; '
+ f'source "{posix(isolated)}" 2>/dev/null; '
f'test $? -ne 0 && echo refused'
)
result = subprocess.run(
- [_bash(), "-c", script],
+ [bash(), "-c", script],
capture_output=True,
text=True,
- cwd=_posix(tmp_path),
+ cwd=posix(tmp_path),
env=env,
)
# Without any provisioned python the source must refuse — never
@@ -307,28 +138,10 @@ def test_activate_fails_cleanly_without_a_store(tmp_path: Path):
assert "refused" in result.stdout
-def _powershell() -> str | None:
- for name in ("pwsh", "powershell"):
- found = shutil.which(name)
- if found and "windowsapps" not in str(found).lower():
- return found
- # Prefer the conventional System32 host over an MSIX-packaged one
- # (same WinError-5-outside-package-context class as _bash()); also the
- # fallback when the hermetic runner's PATH misses both names.
- if sys.platform == "win32":
- cand = (
- Path(os.environ.get("SystemRoot", r"C:\Windows"))
- / "System32" / "WindowsPowerShell" / "v1.0" / "powershell.exe"
- )
- if cand.exists():
- return str(cand)
- return None
-
-
def test_powershell_scripts_parse():
"""Parse-check the PowerShell entry points; skip gracefully when no
PowerShell host is available."""
- ps = _powershell()
+ ps = powershell()
if ps is None:
pytest.skip("no PowerShell host available")
for script in (ACTIVATE_PS1, SETUP_HERMES_PS1):
@@ -353,13 +166,13 @@ def test_powershell_scripts_parse():
@pytest.mark.platforms("windows")
def test_powershell_activate_exports_and_deactivates(tmp_path: Path):
# Native venv redirectors resolve the base DLLs/stdlib without copying CPython.
- root = _isolated_checkout(tmp_path)
- env = _bash_env(tmp_path / "store")
+ root = isolated_checkout(tmp_path)
+ env = bash_env(tmp_path / "store")
subprocess.run(
- [str(_spawnable_python()), "-m", "venv", "--without-pip", str(root / ".venv")],
+ [str(spawnable_python()), "-m", "venv", "--without-pip", str(root / ".venv")],
check=True, capture_output=True, env=env, timeout=60,
)
- ps = _powershell()
+ ps = powershell()
assert ps, "native Windows test requires PowerShell"
result = subprocess.run(
[ps, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command",
diff --git a/tests/pm/test_activation_runtime.py b/tests/pm/test_activation_runtime.py
index 38ededa6405..28c1aed1e88 100644
--- a/tests/pm/test_activation_runtime.py
+++ b/tests/pm/test_activation_runtime.py
@@ -8,79 +8,12 @@ import textwrap
import pytest
-from tests.pm.test_activate_scripts import (
- _bash, _bash_env, _isolated_checkout, _posix, _powershell, _spawnable_python,
-)
+from tests.pm.activation_support import bash, fake_store, posix, powershell, sync_checkout
# Spawns children with a home it builds itself; the parent's must stay real.
pytestmark = pytest.mark.real_machine_home
-def _sync_checkout(tmp_path: Path):
- root = _isolated_checkout(tmp_path)
- env = _bash_env(tmp_path / "store")
- python = _spawnable_python()
- # The setup seam publishes a bootstrap and a selected generation. PM's
- # freshness algorithms have their own tests; here a warm setup call is a
- # no-op and activation must still call it, rather than cache its own answer.
- (root / "sync.py").write_text(textwrap.dedent('''\
- import json, os, pathlib, shutil, sys
- from pm.environments import runtime_facts_path, site_packages
- root = pathlib.Path(__file__).parent
- record = {"argv": sys.argv[1:], "python_env": {
- key: os.environ.get(key) for key in ("PYTHONHOME", "PYTHONPATH", "VIRTUAL_ENV")}}
- with (root / "calls.jsonl").open("a", encoding="utf-8") as stream:
- stream.write(json.dumps(record) + "\\n")
- assert all(value is None for value in record["python_env"].values()), record
- assert sys.argv[1:] == ["runtime-only", "--trust-recorded", "--test-environment"], record
- print("setup progress")
- if (root / "fail").exists():
- sys.exit(42)
- bootstrap = root / ".venv"
- if not bootstrap.exists():
- shutil.copytree(root / "prepared-bootstrap", bootstrap)
- # Windows PowerShell's Set-Content writes a BOM.
- generation = (root / "input").read_text(encoding="utf-8-sig").strip()
- facts = runtime_facts_path(root)
- selected = facts.parent / "environments" / generation / "venv"
- if not selected.exists():
- site_packages(selected).mkdir(parents=True)
- (selected / "pyvenv.cfg").write_text("home = fixture", encoding="utf-8")
- facts.write_text(json.dumps({"packages": {"venv": {"environment": str(selected)}}}), encoding="utf-8")
- with (root / "builds").open("a", encoding="utf-8") as stream:
- stream.write(generation + "\\n")
- '''), encoding="utf-8")
- (root / "input").write_text("first", encoding="utf-8")
- if os.name == "nt":
- subprocess.run(
- [str(python), "-m", "venv", "--without-pip", str(root / "prepared-bootstrap")],
- check=True, capture_output=True, env=env, timeout=60,
- )
- else:
- binary = root / "prepared-bootstrap" / "bin" / "python"
- binary.parent.mkdir(parents=True)
- binary.write_text(f"#!/bin/sh\nexec {shlex.quote(str(python))} \"$@\"\n", encoding="utf-8")
- binary.chmod(0o755)
- # Activation's contract with setup is the runtime-only switch; setup
- # itself maps that to PM's --trust-recorded install.
- (root / "setup-hermes.sh").write_text(
- 'test "$#" = 2 && test "$1" = --runtime-only && test "$2" = --test-environment || exit 2\n'
- f'cd {shlex.quote(str(root))} || exit 3\n'
- f'exec {shlex.quote(str(python))} sync.py runtime-only --trust-recorded --test-environment\n', encoding="utf-8",
- )
- (root / "setup-hermes.ps1").write_text(
- "param([switch]$RuntimeOnly)\n"
- "if (-not $RuntimeOnly) { exit 2 }\n"
- "$ErrorActionPreference = 'Stop'\n"
- "$record = @{pid=$PID; executable=(Get-Process -Id $PID).Path; "
- "argv=[Environment]::GetCommandLineArgs()}\n"
- "$record | ConvertTo-Json -Compress | Add-Content -LiteralPath \"$PSScriptRoot\\ps-calls.jsonl\"\n"
- "Set-Location -LiteralPath $PSScriptRoot\n"
- f"& '{python}' sync.py runtime-only --trust-recorded --test-environment\nexit $LASTEXITCODE\n", encoding="utf-8",
- )
- return root, env
-
-
def _assert_syncs(root: Path):
calls = [json.loads(line) for line in (root / "calls.jsonl").read_text(encoding="utf-8").splitlines()]
assert calls == [{"argv": ["runtime-only", "--trust-recorded", "--test-environment"], "python_env": {
@@ -92,25 +25,25 @@ def _assert_syncs(root: Path):
@pytest.mark.platforms("posix")
@pytest.mark.parametrize("canary", [None, "caller-canary"])
def test_bash_cold_sync_changed_input_and_warm_noop(tmp_path, canary):
- root, env = _sync_checkout(tmp_path)
+ root, env = sync_checkout(tmp_path)
assert not (root / ".venv").exists()
if canary is not None:
env["HERMES_PM_ACTIVATE_CANARY"] = canary
- from tests.pm.test_activate_scripts import _fake_store
- _fake_store(tmp_path)
+ from tests.pm.test_activate_scripts import fake_store
+ fake_store(tmp_path)
script = f'''
set -e
export PYTHONPATH=caller-original VIRTUAL_ENV=caller-venv
original_path="$PATH"
- source "{_posix(root / 'activate')}"
+ source "{posix(root / 'activate')}"
printf '%s\\n' "$PYTHONPATH"
test "$HERMES_PM_ACTIVATE_CANARY" = env-ok
- printf second > "{_posix(root / 'input')}"
- source "{_posix(root / 'activate')}"
+ printf second > "{posix(root / 'input')}"
+ source "{posix(root / 'activate')}"
printf '%s\\n' "$PYTHONPATH"
- source "{_posix(root / 'activate')}"
+ source "{posix(root / 'activate')}"
printf '%s\\n' "$PYTHONPATH"
- test "$PWD" = "{_posix(tmp_path)}"
+ test "$PWD" = "{posix(tmp_path)}"
deactivate
test "$PATH" = "$original_path"
test "$PYTHONPATH" = caller-original
@@ -119,7 +52,7 @@ def test_bash_cold_sync_changed_input_and_warm_noop(tmp_path, canary):
test -z "${{__HERMES_ACTIVATED+set}}"
! declare -F deactivate >/dev/null
'''
- run = subprocess.run([_bash(), "-c", script], cwd=tmp_path, env=env,
+ run = subprocess.run([bash(), "-c", script], cwd=tmp_path, env=env,
capture_output=True, text=True, timeout=40)
assert run.returncode == 0, run.stdout + run.stderr
first, second, warm = run.stdout.splitlines()
@@ -133,7 +66,7 @@ def test_bash_cold_sync_changed_input_and_warm_noop(tmp_path, canary):
@pytest.mark.platforms("posix")
@pytest.mark.parametrize("already_active", [False, True])
def test_bash_setup_failure_preserves_caller(tmp_path, already_active):
- root, env = _sync_checkout(tmp_path)
+ root, env = sync_checkout(tmp_path)
activate = shlex.quote(str(root / "activate"))
script = f'''
set -e
@@ -152,7 +85,7 @@ def test_bash_setup_failure_preserves_caller(tmp_path, already_active):
{"deactivate" if already_active else ':'}
printf preserved
'''
- run = subprocess.run([_bash(), "-c", script], cwd=tmp_path, env=env,
+ run = subprocess.run([bash(), "-c", script], cwd=tmp_path, env=env,
capture_output=True, text=True, timeout=40)
assert run.returncode == 0, run.stdout + run.stderr
assert run.stdout == "preserved"
@@ -164,8 +97,8 @@ def test_bash_setup_failure_preserves_caller(tmp_path, already_active):
@pytest.mark.platforms("windows")
def test_powershell_cold_sync_changed_input_warm_and_failure(tmp_path):
# Native child-process and venv semantics cannot be reproduced by faking win32.
- root, env = _sync_checkout(tmp_path)
- ps = _powershell()
+ root, env = sync_checkout(tmp_path)
+ ps = powershell()
assert ps, "native Windows test requires PowerShell"
script = tmp_path / "run.ps1"
script.write_text(f'''
diff --git a/tests/pm/test_environment_script.py b/tests/pm/test_environment_script.py
new file mode 100644
index 00000000000..c045bded144
--- /dev/null
+++ b/tests/pm/test_environment_script.py
@@ -0,0 +1,42 @@
+"""``pm.environments.shell_exports``: the composed environment as a script a shell can evaluate.
+
+Both ``activate`` and ``scripts/run-in-hermes-env`` evaluate this output, so the
+contract is what a real shell reads back: any value survives the quoting, and
+names the shell cannot assign are left out instead of failing the whole script.
+"""
+
+from __future__ import annotations
+
+import subprocess
+
+import pytest
+
+from pm.environments import shell_exports
+from tests.pm.activation_support import bash
+
+NASTY = {
+ "PLAIN": "value",
+ "SPACES": "a b c",
+ "QUOTES": "it's a \"test\"",
+ "SHELL_SYNTAX": "$HOME `id` $(id) ; & | > < * ? [x] ~ #",
+ "BACKSLASHES": "C:\\path\\to\\ \\n \\'",
+ "EMPTY": "",
+ "MULTILINE": "first\nsecond",
+}
+
+# Prints each value NUL-terminated, in the order of NASTY.
+PROBE = "printf '%s\\0' " + " ".join(f'"${name}"' for name in NASTY)
+
+
+def test_a_real_shell_reads_every_value_back_unchanged():
+ script = shell_exports(NASTY) + "\n" + PROBE
+ run = subprocess.run([bash(), "-c", script], capture_output=True, text=True, timeout=30)
+ assert run.returncode == 0, run.stderr
+ assert run.stdout.split("\0")[:-1] == list(NASTY.values())
+
+
+def test_names_no_shell_can_assign_are_left_out():
+ script = shell_exports({"ProgramFiles(ARM)": "x", "1BAD": "x", "GOOD": "y"})
+ assert "GOOD" in script
+ assert "ProgramFiles" not in script and "1BAD" not in script
diff --git a/tests/scripts/test_hermes_python_prologue.py b/tests/scripts/test_hermes_python_prologue.py
deleted file mode 100644
index bad468ed6a0..00000000000
--- a/tests/scripts/test_hermes_python_prologue.py
+++ /dev/null
@@ -1,159 +0,0 @@
-"""The self-activating shebang prologue: when does it re-activate?
-
-``scripts/_hermes-python`` is the POSIX shebang target. Its one decision worth
-pinning is staleness: pm stamps each dependency input's mtime beside the
-installed-state file ``__HERMES_ACTIVATED`` names, and any input whose mtime
-differs from its stamp means the inherited environment may not match its
-inputs. Invert that either way and the cost is invisible — a re-sync on every
-run, or a stale environment that looks fine.
-
-The stamps come from the real ``pm.environments`` writer, so these tests pin
-the contract between what pm records and what the prologue reads.
-
-A ``python3`` shim goes on PATH because the prologue execs ``python3`` by name,
-which does not exist on stock Windows; the subject here is the staleness
-branch, not interpreter resolution.
-"""
-
-from __future__ import annotations
-
-import datetime
-import os
-import shutil
-import subprocess
-import sys
-from pathlib import Path
-
-import pytest
-
-from pm.environments import ACTIVATION_INPUTS, activation_input_mtimes, record_activation_inputs
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-PROLOGUE = REPO_ROOT / "scripts" / "_hermes-python"
-
-EARLIER = "2018-01-01 00:00:00"
-LONG_AGO = "2019-01-01 00:00:00"
-STAMP_TIME = "2020-06-01 00:00:00"
-JUST_AFTER = "2021-01-01 00:00:00"
-
-
-def _posix(path: Path) -> str:
- return str(path).replace("\\", "/")
-
-
-def _bash() -> str:
- found = shutil.which("bash")
- if found and "windowsapps" not in str(found).lower():
- return found
- if sys.platform == "win32":
- for rel in (("Git", "bin", "bash.exe"), ("Git", "usr", "bin", "bash.exe")):
- cand = Path(os.environ.get("ProgramFiles", r"C:\Program Files")).joinpath(*rel)
- if cand.exists():
- return str(cand)
- return found or "bash"
-
-
-def _set_mtime(path: Path, stamp: str) -> None:
- when = datetime.datetime.strptime(stamp, "%Y-%m-%d %H:%M:%S").timestamp()
- os.utime(path, (when, when))
-
-
-def checkout(tmp_path: Path) -> Path:
- """A repo-shaped tree whose stub activate announces each sourcing; its
- installed state lives in ``state/`` (facts.json beside the input stamps)."""
- root = tmp_path / "checkout"
- (root / "scripts").mkdir(parents=True)
- (root / "shim").mkdir()
- (root / "state").mkdir()
- shutil.copy2(PROLOGUE, root / "scripts" / PROLOGUE.name)
- shutil.copy2(REPO_ROOT / "scripts" / "_activation.sh", root / "scripts" / "_activation.sh")
- for name in ACTIVATION_INPUTS:
- (root / name).parent.mkdir(parents=True, exist_ok=True)
- (root / name).touch()
- _set_mtime(root / name, LONG_AGO)
- (root / "state" / "facts.json").touch()
- _set_mtime(root / "state" / "facts.json", STAMP_TIME)
-
- # Quote in posix form: a /bin/sh script treats backslashes in an unquoted
- # word as escapes (same pattern as tests/pm/test_activate_scripts.py).
- shim = root / "shim" / "python3"
- shim.write_text("#!/bin/sh\nexec '%s' \"$@\"\n" % _posix(Path(sys.executable)), encoding="utf-8")
- shim.chmod(0o755)
-
- (root / "scripts" / "probe.py").write_text(
- "import os, sys\n"
- "print('target ran; sentinel =', os.environ.get('__HERMES_ACTIVATED'))\n",
- encoding="utf-8",
- )
- (root / "activate").write_text(
- "echo 'ACTIVATED' >&2\n"
- "export __HERMES_ACTIVATED=\"%s/state/facts.json\"\n"
- "export PATH=\"%s/shim:$PATH\"\n" % (_posix(root), _posix(root)),
- encoding="utf-8",
- )
- return root
-
-
-def _record(root: Path, *, test_environment: bool = True) -> None:
- """What a successful ``pm install`` leaves behind."""
- record_activation_inputs(root / "state" / "inputs", activation_input_mtimes(root), root,
- test_environment=test_environment)
-
-
-def _run(root: Path, sentinel: str | None = "{root}/state/facts.json") -> str:
- """Drive the prologue as the kernel would; return stderr, assert it ran."""
- env = {**os.environ, "PATH": f"{_posix(root / 'shim')}{os.pathsep}{os.environ.get('PATH', '')}"}
- env.pop("__HERMES_ACTIVATED", None)
- if sentinel is not None:
- env["__HERMES_ACTIVATED"] = sentinel.replace("{root}", _posix(root))
- result = subprocess.run(
- [_bash(), _posix(root / "scripts" / PROLOGUE.name), _posix(root / "scripts" / "probe.py")],
- capture_output=True, text=True, cwd=_posix(root), env=env, timeout=60,
- )
- assert result.returncode == 0, result.stderr
- assert "target ran" in result.stdout, result.stderr
- return result.stderr
-
-
-def test_foreign_checkout_with_matching_input_times_reactivates(checkout: Path):
- _record(checkout)
- other = checkout.parent / "other"
- shutil.copytree(checkout, other, copy_function=shutil.copy2)
- assert "ACTIVATED" in _run(other, str(checkout / "state" / "facts.json"))
-
-
-def test_recorded_inputs_are_left_alone(checkout: Path):
- """A checkout rewrote every input after facts.json was last written, then a
- no-op sync recorded them: the environment is current. Re-syncing on every
- run is the cost of getting this wrong."""
- for name in ACTIVATION_INPUTS:
- _set_mtime(checkout / name, JUST_AFTER)
- _record(checkout)
- assert "ACTIVATED" not in _run(checkout)
-
-
-def test_runtime_only_install_cannot_mark_test_environment_current(checkout: Path):
- marker = checkout / "state" / "inputs" / ".test-environment"
- _record(checkout)
- assert marker.is_file()
- _record(checkout, test_environment=False)
- assert not marker.exists()
- assert "ACTIVATED" not in _run(checkout) # The app is current; the test env isn't.
-
-
[email protected]("moved_to", [JUST_AFTER, EARLIER], ids=["newer", "older"])
[email protected]("input_name", ACTIVATION_INPUTS)
-def test_input_mtime_differing_from_its_stamp_reactivates(checkout: Path, input_name: str, moved_to: str):
- """A branch switch can move an input's mtime either way; both mean the
- recorded install was not verified against what is on disk now."""
- _record(checkout)
- _set_mtime(checkout / input_name, moved_to)
- assert "ACTIVATED" in _run(checkout)
-
-
[email protected]("sentinel", [None, "{root}/gone", "1", "{root}/state/facts.json"],
- ids=["cold", "dangling", "legacy-1", "no-stamps"])
-def test_unusable_sentinel_activates(checkout: Path, sentinel: str | None):
- """Cold, dangling, or incomplete activation state must not read as current."""
- assert "ACTIVATED" in _run(checkout, sentinel)
diff --git a/tests/scripts/test_run_in_hermes_env.py b/tests/scripts/test_run_in_hermes_env.py
new file mode 100644
index 00000000000..552c32b0a29
--- /dev/null
+++ b/tests/scripts/test_run_in_hermes_env.py
@@ -0,0 +1,179 @@
+"""``scripts/run-in-hermes-env``: run a command in the Hermes environment, syncing only when needed.
+
+The runner is what repo scripts hand themselves to from their shebang and what
+``scripts/run_tests.sh`` re-executes under. Its decision worth pinning is
+staleness: pm stamps each dependency input's mtime beside the installed-state
+file ``__HERMES_ACTIVATED`` names, and any input whose mtime differs from its
+stamp means the inherited environment may not match its inputs. Invert that
+either way and the cost is invisible — a re-sync on every run, or a stale
+environment that looks fine.
+
+The stamps come from the real ``pm.environments`` writer, so these tests pin
+the contract between what pm records and what the runner reads. Setup and the
+pm environment reader are stubbed at their process boundary: setup announces
+each run, the reader emits a sentinel and a PATH shim.
+
+A ``python3`` shim goes on PATH because scripts run under the runner name
+``python3``, which does not exist on stock Windows; the subject here is the
+staleness branch, not interpreter resolution.
+"""
+
+from __future__ import annotations
+
+import datetime
+import os
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+from pm.environments import ACTIVATION_INPUTS, activation_input_mtimes, record_activation_inputs
+from tests.pm.activation_support import bash, posix
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+RUNNER = REPO_ROOT / "scripts" / "run-in-hermes-env"
+
+EARLIER = "2018-01-01 00:00:00"
+LONG_AGO = "2019-01-01 00:00:00"
+STAMP_TIME = "2020-06-01 00:00:00"
+JUST_AFTER = "2021-01-01 00:00:00"
+
+
+def _set_mtime(path: Path, stamp: str) -> None:
+ when = datetime.datetime.strptime(stamp, "%Y-%m-%d %H:%M:%S").timestamp()
+ os.utime(path, (when, when))
+
+
+def _shim(path: Path) -> None:
+ """Quote in posix form: a /bin/sh script treats backslashes in an unquoted
+ word as escapes (same pattern as tests/pm/activation_support.py)."""
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("#!/bin/sh\nexec '%s' \"$@\"\n" % posix(Path(sys.executable)), encoding="utf-8")
+ path.chmod(0o755)
+
+
+def checkout(tmp_path: Path) -> Path:
+ """A repo-shaped tree whose stub setup announces each run; its installed
+ state lives in ``state/`` (facts.json beside the input stamps)."""
+ root = tmp_path / "checkout"
+ (root / "scripts").mkdir(parents=True)
+ (root / "pm").mkdir()
+ (root / "state").mkdir()
+ for name in (RUNNER.name, "_activation.sh"):
+ shutil.copy2(REPO_ROOT / "scripts" / name, root / "scripts" / name)
+ for name in ACTIVATION_INPUTS:
+ (root / name).parent.mkdir(parents=True, exist_ok=True)
+ (root / name).touch()
+ _set_mtime(root / name, LONG_AGO)
+ (root / "state" / "facts.json").touch()
+ _set_mtime(root / "state" / "facts.json", STAMP_TIME)
+
+ _shim(root / "shim" / "python3")
+ _shim(root / ".venv" / "bin" / "python") # the bootstrap interpreter that reads the pm env
+
+ (root / "setup-hermes.sh").write_text(
+ "echo SYNCED >&2\n"
+ f'test ! -e "{posix(root)}/fail"\n', encoding="utf-8",
+ )
+ (root / "pm" / "__init__.py").touch()
+ (root / "pm" / "environments.py").write_text(
+ "import sys\n"
+ "assert sys.argv[1:] == ['--format', 'sh'], sys.argv\n"
+ f"print(\"export __HERMES_ACTIVATED='{posix(root)}/state/facts.json'\")\n"
+ f"print('export PATH=\"{posix(root)}/shim:$PATH\"')\n",
+ encoding="utf-8",
+ )
+ return root
+
+
+def _record(root: Path, *, test_environment: bool = True) -> None:
+ """What a successful ``pm install`` leaves behind."""
+ record_activation_inputs(root / "state" / "inputs", activation_input_mtimes(root), root,
+ test_environment=test_environment)
+
+
+def _run_in(root: Path, *command: str, sentinel: str | None = "{root}/state/facts.json"):
+ """Drive the runner as a caller would; the shim dir is on PATH like any tool dir."""
+ env = {**os.environ, "PATH": f"{posix(root / 'shim')}{os.pathsep}{os.environ.get('PATH', '')}"}
+ env.pop("__HERMES_ACTIVATED", None)
+ if sentinel is not None:
+ env["__HERMES_ACTIVATED"] = sentinel.replace("{root}", posix(root))
+ return subprocess.run(
+ [bash(), posix(root / "scripts" / RUNNER.name), *command],
+ capture_output=True, text=True, cwd=posix(root), env=env, timeout=60,
+ )
+
+
+def _synced(root: Path, sentinel: str | None = "{root}/state/facts.json") -> bool:
+ run = _run_in(root, "true", sentinel=sentinel)
+ assert run.returncode == 0, run.stderr
+ return "SYNCED" in run.stderr
+
+
+def test_foreign_checkout_with_matching_input_times_resyncs(checkout: Path):
+ _record(checkout)
+ other = checkout.parent / "other"
+ shutil.copytree(checkout, other, copy_function=shutil.copy2)
+ assert _synced(other, str(checkout / "state" / "facts.json"))
+
+
+def test_recorded_inputs_are_left_alone(checkout: Path):
+ """A checkout rewrote every input after facts.json was last written, then a
+ no-op sync recorded them: the environment is current. Re-syncing on every
+ run is the cost of getting this wrong."""
+ for name in ACTIVATION_INPUTS:
+ _set_mtime(checkout / name, JUST_AFTER)
+ _record(checkout)
+ assert not _synced(checkout)
+
+
+def test_install_that_skipped_the_test_environment_is_stale(checkout: Path):
+ """Every environment the runner hands out includes the test environment,
+ which a plain runtime install cannot mark current."""
+ marker = checkout / "state" / "inputs" / ".test-environment"
+ _record(checkout)
+ assert marker.is_file()
+ _record(checkout, test_environment=False)
+ assert not marker.exists()
+ assert _synced(checkout)
+
+
[email protected]("moved_to", [JUST_AFTER, EARLIER], ids=["newer", "older"])
[email protected]("input_name", ACTIVATION_INPUTS)
+def test_input_mtime_differing_from_its_stamp_resyncs(checkout: Path, input_name: str, moved_to: str):
+ """A branch switch can move an input's mtime either way; both mean the
+ recorded install was not verified against what is on disk now."""
+ _record(checkout)
+ _set_mtime(checkout / input_name, moved_to)
+ assert _synced(checkout)
+
+
[email protected]("sentinel", [None, "{root}/gone", "1", "{root}/state/facts.json"],
+ ids=["cold", "dangling", "legacy-1", "no-stamps"])
+def test_unusable_sentinel_syncs(checkout: Path, sentinel: str | None):
+ """Cold, dangling, or incomplete activation state must not read as current."""
+ assert _synced(checkout, sentinel)
+
+
+def test_command_runs_in_the_environment_with_its_arguments_and_exit_status(checkout: Path):
+ run = _run_in(checkout, "bash", "-c", 'echo "$__HERMES_ACTIVATED|$0|$1|$2"; exit 7', "zero", "b c", "d",
+ sentinel=None)
+ assert run.returncode == 7, run.stderr
+ assert run.stdout.strip() == f"{posix(checkout)}/state/facts.json|zero|b c|d"
+
+
+def test_failed_sync_runs_nothing(checkout: Path):
+ (checkout / "fail").touch()
+ ran = checkout / "ran"
+ run = _run_in(checkout, "touch", posix(ran), sentinel=None)
+ assert run.returncode != 0
+ assert not ran.exists()
+
+
+def test_no_command_is_a_usage_error(checkout: Path):
+ run = _run_in(checkout, sentinel=None)
+ assert run.returncode == 2
+ assert "usage" in run.stderr
diff --git a/website/docs/reference/package-management.md b/website/docs/reference/package-management.md
index fecdbddb144..f93d91a8310 100644
--- a/website/docs/reference/package-management.md
+++ b/website/docs/reference/package-management.md
@@ -342,6 +342,17 @@ Start in a clean shell rather than nesting this inside another venv.
and removes the function and the prompt prefix.
It does not uninstall packages or stop processes that you started.
+To run one command or script in that environment without activating a shell,
+prefix it with `scripts/run-in-hermes-env`. It applies the same environment to
+that command only, syncing first when there is none to inherit or the inherited
+one is stale, and leaves your shell untouched. `scripts/run_tests.sh` re-runs
+itself this way, and the repo's Python scripts hand themselves to it from their
+shebang.
+
+```bash
+scripts/run-in-hermes-env python scripts/release.py --help
+```
+
Verify the interpreter and source before doing work:
```bash