Skip to content

The agent that grows with you

feat(pm): frozen bundle feature set — enabled-features.json

ethernet02eb115f606c
diff --git a/pm/cli.py b/pm/cli.py
index 52d3b8056ea..7dcd2b92965 100644
--- a/pm/cli.py
+++ b/pm/cli.py
@@ -614,6 +614,15 @@ def cmd_bundle(args) -> int:
return 1
print("✓ venv (relocatable, all extras, on the staged interpreter)")
+ # The frozen feature set: the EXACT extras that installed on this
+ # target (markers gate some off per-platform). This file is the
+ # lazy-off contract — pm sync never deviates from it.
+ from pm.features import installed_extras, write_features
+
+ features = installed_extras(repo_dir, venv_dir)
+ write_features(features, out)
+ print(f"✓ enabled-features.json ({len(features)} extras recorded)")
+
bad = _arch_guard(store_dir)
for line in bad:
print(f"✗ arch: {line}")
diff --git a/pm/ensure.py b/pm/ensure.py
index 88c26a79d48..46106b4b9f1 100644
--- a/pm/ensure.py
+++ b/pm/ensure.py
@@ -307,7 +307,24 @@ def sync_venv(extras: Optional[list[str]] = None, *, explicit: bool = False) ->
the installed state (one ledger); no-op when the stamp already matches.
``explicit`` marks a deliberate install command (`hermes pm install`,
`hermes update`) — those are the remedy the lazy-install policy points
- at, so the policy does not apply to them."""
+ at, so the policy does not apply to them.
+
+ Lazy installs OFF = the frozen feature set: when
+ security.allow_lazy_installs is false AND the bundle's
+ enabled-features.json exists, the feature list is FROZEN to that file
+ — requested extras outside it are refused, and plugin members are
+ never installed (the bundle IS the install)."""
+ from pm.features import read_features
+
+ frozen = read_features() if not lazy_installs_allowed() else None
+ if frozen is not None and extras:
+ outside = sorted(set(extras) - set(frozen))
+ if outside:
+ raise _refuse_lazy(
+ "venv",
+ f"extras {outside} are outside this bundle's frozen feature "
+ "set (security.allow_lazy_installs is false)",
+ )
package = get_package("venv")
facts = _facts()
fact = facts.get("venv") or {}
diff --git a/pm/features.py b/pm/features.py
new file mode 100644
index 00000000000..51b274f293a
--- /dev/null
+++ b/pm/features.py
@@ -0,0 +1,111 @@
+"""The enabled-features file: the exact extras the install carries.
+
+The bundle is built with `uv sync --all-extras`, but WHICH extras
+actually resolve differs per platform (markers gate some off). The
+shipped default is the EXACT list that installed — written at bundle
+time beside the payload, read at sync time:
+
+- lazy installs OFF (security.allow_lazy_installs: false): the feature
+ list is FROZEN to this file; pm sync never deviates from it and never
+ installs a plugin dep.
+- lazy installs ON: the file is the baseline; extras union on top.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Optional
+
+FEATURES_FILENAME = "enabled-features.json"
+
+
+def features_path(base_dir: Optional[Path] = None) -> Path:
+ """Where the enabled-features file lives. In a bundle, the payload
+ root (beside manifest.json — bundle-written, sealed-shipped). At
+ runtime, the runtime dir (beside the byte store — per-install,
+ writable on every install kind). Same relative location on both:
+ a sealed install's store_root() is <payload>/tools, and the file
+ sits at the payload root = store_root().parent."""
+ if base_dir is not None:
+ return base_dir / FEATURES_FILENAME
+ from pm.paths import store_root
+
+ return store_root().parent / FEATURES_FILENAME
+
+
+def write_features(extras: list[str], base_dir: Optional[Path] = None) -> Path:
+ """Record the exact extras an install carries. Sorted, deduped."""
+ path = features_path(base_dir)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(
+ json.dumps({"schema": 1, "extras": sorted(set(extras))}, indent=2) + "\n",
+ encoding="utf-8",
+ )
+ return path
+
+
+def read_features() -> Optional[list[str]]:
+ """The frozen/baseline feature list; None when no file exists (source
+ installs without a bundle — the baseline is the recorded venv
+ state)."""
+ try:
+ data = json.loads(features_path().read_text(encoding="utf-8-sig"))
+ except (OSError, ValueError):
+ return None
+ extras = data.get("extras")
+ if not isinstance(extras, list):
+ return None
+ return sorted({str(e) for e in extras})
+
+
+def declared_extras(repo_dir: Path) -> list[str]:
+ """Every extra the repo's pyproject declares."""
+ import tomllib
+
+ with (repo_dir / "pyproject.toml").open("rb") as f:
+ data = tomllib.load(f)
+ return sorted(data.get("project", {}).get("optional-dependencies", {}))
+
+
+def installed_extras(repo_dir: Path, venv_dir: Path) -> list[str]:
+ """The extras that ACTUALLY installed on this target: every declared
+ extra whose pm anchor import resolves in the venv. Markers-gated
+ extras show up as missing anchors — the honest per-target record of
+ what `uv sync --all-extras` put on THIS machine."""
+ from pm.extras import ANCHORS
+
+ installed: list[str] = []
+ for extra in declared_extras(repo_dir):
+ anchor = ANCHORS.get(extra, extra.replace("-", "_"))
+ if isinstance(anchor, str):
+ anchor = (anchor,)
+ if all(_importable_in(anchor_member, venv_dir) for anchor_member in anchor):
+ installed.append(extra)
+ return sorted(installed)
+
+
+def _importable_in(anchor: str, venv_dir: Path) -> bool:
+ """Does the anchor import resolve inside venv_dir's site-packages?"""
+ import importlib.util
+ import sys
+ import sysconfig
+ from pathlib import Path as _P
+
+ sites = set()
+ pure = sysconfig.get_paths(vars={"base": str(venv_dir)}).get("purelib")
+ if pure:
+ sites.add(_P(pure))
+ plat = sysconfig.get_paths(vars={"base": str(venv_dir)}).get("platlib")
+ if plat:
+ sites.add(_P(plat))
+
+ saved = list(sys.path)
+ try:
+ sys.path = [str(s) for s in sites]
+ try:
+ return importlib.util.find_spec(anchor) is not None
+ except (ImportError, ValueError):
+ return False
+ finally:
+ sys.path = saved
diff --git a/pm/packages.py b/pm/packages.py
index 090b6c24a42..887119a357a 100644
--- a/pm/packages.py
+++ b/pm/packages.py
@@ -316,6 +316,20 @@ class Venv(StatePackage):
member_dirs = enabled_member_dirs()
if member_dirs:
+ # Lazy installs OFF = the frozen bundle feature set: plugin
+ # members are never installed (the bundle IS the install).
+ from pm.ensure import lazy_installs_allowed
+
+ if not lazy_installs_allowed():
+ from pm.features import read_features
+
+ if read_features() is not None:
+ raise InstallError(
+ self.name,
+ "plugin members present but lazy installs are "
+ "disabled — this bundle's feature set is frozen "
+ "(remove the plugin or enable lazy installs)",
+ )
# Plugin deps union into the venv through the generated
# workspace root (one lock, conflict = loud refusal).
lock_and_sync(member_dirs, extras, venv_dir=self.venv_dir())
diff --git a/tests/pm/test_features.py b/tests/pm/test_features.py
new file mode 100644
index 00000000000..8c37904ccae
--- /dev/null
+++ b/tests/pm/test_features.py
@@ -0,0 +1,111 @@
+"""pm.features: the frozen bundle feature set (enabled-features.json).
+
+Lazy installs OFF = the bundle's feature list is FROZEN to the file the
+bundle wrote (the EXACT extras that installed on that target); pm sync
+never deviates and never installs a plugin member.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+import pm.features as feats
+
+
+def rooted(tmp_path, monkeypatch):
+ """Point features_path at a temp runtime dir (store_root().parent)."""
+ store = tmp_path / "tools"
+ store.mkdir()
+ monkeypatch.setattr(
+ feats,
+ "features_path",
+ lambda base=None: (base if base is not None else store.parent)
+ / feats.FEATURES_FILENAME,
+ )
+ return tmp_path
+
+
+def test_write_then_read_roundtrip(rooted):
+ path = feats.write_features(["web", "acp", "web"])
+ assert path.is_file()
+ got = feats.read_features()
+ assert got == ["acp", "web"] # sorted, deduped
+
+
+def test_read_features_none_when_absent(rooted):
+ assert feats.read_features() is None
+
+
+def test_read_features_none_on_garbage(rooted):
+ feats.features_path().write_text("{ not json", encoding="utf-8")
+ assert feats.read_features() is None
+
+
+def test_features_path_in_bundle_uses_payload_root(rooted):
+ payload = rooted / "payload"
+ payload.mkdir()
+ assert feats.features_path(payload) == payload / "enabled-features.json"
+
+
+def test_installed_extras_reports_only_anchor_resolved(tmp_path, monkeypatch):
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ (repo / "pyproject.toml").write_text(
+ "[project]\n"
+ 'name = "hermes-agent"\n'
+ "[project.optional-dependencies]\n"
+ 'present = ["x"]\n'
+ 'absent = ["y"]\n',
+ encoding="utf-8",
+ )
+ venv = tmp_path / "venv"
+ site = venv / "Lib" / "site-packages"
+ site.mkdir(parents=True)
+ (site / "somepkg.py").write_text("x = 1\n", encoding="utf-8")
+
+ import pm.extras as extras_mod
+
+ monkeypatch.setattr(
+ extras_mod,
+ "ANCHORS",
+ {**extras_mod.ANCHORS, "present": "somepkg", "absent": "missingmod"},
+ )
+ got = feats.installed_extras(repo, venv)
+ assert "present" in got
+ assert "absent" not in got
+
+
+def test_sync_venv_refuses_outside_frozen_extras(rooted, monkeypatch):
+ feats.write_features(["web", "acp"])
+
+ import sys
+
+ ensure_mod = sys.modules["pm.ensure"]
+ from pm.package import InstallError
+
+ monkeypatch.setattr(ensure_mod, "lazy_installs_allowed", lambda: False)
+ with pytest.raises(InstallError) as exc:
+ ensure_mod.sync_venv(["slack"], explicit=True)
+ assert "frozen" in str(exc.value) or "outside" in str(exc.value)
+
+
+def test_sync_venv_allows_frozen_extras_when_lazy_off(rooted, monkeypatch):
+ feats.write_features(["web"])
+
+ import sys
+
+ ensure_mod = sys.modules["pm.ensure"]
+
+ # lazy off, request within the frozen set: passes the gate (may still
+ # no-op on the stamp — we only assert no refusal here, by making the
+ # stamp match so sync_venv returns early)
+ monkeypatch.setattr(ensure_mod, "lazy_installs_allowed", lambda: False)
+ venv_pkg = ensure_mod.get_package("venv")
+ monkeypatch.setattr(
+ venv_pkg, "expected_stamp", lambda extras: "stamp"
+ )
+ monkeypatch.setattr(ensure_mod, "_facts", lambda: {"venv": {"stamp": "stamp", "extras": ["web"]}})
+ ensure_mod.sync_venv(["web"]) # no raise