# Copyright (c) 2026 CLSA contributors # SPDX-License-Identifier: MIT """Certificates: Cert(a_t) = . Every executed, clarified or abstained action writes exactly one certificate to an append-only, hash-chained ledger. Evaluation audits the ledger, never a transcript. If the writer is disabled the agent raises: an uncertified action is impossible by construction, not by convention. """ from __future__ import annotations import hashlib import json import os from pathlib import Path import jsonschema from clsa.util import ROOT, RESULTS, sha256_json, utc_now SCHEMA_PATH = ROOT / "schemas" / "certificate.schema.json" _VALIDATOR = None def _validator(): global _VALIDATOR if _VALIDATOR is None: with open(SCHEMA_PATH, "r", encoding="utf-8") as fh: sch = json.load(fh) cls = jsonschema.validators.validator_for(sch) cls.check_schema(sch) _VALIDATOR = cls(sch) return _VALIDATOR def _genesis_hash() -> str: return "0" * 64 class UncertifiedActionError(RuntimeError): """Raised when a decision is taken without a certificate writer.""" class CertificateLedger: """Append-only JSONL ledger with a hash chain over certificates.""" def __init__(self, path: str | Path | None = None, enabled: bool = True): RESULTS.mkdir(parents=True, exist_ok=True) self.path = Path(path) if path else RESULTS / "certificates.jsonl" self.enabled = enabled self._last_hash = _genesis_hash() if self.path.exists() and self.path.stat().st_size > 0: with open(self.path, "r", encoding="utf-8") as fh: for line in fh: line = line.strip() if line: self._last_hash = json.loads(line)["cert_hash"] def write(self, cert: dict) -> dict: if not self.enabled: raise UncertifiedActionError( "certificate writer disabled: refusing to execute an uncertified action" ) body = dict(cert) body["prev_hash"] = self._last_hash body["cert_hash"] = sha256_json({k: v for k, v in body.items() if k != "cert_hash"})[:32] errors = list(_validator().iter_errors(body)) if errors: raise ValueError(f"certificate failed schema validation: {errors[0].message}") with open(self.path, "a", encoding="utf-8") as fh: fh.write(json.dumps(body, sort_keys=True) + "\n") self._last_hash = body["cert_hash"] return body def read(self) -> list[dict]: if not self.path.exists(): return [] with open(self.path, "r", encoding="utf-8") as fh: return [json.loads(line) for line in fh if line.strip()] def verify_chain(self) -> tuple[bool, str]: prev = _genesis_hash() for cert in self.read(): body = {k: v for k, v in cert.items() if k != "cert_hash"} expect = sha256_json(body)[:32] if cert.get("prev_hash") != prev: return False, f"broken link at {cert.get('cert_id')}" if cert.get("cert_hash") != expect: return False, f"hash mismatch at {cert.get('cert_id')}" prev = cert["cert_hash"] return True, "ok" def attribution_graph( z: list[float], feature_weights: list[float], action: dict, p_hat: float, evidence_ids: list[str], top_k: int = 6, ) -> dict: """G_t: which admitted features support or oppose the action.""" ranked = sorted(range(len(z)), key=lambda j: abs(feature_weights[j] * z[j]), reverse=True) nodes = [] edges = [] for j in ranked[:top_k]: weight = float(feature_weights[j] * z[j]) if abs(weight) < 1e-9: continue nid = f"z{j}" nodes.append( { "id": nid, "kind": "feature", "label": f"z[{j}]", "weight": weight, } ) edges.append({"src": nid, "dst": "action", "weight": weight}) nodes.append( {"id": "action", "kind": "action", "label": f"{action['name']}", "weight": 1.0} ) nodes.append({"id": "risk", "kind": "risk", "label": "p_hat", "weight": float(p_hat)}) edges.append({"src": "action", "dst": "risk", "weight": float(p_hat)}) for cid in evidence_ids[:4]: nodes.append({"id": f"e_{cid}", "kind": "evidence", "label": cid, "weight": 1.0}) edges.append({"src": f"e_{cid}", "dst": "action", "weight": 0.5}) return {"method": "feature_ablation_attribution", "nodes": nodes, "edges": edges} def make_certificate( *, item_id: str, episode_id: str, step: int, decision: str, action: dict, mode: str, graph: dict, alternative: dict, predicted: dict, replayed: dict | None, consistency: tuple[bool, float], evidence: dict, bound: dict, cost: dict, ) -> dict: consistent, divergence = consistency replay_available = replayed is not None replayed = replayed or {"success": False, "harm": 0.0, "irreversible_harm": False} return { "schema_version": "1.0", "cert_id": hashlib.sha256( f"{item_id}:{step}:{utc_now()}:{os.getpid()}".encode("utf-8") ).hexdigest()[:24], "item_id": item_id, "episode_id": episode_id, "step": int(step), "decision": decision, "action": action, "mode": mode, "G": graph, "fork": { "alternative": alternative, "predicted": { "success": bool(predicted.get("success", False)), "harm": float(predicted.get("harm", 0.0)), "irreversible_harm": bool(predicted.get("irreversible_harm", False)), }, "replayed": { "success": bool(replayed.get("success", False)), "harm": float(replayed.get("harm", 0.0)), "irreversible_harm": bool(replayed.get("irreversible_harm", False)), "available": replay_available, }, "consistent": bool(consistent), "divergence": float(divergence), }, "E": evidence, "bound": bound, "cost": cost, "timestamp_utc": utc_now(), "prev_hash": _genesis_hash(), "cert_hash": "pending", } def audit_ledger(path: str | Path | None = None) -> dict: led = CertificateLedger(path) certs = led.read() ok, msg = led.verify_chain() n = len(certs) per_modality = {} for c in certs: for node in c["G"]["nodes"]: if node["kind"] == "evidence": per_modality[node["label"]] = per_modality.get(node["label"], 0) + 1 modes = {} for c in certs: modes[c["mode"]] = modes.get(c["mode"], 0) + 1 consistent = sum(1 for c in certs if c["fork"]["consistent"]) return { "n_certificates": n, "chain_ok": ok, "chain_message": msg, "modes": modes, "consistent": consistent, "consistency_rate": consistent / n if n else 0.0, "schema_valid": all(not list(_validator().iter_errors(c)) for c in certs) if n else True, }