#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 # © 2026 Lutar, Stephen P. — SZL Holdings """ publish_harness_run.py — FAIL-CLOSED publisher for anatomy alive-harness runs. Pipeline (any failure aborts the publish — nothing unsigned or unverified is ever uploaded): 1. Read the evidence JSON produced by anatomy_alive_v6.py. 2. Build a compact run record (counts DERIVED from the assertion list — recomputed here, not trusted from the summary fields). 3. Ask the live Hatun MCP gateway to DSSE-sign the record (tools/call dsse_sign). The gateway signs with the org ECDSA-P256 key; a PLACEHOLDER response aborts the publish. 4. Verify the returned envelope locally against the COMMITTED public key (hatun-mcp/main/PUBKEY_szlholdings-ec-p256.pem) over DSSE PAE v1. 5. Append the signed record to harness_runs.jsonl in the public SZLHOLDINGS/test-results dataset and upload evidence + envelope files. Usage: HF_TOKEN=... python3 publish_harness_run.py evidence.json """ from __future__ import annotations import base64 import hashlib import json import os import re import sys from datetime import datetime, timezone import httpx from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ec HATUN = "https://szlholdings-hatun-mcp.hf.space" PUBKEY_URL = "https://raw.githubusercontent.com/szl-holdings/hatun-mcp/main/PUBKEY_szlholdings-ec-p256.pem" DATASET = "SZLHOLDINGS/test-results" HF = "https://huggingface.co" def die(msg: str) -> None: print(f"FAIL-CLOSED: {msg}", file=sys.stderr) sys.exit(1) def main() -> None: token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_API_TOKEN") if not token: die("no HF token in env (HF_TOKEN)") token = token.strip() evidence_path = sys.argv[1] if len(sys.argv) > 1 else "evidence.json" with open(evidence_path) as f: evidence = json.load(f) # 2. derive counts from the raw assertion records (never trust summaries) assertions = evidence.get("assertions") or die("evidence has no assertions") passed = sum(1 for a in assertions if a.get("status") == "PASS") total = len(assertions) gates = [a for a in assertions if a["layer"] == "L2-GATES" and a["assertion"].startswith("live gate ")] gate_pass = sum(1 for a in gates if a["status"] == "PASS") evidence_bytes = json.dumps(evidence, sort_keys=True, separators=(",", ":")).encode() run = { "record": "szl.anatomy-alive-harness.run", "schema": 1, "harness_version": evidence.get("version"), "startedAt": evidence.get("startedAt"), "finishedAt": evidence.get("finishedAt"), "assertions_passed": passed, "assertions_total": total, "verdict": "GREEN" if passed == total else "PARTIAL", "formula_gates_passed": gate_pass, "formula_gates_total": len(gates), "evidence_sha256": hashlib.sha256(evidence_bytes).hexdigest(), "publishedAt": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), } payload = json.dumps(run, sort_keys=True, separators=(",", ":")) client = httpx.Client(timeout=30.0, follow_redirects=True) # 3. gateway DSSE signature r = client.post(f"{HATUN}/mcp/", json={ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "dsse_sign", "arguments": {"payload": payload}}, }, headers={"Accept": "application/json, text/event-stream"}) m = re.search(r"data: (\{.*\})", r.text) body = json.loads(m.group(1)) if m else json.loads(r.text) inner = json.loads(body["result"]["content"][0]["text"]) if inner.get("honesty") != "REAL" or inner.get("signer_mode") != "ECDSA-P256": die(f"gateway signer not REAL ECDSA-P256 (mode={inner.get('signer_mode')})") env = inner["envelope"] # 4. local verification against the COMMITTED pubkey pub_pem = client.get(PUBKEY_URL).text pub = serialization.load_pem_public_key(pub_pem.encode()) signed_payload = base64.b64decode(env["payload"]) if json.loads(signed_payload) != run: die("signed payload does not round-trip to the run record") pae = b"DSSEv1 %d %s %d %s" % (len(env["payloadType"].encode()), env["payloadType"].encode(), len(signed_payload), signed_payload) sig = base64.b64decode(env["signatures"][0]["sig"]) try: pub.verify(sig, pae, ec.ECDSA(hashes.SHA256())) except Exception as e: die(f"signature does NOT verify against committed pubkey: {e}") print("signature verified against committed org pubkey — publishing") record_line = json.dumps({"run": run, "dsse": {k: env[k] for k in ("payloadType", "payload", "signatures")}}, sort_keys=True, separators=(",", ":")) # 5. upload (append-style: fetch existing jsonl, append, re-upload) H = {"Authorization": f"Bearer {token}"} existing = client.get(f"{HF}/datasets/{DATASET}/resolve/main/harness_runs.jsonl", headers=H) lines = existing.text.strip().split("\n") if existing.status_code == 200 and existing.text.strip() else [] lines.append(record_line) stamp = run["finishedAt"].replace(":", "").replace("-", "") files = { "harness_runs.jsonl": "\n".join(lines) + "\n", f"runs/{stamp}.evidence.json": json.dumps(evidence, indent=1), f"runs/{stamp}.dsse.json": json.dumps({k: env[k] for k in ("payloadType", "payload", "signatures")}, indent=1), } for path, content in files.items(): rr = client.post( f"{HF}/api/datasets/{DATASET}/commit/main", headers={**H, "Content-Type": "application/x-ndjson"}, content="\n".join([ json.dumps({"key": "header", "value": {"summary": f"harness run {run['finishedAt']} — {path}", "description": ""}}), json.dumps({"key": "file", "value": {"path": path, "encoding": "base64", "content": base64.b64encode(content.encode()).decode()}}), ]), ) if rr.status_code != 200: die(f"upload {path} failed: {rr.status_code} {rr.text[:300]}") print(f"uploaded {path}") # post-publish verify: re-download and re-verify the last record chk = client.get(f"{HF}/datasets/{DATASET}/resolve/main/harness_runs.jsonl", headers=H) last = json.loads(chk.text.strip().split("\n")[-1]) sp = base64.b64decode(last["dsse"]["payload"]) pae2 = b"DSSEv1 %d %s %d %s" % (len(last["dsse"]["payloadType"].encode()), last["dsse"]["payloadType"].encode(), len(sp), sp) pub.verify(base64.b64decode(last["dsse"]["signatures"][0]["sig"]), pae2, ec.ECDSA(hashes.SHA256())) print(f"post-publish re-verify OK — {DATASET} carries a DSSE-signed " f"{last['run']['verdict']} run ({last['run']['assertions_passed']}/{last['run']['assertions_total']})") if __name__ == "__main__": main()