# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-signed-agent-passport-whose-delegation-chain-was-attenuated-after-the-warrant-was-minted.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-signed-agent-passport-whose-delegation-chain-was-attenuated-after-the-warrant-was-minted.warrant.json
# Markdown SHA-256:   b0c15c1897c54ab074ffc3397a7c125bf47571971ae2afba80c31eb845a58489
# Code AST SHA-256:   3a7d129d588184289ac9cebc5470889e2399970d74722d24752683828768deb6
# Verified Classes:   DelegationDriftError, Warrant, AuthorityStore
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class DelegationDriftError(RuntimeError):
    """Raised when a presented delegation link is superseded or non-authoritative."""
    pass


@dataclass(frozen=True)
class Warrant:
    warrant_id: str          # stable ID (the hazard) or content hash (safe)
    issuer: str
    caps: frozenset
    not_after: float
    body: bytes

    def content_hash(self) -> str:
        return hashlib.sha256(self.body).hexdigest()


@dataclass
class AuthorityStore:
    """Issuer-side authoritative records, keyed by warrant_id."""
    records: dict

    def current(self, warrant_id: str):
        return self.records.get(warrant_id)


def verify_chain(chain, store: AuthorityStore, now=None, require_live=True):
    """
    chain: list[Warrant] ordered root -> leaf.
    Enforces the invariant: every link's embedded bytes must equal the issuer's
    current authoritative record, and leaf caps must be a subset of every
    ancestor's *current* grant (not the embedded snapshot).
    """
    now = now if now is not None else time.time()
    if not chain:
        raise DelegationDriftError("empty delegation chain")

    leaf_caps = chain[-1].caps
    for link in chain:
        if now > link.not_after:
            raise DelegationDriftError(
                f"warrant {link.warrant_id} expired at {link.not_after}"
            )

        if not require_live:
            # Snapshot-trust path: only safe if warrant_id is a content hash.
            if link.warrant_id != link.content_hash():
                raise DelegationDriftError(
                    f"snapshot-trust requested for non-content-addressed "
                    f"warrant_id={link.warrant_id}; drift window open"
                )
            continue

        auth = store.current(link.warrant_id)
        if auth is None:
            raise DelegationDriftError(
                f"warrant {link.warrant_id} does not resolve to a live record"
            )
        if auth.body != link.body:
            raise DelegationDriftError(
                f"warrant {link.warrant_id} bytes diverge from authoritative "
                f"record (superseded under stable ID)"
            )
        if not leaf_caps <= auth.caps:
            raise DelegationDriftError(
                f"leaf caps {sorted(leaf_caps)} exceed current grant of "
                f"{link.warrant_id} {sorted(auth.caps)}"
            )
    return True


def reconcile_leaf(leaf_chain, store):
    """Audit hook: flag over-grant before it is exercised."""
    try:
        return verify_chain(leaf_chain, store, require_live=True)
    except DelegationDriftError as e:
        # Surface for security review; do not silently downgrade to snapshot.
        raise DelegationDriftError(f"reconciliation failed: {e}") from e
