"""Hashing, environment facts and small helpers shared by the harness.""" import hashlib import json import os import platform import subprocess REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) def sha256_bytes(data): return "sha256:" + hashlib.sha256(data).hexdigest() def sha256_text(text): return sha256_bytes(text.encode("utf-8")) def sha256_path(path): """Hash of a file, or of a directory tree (sorted relative paths and contents).""" h = hashlib.sha256() if os.path.isfile(path): with open(path, "rb") as f: h.update(f.read()) return "sha256:" + h.hexdigest() for root, dirs, files in os.walk(path): dirs[:] = sorted(d for d in dirs if d not in (".git", "__pycache__")) for name in sorted(files): full = os.path.join(root, name) rel = os.path.relpath(full, path) h.update(rel.encode() + b"\0") with open(full, "rb") as f: h.update(f.read()) h.update(b"\0") return "sha256:" + h.hexdigest() def git_commit(path=REPO): """`` or `+dirty` for the repository containing `path`.""" try: rev = subprocess.run(["git", "-C", path, "rev-parse", "HEAD"], capture_output=True, text=True, check=True).stdout.strip() dirty = subprocess.run(["git", "-C", path, "status", "--porcelain"], capture_output=True, text=True, check=True).stdout.strip() return rev + ("+dirty" if dirty else "") except (OSError, subprocess.CalledProcessError): return None def hardware(): info = {"machine": platform.machine(), "system": platform.system(), "release": platform.release(), "cpus": os.cpu_count()} try: with open("/proc/cpuinfo") as f: for line in f: if line.startswith("model name"): info["cpu"] = line.split(":", 1)[1].strip() break with open("/proc/meminfo") as f: info["mem_kb"] = int(f.readline().split()[1]) except OSError: pass return info def write_json(path, obj): with open(path, "w") as f: json.dump(obj, f, indent=2, sort_keys=True) f.write("\n") def read_json(path): with open(path) as f: return json.load(f) def estimate_tokens(nbytes): """Rough token estimate for byte counts the provider does not report (documentation inspected); flagged as an estimate in records.""" return (nbytes + 3) // 4