# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a2a-v1-0-task-lifecycle-negotiation-from-silently-degrading-when-capability-attestations-are-re-signed-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a2a-v1-0-task-lifecycle-negotiation-from-silently-degrading-when-capability-attestations-are-re-signed-mid-handoff.warrant.json
# Markdown SHA-256:   518885249a225840e0294f238190493032a7d1cfa2a048ec3ac85f4089f5e940
# Code AST SHA-256:   0ce1e6bf2ce23858f6827fb37030ab185d1ed34035d378c3baa59be44418c2c0
# Verified Classes:   AttestationDriftError, Attestation, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Dict, Set


class AttestationDriftError(RuntimeError):
    """Raised when a task warrant's bound capability digest no longer matches
    the accepting agent's live attestation along a load-bearing dimension."""
    pass


@dataclass(frozen=True)
class Attestation:
    digest: str
    capabilities: Dict[str, object]  # e.g. {"code_exec": True, "model": "v2-large"}

    @staticmethod
    def sign(capabilities: Dict[str, object]) -> "Attestation":
        raw = repr(sorted(capabilities.items())).encode()
        return Attestation(hashlib.sha256(raw).hexdigest(), dict(capabilities))


@dataclass
class Warrant:
    warrant_id: str
    bound_digest: str
    scope: Set[str]                 # capability keys this warrant depends on
    parent_warrant_id: str = ""
    parent_digest: str = ""
    suspended: bool = False


def is_superset_on(new: Dict[str, object], old: Dict[str, object], keys: Set[str]) -> bool:
    """True iff new matches old on every referenced key (no narrowing)."""
    for k in keys:
        if k not in new:
            return False
        if new[k] != old[k]:
            return False
    return True


def check_warrant_before_step(warrant: Warrant, live: Attestation,
                              old_caps: Dict[str, object]) -> None:
    """Guardrail 1: fire before any capability-dependent step. Raises on drift."""
    if warrant.suspended:
        raise AttestationDriftError(
            f"warrant {warrant.warrant_id} suspended pending renegotiation"
        )
    if live.digest != warrant.bound_digest:
        # digest changed mid-task: only safe if narrowing did not touch our scope
        if not is_superset_on(live.capabilities, old_caps, warrant.scope):
            raise AttestationDriftError(
                f"warrant {warrant.warrant_id} bound to {warrant.bound_digest} "
                f"but live attestation {live.digest} narrowed scope {warrant.scope}"
            )
    # Guardrail 2: sub-warrant must still see parent capability intact
    if warrant.parent_warrant_id and live.digest != warrant.parent_digest:
        if not is_superset_on(live.capabilities, old_caps, warrant.scope):
            raise AttestationDriftError(
                f"sub-warrant {warrant.warrant_id} parent {warrant.parent_warrant_id} "
                f"lost capability on {warrant.scope}"
            )


def on_attestation_rotation(open_warrants: list, old: Attestation,
                            new: Attestation) -> list:
    """Guardrail 3: suspend any warrant whose scope references a narrowed dimension."""
    narrowed = []
    for w in open_warrants:
        if not is_superset_on(new.capabilities, old.capabilities, w.scope):
            w.suspended = True
            narrowed.append(w.warrant_id)
    return narrowed
