File size: 7,243 Bytes
fd5366a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 | # Copyright (c) 2026 CLSA contributors
# SPDX-License-Identifier: MIT
"""Certificates: Cert(a_t) = <G_t, Fork_t, E_t, Bound_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,
}
|