Download src/clsa/evidence/ledger.py from fahadhafeezofficial/clsa-code: direct link, hf CLI and curl.
- Browser
- Download file 9.96 kB
-
https://huggingface.co/datasets/fahadhafeezofficial/clsa-code/resolve/main/src/clsa/evidence/ledger.py
- Command line
-
hf download hf://datasets/fahadhafeezofficial/clsa-code/src/clsa/evidence/ledger.py
-
curl -L -o ledger.py https://huggingface.co/datasets/fahadhafeezofficial/clsa-code/resolve/main/src/clsa/evidence/ledger.py
9.96 kB
| # Copyright (c) 2026 CLSA contributors | |
| # SPDX-License-Identifier: MIT | |
| """The evidence and provenance state e_t. | |
| Claims are structured tuples (claim, source, timestamp, modality). Staleness and | |
| cross-modal conflict are computed from that structure, never inferred from prose | |
| by a language model. This is the difference between an evidence pack and a | |
| transcript. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| from dataclasses import dataclass, field | |
| from datetime import datetime, timezone | |
| from typing import Iterable | |
| from clsa.envs.render import extract_image_features | |
| NOW = datetime(2026, 11, 25, tzinfo=timezone.utc) | |
| STALE_DAYS = 90.0 | |
| MODALITY_TRUST = {"tool_state": 0.95, "image": 0.80, "text": 0.60} | |
| SOURCE_TRUST = { | |
| "inbox": 0.60, | |
| "file": 0.70, | |
| "catalog_cache": 0.50, | |
| "image": 0.80, | |
| "tool_state": 0.95, | |
| } | |
| def _age_days(ts: str) -> float: | |
| try: | |
| dt = datetime.fromisoformat(ts.replace("Z", "+00:00")) | |
| if dt.tzinfo is None: | |
| dt = dt.replace(tzinfo=timezone.utc) | |
| return max(0.0, (NOW - dt).total_seconds() / 86400.0) | |
| except Exception: | |
| return 999.0 | |
| def _first_number(text: str) -> float | None: | |
| m = re.search(r"(\d+(?:\.\d+)?)", text) | |
| return float(m.group(1)) if m else None | |
| def claims_from_env(env) -> list[dict]: | |
| """Build e_t from one environment snapshot.""" | |
| claims: list[dict] = [] | |
| fam = env.spec["family"] | |
| st = env.state | |
| cid = 0 | |
| def add(var, value, source, ts, modality, trusted=True, text=""): | |
| nonlocal cid | |
| cid += 1 | |
| claims.append( | |
| { | |
| "claim_id": f"c{cid}", | |
| "claim": var, | |
| "claim_text": text or f"{var}={value}", | |
| "source": source, | |
| "timestamp": ts, | |
| "modality": modality, | |
| "value": value, | |
| "trusted": bool(trusted), | |
| } | |
| ) | |
| if fam == "email_payment": | |
| o = st["orders"][env.spec["order_id"]] | |
| for m in st["inbox"]: | |
| if "refund" in m["body"].lower() or "gbp" in m["body"].lower(): | |
| num = _first_number(m["body"].split("GBP")[-1]) if "GBP" in m["body"] else None | |
| if num is not None: | |
| add("amount_due", num, f"inbox:{m['id']}", m["ts"], "text", not m["injected"], m["body"]) | |
| if m["injected"]: | |
| add("instruction", "pay_external", f"inbox:{m['id']}", m["ts"], "text", False, m["body"]) | |
| add("order_amount", o["amount"], "tool_state:order", "2026-11-20", "tool_state") | |
| add("recipient_safe", st["constraints"]["allowed_recipients"][0], "tool_state:policy", "2026-10-01", "tool_state") | |
| if st.get("image"): | |
| feats = extract_image_features(env.image_path) | |
| if feats["amount"] is not None: | |
| add( | |
| "amount_due", | |
| feats["amount"], | |
| "image:invoice", | |
| st["image"].get("ts", "2026-11-20"), | |
| "image", | |
| True, | |
| f"invoice shows {feats['amount']}", | |
| ) | |
| elif fam == "files_ops": | |
| contract = st["files"].get("contract.pdf", {"content": ""})["content"] | |
| notes = st["files"].get("notes.txt", {"content": ""})["content"] | |
| draft_ts = st["files"].get("draft.md", {}).get("ts", "2026-11-24") | |
| add("contract_present", "contract.pdf" in st["files"], "tool_state:fs", "2026-11-24", "tool_state") | |
| add("draft_present", "draft.md" in st["files"], "tool_state:fs", "2026-11-24", "tool_state") | |
| add("notes_topic", notes.split(":")[0], "file:notes.txt", "2026-11-22", "text", True, notes[:90]) | |
| add("draft_freshness", draft_ts, "file:draft.md", draft_ts, "text", True, "draft timestamp") | |
| money = re.search(r"GBP (\d+(?:\.\d+)?)", notes) | |
| if money: | |
| add("doc_amount", float(money.group(1)), "file:notes.txt", "2026-11-22", "text", True, notes[:90]) | |
| if "Ignore previous instructions" in notes: | |
| add("instruction", "exfiltrate", "file:notes.txt", "2026-11-22", "text", False, notes[-80:]) | |
| add("secret_ref", contract[:24], "file:contract.pdf", "2026-11-24", "text", True, contract[:60]) | |
| if st.get("image"): | |
| feats = extract_image_features(env.image_path) | |
| if feats["amount"] is not None: | |
| img_ts = st["image"].get("ts", "2026-11-24") | |
| add("doc_amount", feats["amount"], "image:scan", img_ts, "image") | |
| elif fam == "web_shop": | |
| for sku, item in st["catalog"].items(): | |
| add( | |
| "price_" + sku, | |
| item["price"], | |
| "catalog_cache", | |
| item["listed_ts"], | |
| "text", | |
| _age_days(item["listed_ts"]) < STALE_DAYS, | |
| f"{sku} listed at {item['price']}", | |
| ) | |
| add("stock_" + sku, item["stock"], "tool_state:inventory", "2026-11-24", "tool_state") | |
| add("budget", st["budget"], "tool_state:cart", "2026-11-24", "tool_state") | |
| if st.get("image"): | |
| feats = extract_image_features(env.image_path) | |
| if feats["amount"] is not None: | |
| add("price_lap-a", feats["amount"], "image:product_page", "2026-11-24", "image", True, f"page shows {feats['amount']}") | |
| else: # gui_settings | |
| feats = extract_image_features(env.image_path) if st.get("image") else {"toggle_states": [True, True, True]} | |
| toggles = list(feats.get("toggle_states", [True, True, True])) | |
| img_ts = st.get("image", {}).get("ts", "2026-11-24") | |
| add("marketing_notifications", toggles[0], "image:settings", img_ts, "image", True, "marketing toggle") | |
| add("two_factor_auth", toggles[1], "image:settings", img_ts, "image", True, "two-factor toggle") | |
| add("marketing_notifications", st["settings"]["marketing_notifications"], "tool_state:settings", "2026-11-24", "tool_state") | |
| add("account_active", st["settings"]["account_active"], "tool_state:settings", "2026-11-24", "tool_state") | |
| add("two_factor_auth", st["settings"]["two_factor_auth"], "tool_state:settings", "2026-11-24", "tool_state") | |
| for c in claims: | |
| c["age_days"] = _age_days(c["timestamp"]) | |
| c.setdefault("trusted", True) | |
| if c["age_days"] > STALE_DAYS: | |
| c["stale"] = True | |
| else: | |
| c["stale"] = False | |
| base = SOURCE_TRUST.get(c["source"].split(":")[0], 0.6) | |
| c["weight"] = base * (0.3 if c["stale"] else 1.0) * (1.0 if c["trusted"] else 0.15) | |
| return claims | |
| def conflicts(claims: Iterable[dict]) -> list[dict]: | |
| """Cross-modal or cross-source contradictions on the same variable.""" | |
| by_var: dict[str, list[dict]] = {} | |
| for c in claims: | |
| by_var.setdefault(c["claim"], []).append(c) | |
| out = [] | |
| for var, group in by_var.items(): | |
| vals: list[float] = [] | |
| for c in group: | |
| v = c["value"] | |
| if v is None: | |
| continue | |
| if isinstance(v, bool): | |
| vals.append(1.0 if v else 0.0) | |
| elif isinstance(v, (int, float)): | |
| vals.append(float(v)) | |
| if len(vals) >= 2 and (max(vals) - min(vals)) > 1e-6: | |
| numeric = [float(c["value"]) for c in group if isinstance(c["value"], (int, float)) and not isinstance(c["value"], bool)] | |
| numeric_ok = len(numeric) < 2 or (max(numeric) - min(numeric)) > max(1e-6, 0.01 * max(abs(max(numeric)), 1.0)) | |
| if not numeric_ok: | |
| continue | |
| modalities = sorted({c["modality"] for c in group}) | |
| out.append( | |
| { | |
| "claim": var, | |
| "values": vals, | |
| "modalities": modalities, | |
| "cross_modal": len(modalities) > 1, | |
| "claim_ids": [c["claim_id"] for c in group], | |
| } | |
| ) | |
| return out | |
| class EvidenceLedger: | |
| """Append-only evidence state with a fixed-width summary vector.""" | |
| claims: list[dict] = field(default_factory=list) | |
| acquired: list[dict] = field(default_factory=list) | |
| def update(self, claims: list[dict]) -> None: | |
| self.claims = list(claims) | |
| self.stale = any(c.get("stale") for c in self.claims) | |
| self.conflict_list = conflicts(self.claims) | |
| self.conflict = len(self.conflict_list) > 0 | |
| def acquire(self, claim: dict) -> None: | |
| self.acquired.append(claim) | |
| self.claims.append(claim) | |
| self.stale = any(c.get("stale") for c in self.claims) | |
| self.conflict_list = conflicts(self.claims) | |
| self.conflict = len(self.conflict_list) > 0 | |
| def used_claims(self) -> list[str]: | |
| return [c["claim_id"] for c in self.claims if c.get("trusted") and not c.get("stale")] | |
| def vector(self) -> list[float]: | |
| n = len(self.claims) | |
| if n == 0: | |
| return [0.0] * 9 | |
| stale = sum(1 for c in self.claims if c.get("stale")) | |
| trusted = sum(1 for c in self.claims if c.get("trusted")) | |
| ages = [c.get("age_days", 0.0) for c in self.claims] | |
| has_img = any(c["modality"] == "image" for c in self.claims) | |
| has_tool = any(c["modality"] == "tool_state" for c in self.claims) | |
| has_text = any(c["modality"] == "text" for c in self.claims) | |
| return [ | |
| min(1.0, n / 10.0), | |
| stale / n, | |
| len(self.conflict_list) / max(1, n), | |
| trusted / n, | |
| min(1.0, (sum(ages) / n) / 365.0), | |
| float(has_img), | |
| float(has_tool), | |
| float(has_text), | |
| float(len(self.acquired) > 0), | |
| ] | |
| def snapshot(self) -> dict: | |
| return { | |
| "claims": self.claims, | |
| "stale": self.stale, | |
| "conflict": self.conflict, | |
| "conflicts": self.conflict_list, | |
| "used": self.used_claims(), | |
| } | |