Publish Foundry Preview (foundry-001-dev-00 & foundry-002-dev-00 Harbor 0.26 bundles, allowlisted verifier, 3-lab calibration)
fe0ff58 verified Download preview/core/pack_registry.py from zero-trust-physics/zero-trust-physics-foundry-preview: direct link, hf CLI and curl.
- Browser
- Download file 9.56 kB
-
https://huggingface.co/datasets/zero-trust-physics/zero-trust-physics-foundry-preview/resolve/main/preview/core/pack_registry.py
- Command line
-
hf download hf://datasets/zero-trust-physics/zero-trust-physics-foundry-preview/preview/core/pack_registry.py
-
curl -L -o pack_registry.py https://huggingface.co/datasets/zero-trust-physics/zero-trust-physics-foundry-preview/resolve/main/preview/core/pack_registry.py
9.56 kB
| """Manifest-driven Pack Registry & Dynamic Task/Plugin Loader.""" | |
| from __future__ import annotations | |
| import importlib.util | |
| import json | |
| import os | |
| import sys | |
| from typing import Any | |
| CORE_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| LAB_ROOT = os.path.dirname(CORE_DIR) | |
| PACK_ROOT_CANDIDATES = ( | |
| os.path.join(LAB_ROOT, "packs"), | |
| "/root/ztp_packs", | |
| ) | |
| def resolve_pack_dir(pack_name: str = "flagship_monolith_30", pack_dir: str | None = None) -> str: | |
| """Locate a pack directory on host or inside an air-gapped Docker container.""" | |
| if pack_dir and os.path.isdir(pack_dir): | |
| return os.path.abspath(pack_dir) | |
| env_dir = os.environ.get("ZTP_PACK_DIR") | |
| if env_dir and os.path.isdir(env_dir): | |
| return os.path.abspath(env_dir) | |
| for base in PACK_ROOT_CANDIDATES: | |
| cand = os.path.join(base, pack_name) | |
| if os.path.isdir(cand): | |
| return os.path.abspath(cand) | |
| raise FileNotFoundError(f"Could not locate pack {pack_name!r} in {PACK_ROOT_CANDIDATES}") | |
| def load_pack_manifest(pack_name: str = "flagship_monolith_30", pack_dir: str | None = None) -> tuple[str, dict[str, Any]]: | |
| """Load `pack_manifest.json` and return `(pack_dir, manifest_dict)`.""" | |
| pdir = resolve_pack_dir(pack_name=pack_name, pack_dir=pack_dir) | |
| mpath = os.path.join(pdir, "pack_manifest.json") | |
| with open(mpath, "r", encoding="utf-8") as fh: | |
| manifest = json.load(fh) | |
| return pdir, manifest | |
| # Default runtime: the frozen 0.15.3 monument binaries in `genesis_lab/bin/<arch>/`. | |
| # A pack overrides it with a `runtime` block in `pack_manifest.json`, e.g. Foundry: | |
| # "runtime": {"engine": {"name": "ztp_foundry_mcp", "bin_root": "foundry_engine/bin"}, | |
| # "vault_bins": [{"name": "ztp_foundry_verifier", "bin_root": "foundry_engine/bin"}]} | |
| # `engine` is the MCP stdio binary the root daemon serves to the agent (component tools only). | |
| # `vault_bins` are root-only binaries: never on the agent's tool surface, run by plant | |
| # plugins inside the daemon (stateful probes) and by evaluators inside the root verifier. | |
| # `bin_root` is relative to `genesis_lab/` and holds `<arch>/<name>` for linux-arm64 and | |
| # linux-amd64 (exported into containers) and optionally macos-arm64 (host runs). | |
| DEFAULT_RUNTIME: dict[str, Any] = { | |
| "engine": {"name": "mcp_stdio", "bin_root": "bin"}, | |
| "vault_bins": [{"name": "genesis_seal", "bin_root": "bin"}], | |
| } | |
| def load_pack_runtime(pack_name: str = "flagship_monolith_30", pack_dir: str | None = None) -> dict[str, Any]: | |
| """Return the pack's runtime binaries (`engine` + `vault_bins`), defaulting to the monument set.""" | |
| _pdir, manifest = load_pack_manifest(pack_name=pack_name, pack_dir=pack_dir) | |
| raw = dict(manifest.get("runtime") or {}) | |
| # Foundry-style manifests name the binaries as `<bin_root>/{arch}/<name>` paths instead. | |
| for key, slot in (("engine_mcp_rel", "engine"), ("verifier_bin_rel", "vault_bins")): | |
| rel = manifest.get(key) | |
| if not rel: | |
| continue | |
| rel = str(rel) | |
| if "/{arch}/" not in rel: | |
| raise ValueError(f"{key}={rel!r} in pack {pack_name!r} must look like '<bin_root>/{{arch}}/<name>'") | |
| root, name = rel.split("/{arch}/", 1) | |
| ent = {"name": name, "bin_root": root} | |
| if slot == "engine": | |
| if "engine" in raw and raw["engine"] != ent: | |
| raise ValueError(f"pack {pack_name!r}: runtime.engine and {key} disagree") | |
| raw["engine"] = ent | |
| elif ent not in (raw.get("vault_bins") or []): | |
| raw["vault_bins"] = [*(raw.get("vault_bins") or []), ent] | |
| engine = dict(DEFAULT_RUNTIME["engine"]) | |
| engine.update(raw.get("engine") or {}) | |
| vault_bins = [dict(v) for v in (raw.get("vault_bins") if "vault_bins" in raw else DEFAULT_RUNTIME["vault_bins"])] | |
| for v in [engine, *vault_bins]: | |
| name = str(v.get("name") or "") | |
| if not name or "/" in name or name.startswith("."): | |
| raise ValueError(f"Invalid runtime binary name {name!r} in pack {pack_name!r}") | |
| v.setdefault("bin_root", "bin") | |
| prefix = manifest.get("engine_version_prefix") | |
| if prefix and "foundry" in str(prefix) and engine["name"] == DEFAULT_RUNTIME["engine"]["name"]: | |
| raise ValueError(f"pack {pack_name!r} expects engine {prefix!r} but names no Foundry engine binary") | |
| names = [engine["name"], *[v["name"] for v in vault_bins]] | |
| if len(set(names)) != len(names): | |
| raise ValueError(f"Duplicate runtime binary names in pack {pack_name!r}: {names}") | |
| return {"engine": engine, "vault_bins": vault_bins} | |
| def list_active_tasks( | |
| pack_name: str = "flagship_monolith_30", | |
| pack_dir: str | None = None, | |
| ) -> list[dict[str, Any]]: | |
| """Return active task records (with resolved `task_dir` and parsed `task.json`).""" | |
| pdir, manifest = load_pack_manifest(pack_name=pack_name, pack_dir=pack_dir) | |
| out: list[dict[str, Any]] = [] | |
| for entry in manifest.get("tasks", []): | |
| if entry.get("status", "active") != "active": | |
| continue | |
| tid = str(entry["task_id"]) | |
| rel = str(entry.get("rel_path") or os.path.join("tasks", tid)) | |
| tdir = os.path.join(pdir, rel) | |
| tjson = os.path.join(tdir, "task.json") | |
| if not os.path.isfile(tjson): | |
| continue | |
| with open(tjson, "r", encoding="utf-8") as fh: | |
| tspec = json.load(fh) | |
| out.append( | |
| { | |
| "task_id": tid, | |
| "task_dir": tdir, | |
| "pack_dir": pdir, | |
| "manifest_entry": entry, | |
| "task_spec": tspec, | |
| } | |
| ) | |
| return out | |
| def get_task_bundle( | |
| task_id: str, | |
| pack_name: str = "flagship_monolith_30", | |
| pack_dir: str | None = None, | |
| ) -> dict[str, Any]: | |
| """Resolve a single active task by ID.""" | |
| for item in list_active_tasks(pack_name=pack_name, pack_dir=pack_dir): | |
| if item["task_id"] == task_id: | |
| return item | |
| raise KeyError(f"Task {task_id!r} not found or not active in pack {pack_name!r}") | |
| def _import_module_from_path(module_name: str, file_path: str) -> Any: | |
| if LAB_ROOT not in sys.path: | |
| sys.path.insert(0, LAB_ROOT) | |
| spec = importlib.util.spec_from_file_location(module_name, file_path) | |
| if spec is None or spec.loader is None: | |
| raise ImportError(f"Could not load module {module_name} from {file_path}") | |
| mod = importlib.util.module_from_spec(spec) | |
| sys.modules[module_name] = mod | |
| spec.loader.exec_module(mod) | |
| return mod | |
| _ACTIVATED_TASK_DIRS: list[str] = [] | |
| def _activate_task_dir(task_dir: str) -> None: | |
| """Let a task's files import each other by bare name (`from plant import ...`). | |
| Puts `task_dir` first on `sys.path`, and drops any other task's directory together | |
| with the bare-name modules loaded from it, so a second task loaded in the same | |
| process never gets the first task's `plant`. | |
| """ | |
| tdir = os.path.abspath(task_dir) | |
| for old in _ACTIVATED_TASK_DIRS: | |
| if old == tdir: | |
| continue | |
| while old in sys.path: | |
| sys.path.remove(old) | |
| for name, mod in list(sys.modules.items()): | |
| mfile = getattr(mod, "__file__", None) | |
| if mfile and "." not in name and not name.startswith("ztp_task_") and os.path.dirname(os.path.abspath(mfile)) == old: | |
| del sys.modules[name] | |
| if tdir not in _ACTIVATED_TASK_DIRS: | |
| _ACTIVATED_TASK_DIRS.append(tdir) | |
| while tdir in sys.path: | |
| sys.path.remove(tdir) | |
| sys.path.insert(0, tdir) | |
| def load_task_evaluator(task_id: str, task_dir: str) -> Any: | |
| """Load `<task_dir>/evaluator.py` dynamically.""" | |
| ev_path = os.path.join(task_dir, "evaluator.py") | |
| if not os.path.isfile(ev_path): | |
| raise FileNotFoundError(f"Missing evaluator.py for {task_id} at {ev_path}") | |
| _activate_task_dir(task_dir) | |
| return _import_module_from_path(f"ztp_task_eval_{task_id.replace('-', '_')}", ev_path) | |
| def load_task_plant_plugin( | |
| task_id: str, | |
| task_dir: str, | |
| task_spec: dict[str, Any], | |
| engine_client: Any, | |
| vault: dict[str, Any] | None = None, | |
| ) -> Any | None: | |
| """Instantiate `<task_dir>/plant.py:create_plugin(...)` if `plant.py` exists.""" | |
| plant_path = os.path.join(task_dir, "plant.py") | |
| if not os.path.isfile(plant_path): | |
| return None | |
| _activate_task_dir(task_dir) | |
| mod = _import_module_from_path(f"ztp_task_plant_{task_id.replace('-', '_')}", plant_path) | |
| if hasattr(mod, "create_plugin"): | |
| return mod.create_plugin(task_spec=task_spec, engine_client=engine_client, vault=vault or {}) | |
| if hasattr(mod, "PlantPlugin"): | |
| return mod.PlantPlugin(task_spec=task_spec, engine_client=engine_client, vault=vault or {}) | |
| raise AttributeError(f"{plant_path} defines neither create_plugin nor PlantPlugin") | |
| def load_task_vault(task_id: str, vault_dir: str | None = None, pack_dir: str | None = None) -> dict[str, Any]: | |
| """Load root-only vault JSON for `task_id` if one exists (optional).""" | |
| candidates: list[str] = [] | |
| if vault_dir: | |
| candidates.append(os.path.join(vault_dir, f"{task_id}.json")) | |
| env_v = os.environ.get("ZTP_VAULT_DIR") | |
| if env_v: | |
| candidates.append(os.path.join(env_v, f"{task_id}.json")) | |
| candidates.append(f"/root/ztp_vault/{task_id}.json") | |
| if pack_dir: | |
| candidates.append(os.path.join(pack_dir, ".vault", f"{task_id}.json")) | |
| for p in candidates: | |
| if os.path.isfile(p): | |
| with open(p, "r", encoding="utf-8") as fh: | |
| return json.load(fh) | |
| return {} | |