omega-helix
This project has not described itself yet.
Brought by drakestapleton
omega-helix / tools / commons / pkg.py
| 1 | """DNA Commons / Cognitive Package Manager for signed OLLMSP01 `.sp` Merkle packs. |
| 2 | |
| 3 | Python 3 standard library only — zero third-party deps. |
| 4 | """ |
| 5 | |
| 6 | from __future__ import annotations |
| 7 | |
| 8 | import datetime |
| 9 | import json |
| 10 | import os |
| 11 | import shutil |
| 12 | import struct |
| 13 | import sys |
| 14 | from pathlib import Path |
| 15 | from typing import Any |
| 16 | |
| 17 | TOOLS_DIR = Path(__file__).resolve().parents[1] |
| 18 | for _p in (str(TOOLS_DIR), str(TOOLS_DIR / "openwaldo"), str(TOOLS_DIR / "distill")): |
| 19 | if _p not in sys.path: |
| 20 | sys.path.insert(0, _p) |
| 21 | |
| 22 | import openwaldo_bridge as ow_bridge # noqa: E402 |
| 23 | from distill.harvest import fnv1a64 # noqa: E402 |
| 24 | |
| 25 | |
| 26 | def _utc_now() -> str: |
| 27 | return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") |
| 28 | |
| 29 | |
| 30 | def read_sp_meta(sp_path: str | Path) -> dict[str, Any]: |
| 31 | """Parse and cryptographically verify an OLLMSP01 specialist pack header + payload FNV-1a.""" |
| 32 | p = Path(sp_path).expanduser().resolve() |
| 33 | raw = p.read_bytes() |
| 34 | if len(raw) < 48 or raw[:8] != b"OLLMSP01": |
| 35 | raise ValueError(f"{p}: invalid OLLMSP01 magic/header") |
| 36 | base_l, spec_l, base_hash, n_spec, pack_hash = struct.unpack("<5Q", raw[8:48]) |
| 37 | want_sz = 48 + 8 * n_spec |
| 38 | if len(raw) != want_sz: |
| 39 | raise ValueError(f"{p}: payload length mismatch (got {len(raw)}, expected {want_sz})") |
| 40 | got_fnv = fnv1a64(raw[48:]) |
| 41 | if got_fnv != pack_hash: |
| 42 | raise ValueError(f"{p}: OLLMSP01 payload FNV-1a mismatch (got {got_fnv:016x}, expected {pack_hash:016x})") |
| 43 | sha, size = ow_bridge.file_sha256_and_bytes(p) |
| 44 | return { |
| 45 | "magic": "OLLMSP01", |
| 46 | "path": str(p), |
| 47 | "sha256": sha, |
| 48 | "bytes": size, |
| 49 | "base_L": base_l, |
| 50 | "spec_L": spec_l, |
| 51 | "base_hash": f"{base_hash:016x}", |
| 52 | "n_spec_params": n_spec, |
| 53 | "pack_hash": f"{pack_hash:016x}", |
| 54 | } |
| 55 | |
| 56 | |
| 57 | def _load_registry(registry_dir: Path) -> dict[str, Any]: |
| 58 | idx_path = registry_dir / "registry.json" |
| 59 | if idx_path.is_file(): |
| 60 | return json.loads(idx_path.read_text(encoding="utf-8")) |
| 61 | return {"kind": "omega-helix-dna-commons", "schema": 1, "packages": {}} |
| 62 | |
| 63 | |
| 64 | def _write_json_atomic(path: Path, doc: dict[str, Any]) -> None: |
| 65 | path.parent.mkdir(parents=True, exist_ok=True) |
| 66 | tmp = path.with_name("." + path.name + ".tmp") |
| 67 | tmp.write_text(json.dumps(doc, indent=2) + "\n", encoding="utf-8") |
| 68 | os.replace(tmp, path) |
| 69 | |
| 70 | |
| 71 | def publish_pack( |
| 72 | sp_path: str | Path, |
| 73 | name: str, |
| 74 | *, |
| 75 | registry_dir: str | Path, |
| 76 | version: str = "0.1.0", |
| 77 | license_id: str = "Apache-2.0", |
| 78 | description: str = "", |
| 79 | ) -> dict[str, Any]: |
| 80 | """Publish a verified OLLMSP01 `.sp` pack into a content-addressed DNA Commons registry.""" |
| 81 | meta = read_sp_meta(sp_path) |
| 82 | reg_dir = Path(registry_dir).expanduser().resolve() |
| 83 | blobs_dir = reg_dir / "blobs" |
| 84 | blobs_dir.mkdir(parents=True, exist_ok=True) |
| 85 | blob_path = blobs_dir / f"{meta['sha256']}.sp" |
| 86 | shutil.copy2(meta["path"], blob_path) |
| 87 | |
| 88 | reg = _load_registry(reg_dir) |
| 89 | entry = { |
| 90 | "name": name, |
| 91 | "version": version, |
| 92 | "license": license_id, |
| 93 | "description": description, |
| 94 | "sha256": meta["sha256"], |
| 95 | "bytes": meta["bytes"], |
| 96 | "base_L": meta["base_L"], |
| 97 | "spec_L": meta["spec_L"], |
| 98 | "base_hash": meta["base_hash"], |
| 99 | "n_spec_params": meta["n_spec_params"], |
| 100 | "pack_hash": meta["pack_hash"], |
| 101 | "blob_rel": f"blobs/{meta['sha256']}.sp", |
| 102 | "published_at": _utc_now(), |
| 103 | } |
| 104 | reg["packages"][name] = entry |
| 105 | _write_json_atomic(reg_dir / "registry.json", reg) |
| 106 | return entry |
| 107 | |
| 108 | |
| 109 | def search_packs( |
| 110 | registry_dir: str | Path, |
| 111 | *, |
| 112 | query: str = "", |
| 113 | base_hash: str = "", |
| 114 | ) -> list[dict[str, Any]]: |
| 115 | """Search packages in a local DNA Commons registry by keyword and/or base_hash pin.""" |
| 116 | reg_dir = Path(registry_dir).expanduser().resolve() |
| 117 | reg = _load_registry(reg_dir) |
| 118 | q = query.strip().lower() |
| 119 | bh = base_hash.strip().lower() |
| 120 | out: list[dict[str, Any]] = [] |
| 121 | for entry in reg.get("packages", {}).values(): |
| 122 | if bh and str(entry.get("base_hash", "")).lower() != bh: |
| 123 | continue |
| 124 | if q: |
| 125 | hay = f"{entry.get('name', '')} {entry.get('description', '')} {entry.get('license', '')}".lower() |
| 126 | if q not in hay: |
| 127 | continue |
| 128 | out.append(entry) |
| 129 | out.sort(key=lambda x: str(x.get("name", ""))) |
| 130 | return out |
| 131 | |
| 132 | |
| 133 | def install_pack( |
| 134 | name: str, |
| 135 | env_dir: str | Path, |
| 136 | *, |
| 137 | registry_dir: str | Path, |
| 138 | expected_base_hash: str | None = None, |
| 139 | ) -> dict[str, Any]: |
| 140 | """Install a `.sp` pack from the Commons after fail-closed SHA-256, FNV-1a, and base_hash checks.""" |
| 141 | reg_dir = Path(registry_dir).expanduser().resolve() |
| 142 | reg = _load_registry(reg_dir) |
| 143 | entry = reg.get("packages", {}).get(name) |
| 144 | if not entry: |
| 145 | raise ValueError(f"package {name!r} not found in registry {reg_dir}") |
| 146 | |
| 147 | blob_path = reg_dir / entry["blob_rel"] |
| 148 | if not blob_path.is_file(): |
| 149 | raise FileNotFoundError(f"missing registry blob {blob_path}") |
| 150 | meta = read_sp_meta(blob_path) |
| 151 | if meta["sha256"] != entry["sha256"] or meta["pack_hash"] != entry["pack_hash"]: |
| 152 | raise ValueError(f"{name}: blob digest mismatch against registry entry") |
| 153 | if expected_base_hash is not None and meta["base_hash"].lower() != expected_base_hash.strip().lower(): |
| 154 | raise ValueError( |
| 155 | f"{name}: base_hash mismatch (pack pinned to {meta['base_hash']}, expected {expected_base_hash})" |
| 156 | ) |
| 157 | |
| 158 | env = Path(env_dir).expanduser().resolve() |
| 159 | packs_dir = env / "packs" |
| 160 | packs_dir.mkdir(parents=True, exist_ok=True) |
| 161 | dest = packs_dir / f"{name}.sp" |
| 162 | shutil.copy2(blob_path, dest) |
| 163 | |
| 164 | mpath = env / "manifest.json" |
| 165 | manifest = json.loads(mpath.read_text(encoding="utf-8")) if mpath.is_file() else {"installed": {}} |
| 166 | manifest["installed"][name] = {**entry, "installed_path": str(dest), "installed_at": _utc_now()} |
| 167 | _write_json_atomic(mpath, manifest) |
| 168 | return manifest["installed"][name] |
| 169 | |
| 170 | |
| 171 | def revoke_pack( |
| 172 | name: str, |
| 173 | env_dir: str | Path, |
| 174 | *, |
| 175 | reason: str = "right-to-be-forgotten", |
| 176 | ) -> dict[str, Any]: |
| 177 | """Delete an installed `.sp` pack and append an immutable cryptographic revocation record.""" |
| 178 | env = Path(env_dir).expanduser().resolve() |
| 179 | mpath = env / "manifest.json" |
| 180 | manifest = json.loads(mpath.read_text(encoding="utf-8")) if mpath.is_file() else {"installed": {}} |
| 181 | removed = manifest.get("installed", {}).pop(name, None) |
| 182 | dest = env / "packs" / f"{name}.sp" |
| 183 | file_deleted = False |
| 184 | if dest.is_file(): |
| 185 | dest.unlink() |
| 186 | file_deleted = True |
| 187 | _write_json_atomic(mpath, manifest) |
| 188 | |
| 189 | rev_rec = { |
| 190 | "name": name, |
| 191 | "revoked_at": _utc_now(), |
| 192 | "reason": reason, |
| 193 | "removed_entry": removed, |
| 194 | "file_deleted": file_deleted, |
| 195 | } |
| 196 | rev_path = env / "revocations.jsonl" |
| 197 | rev_path.parent.mkdir(parents=True, exist_ok=True) |
| 198 | with rev_path.open("a", encoding="utf-8") as f: |
| 199 | f.write(json.dumps(rev_rec) + "\n") |
| 200 | return rev_rec |
| 201 | |
| 202 | |
| 203 | def diff_packs(sp_a: str | Path, sp_b: str | Path) -> dict[str, Any]: |
| 204 | """Compare two OLLMSP01 specialist packs' Merkle roots, shapes, and hashes.""" |
| 205 | a = read_sp_meta(sp_a) |
| 206 | b = read_sp_meta(sp_b) |
| 207 | return { |
| 208 | "same_base_hash": a["base_hash"] == b["base_hash"], |
| 209 | "same_pack": a["sha256"] == b["sha256"], |
| 210 | "same_base_L": a["base_L"] == b["base_L"], |
| 211 | "same_spec_L": a["spec_L"] == b["spec_L"], |
| 212 | "a": a, |
| 213 | "b": b, |
| 214 | } |