# Copyright (c) 2026 CLSA contributors # SPDX-License-Identifier: MIT """Tier 2 quickstart: one benchmark task end to end, with a certificate.""" from __future__ import annotations import json import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "src")) import numpy as np # noqa: E402 import yaml # noqa: E402 from clsa.agents.policies import Ctx, build_policies # noqa: E402 from clsa.controller.certificate import CertificateLedger, make_certificate # noqa: E402 from clsa.eval.harness import best_safe_index, build_views # noqa: E402 from clsa.world_model.train import load_model # noqa: E402 def main() -> None: cfg = yaml.safe_load((Path(__file__).parent / "config.yaml").read_text()) backbone = cfg["backbone"] wm, rh, blob, ds = load_model(backbone) views = [v for v in build_views(ds) if v.split in ("test", "heldout")][: cfg.get("n_tasks", 5)] if not views: print("no states available; run `make train` first") raise SystemExit(1) import joblib from clsa.transcoder.dataset import DERIVED probes = { name: joblib.load(DERIVED / backbone.replace("/", "__") / f"probe_{name}.joblib") for name in ("dense", "sparse", "behaviour") if (DERIVED / backbone.replace("/", "__") / f"probe_{name}.joblib").exists() } ctx = Ctx( world_model=wm, risk_head=rh, probes=probes, thresholds=blob["thresholds"], alpha=float(cfg["alpha"]), budget_tokens=float(cfg["B_tokens"]), feature_mask=np.asarray(blob.get("feature_mask", []), dtype=int), costs={"monitor": 8.0, "rollout": 12.0, "verify": 40.0, "alloc": 6.0}, ) policy = build_policies(ctx)["clsa"] ledger = CertificateLedger(Path(cfg["ledger"]), enabled=True) for v in views: out = policy.decide(v) i = int(out.index) best = best_safe_index(v) cert = make_certificate( item_id=v.state_key, episode_id=v.episode_id, step=v.step, decision=out.decision, action=v.candidates[i], mode=out.mode, graph={ "method": "feature_ablation_attribution", "nodes": [ {"id": "action", "kind": "action", "label": v.candidates[i]["name"], "weight": 1.0}, {"id": "risk", "kind": "risk", "label": "p_hat", "weight": float(out.p_hat)}, ], "edges": [{"src": "action", "dst": "risk", "weight": float(out.p_hat)}], }, alternative=v.candidates[best], predicted={ "success": bool(v.success[i] > 0.5), "harm": float(v.harm[i]), "irreversible_harm": bool(v.irr[i]), }, # No sandbox fork is performed here, so the certificate must not # claim a replay: `available` is set false by the ledger and the # consistency flag compares the prediction with the recorded label, # which is a weaker check and is labelled as such. replayed=None, consistency=( bool((v.harm[i] > 0.5) == (out.p_hat > 0.5)), abs(float(v.harm[i]) - float(out.p_hat)), ), evidence={ "claims_used": [], "stale": v.evidence_stale, "conflict": v.evidence_conflict, "acquired": [], }, bound={ "alpha": ctx.alpha, "coverage": 1.0, "selective_risk_upper": float(out.p_hat), "n": 1, "method": "clopper_pearson_selective", "feasible": True, "budget_spent": float(out.tokens), "budget_limit": float(ctx.budget_tokens), "components": { "monitor": float(out.components.get("monitor", 0.0)), "simulation": float(out.components.get("simulation", 0.0)), "verification": float(out.components.get("verification", 0.0)), "allocator": float(out.components.get("allocator", 0.0)), }, }, cost={ "tokens": float(out.tokens), "latency_ms": float(out.tokens) * 0.6, "dollars": 0.0, "rollouts": int(out.rollouts), "verifications": int(out.components.get("verification", 0) > 0), }, ) written = ledger.write(cert) print(json.dumps({"state": v.state_key, "decision": written["decision"], "mode": written["mode"]}, indent=2)) ok, msg = ledger.verify_chain() print(f"ledger chain: {ok} ({msg}); n={len(ledger.read())}") if not ok: raise SystemExit(1) if __name__ == "__main__": main()