# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-trust-broker-attestation-drift-during-cross-org-capability-exchange-in-federated-agent-meshes.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-trust-broker-attestation-drift-during-cross-org-capability-exchange-in-federated-agent-meshes.warrant.json
# Markdown SHA-256:   fbeb199bf0d03b0d9ed9f0b88906969bb6eac8d1880dc0360b929b800322d2bf
# Code AST SHA-256:   3a5e4fe53def2df68ead032e7d846cf5658914f745032bcfd2fefe335c8b963a
# Verified Classes:   AttestationDriftError, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class AttestationDriftError(RuntimeError):
    """Raised when a consumed warrant's pinned predicate version no longer
    matches the issuer's live predicate version and no pin is honored."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    predicate_version: str
    pinned_until: float          # epoch seconds; issuer commits to this version until here
    ttl_expires: float
    scope: dict
    signature_ok: bool


def mint_warrant(predicate_version: str, scope: dict, ttl_s: int, now: float) -> Warrant:
    nonce = hashlib.sha256(f"{predicate_version}|{sorted(scope.items())}|{now}".encode()).hexdigest()[:16]
    return Warrant(
        warrant_id=f"w-{predicate_version}-{nonce}",
        predicate_version=predicate_version,
        pinned_until=now + ttl_s,
        ttl_expires=now + ttl_s,
        scope=scope,
        signature_ok=True,
    )


def verify_and_consume(w: Warrant, live_predicate_version: str, now: float) -> None:
    # Standard gates — all pass even under drift.
    if not w.signature_ok:
        raise AttestationDriftError(f"warrant {w.warrant_id}: signature invalid")
    if now > w.ttl_expires:
        raise AttestationDriftError(f"warrant {w.warrant_id}: expired")

    # The continuity invariant: the issuer must either honor the pin, or the
    # pinned version must equal the live version. Anything else is drift.
    pin_honored = now <= w.pinned_until
    version_matches = w.predicate_version == live_predicate_version
    if not (pin_honored or version_matches):
        raise AttestationDriftError(
            f"warrant {w.warrant_id}: pinned predicate {w.predicate_version} "
            f"superseded by {live_predicate_version} at t={now:.0f}, "
            f"pin expired at t={w.pinned_until:.0f}; authorization is orphaned"
        )


def reconcile_audit(mint_log: list[Warrant], exec_log: list[dict], live_versions: dict[str, str]) -> list[str]:
    """Background reconciliation: returns warrant_ids consumed under drift.
    Relies on warrant_id being a deterministic function of predicate_version."""
    drifted = []
    for entry in exec_log:
        w = next((m for m in mint_log if m.warrant_id == entry["warrant_id"]), None)
        if w is None:
            drifted.append(entry["warrant_id"])  # unjoinable — also a failure
            continue
        live = live_versions.get(w.predicate_version)
        if live is not None and live != w.predicate_version and entry["consumed_at"] > w.pinned_until:
            drifted.append(w.warrant_id)
    return drifted


if __name__ == "__main__":
    now = time.time()
    w = mint_warrant("P_read_v7", {"dataset": "catalog-prod", "ops": ["read"]}, ttl_s=900, now=now)
    # Policy team ships v8 at now+3s; retry re-presents the old warrant at now+600s.
    verify_and_consume(w, live_predicate_version="P_read_v8", now=now + 600)  # pin still honored
    verify_and_consume(w, live_predicate_version="P_read_v8", now=now + 950)  # raises: pin expired, version stale
