# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegation-receipt-forgery-when-an-auditor-agent-replays-a-sub-agent-s-tool-call-transcript-against-a-mutable-mcp-capability.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegation-receipt-forgery-when-an-auditor-agent-replays-a-sub-agent-s-tool-call-transcript-against-a-mutable-mcp-capability.warrant.json
# Markdown SHA-256:   c0058f6b77b941b7aa3a0746251df0efa1f42c667207a420ce330ef03ebadffa
# Code AST SHA-256:   bc37b4e2ea930edde803caae2dff044000f49342a997fb98ae5408bb4c428087
# Verified Classes:   ContractDriftError, CapabilityContract, DelegationReceipt, ReAttestation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Optional


class ContractDriftError(RuntimeError):
    """Raised when a delegation receipt's committed capability digest no longer
    matches the live manifest and no signed re-attestation bridges the gap."""
    pass


@dataclass(frozen=True)
class CapabilityContract:
    capability_id: str
    schema: dict
    defaults: dict
    enforcement_hooks: tuple

    def digest(self) -> str:
        # Digest MUST cover defaults and enforcement hooks, not just schema.
        payload = json.dumps(
            {
                "id": self.capability_id,
                "schema": self.schema,
                "defaults": self.defaults,
                "hooks": sorted(self.enforcement_hooks),
            },
            sort_keys=True,
            separators=(",", ":"),
        ).encode()
        return "sha256:" + hashlib.sha256(payload).hexdigest()


@dataclass(frozen=True)
class DelegationReceipt:
    delegator: str
    delegate: str
    capability_id: str
    capability_digest: str  # committed at issuance
    constraints: dict
    signature: str


@dataclass(frozen=True)
class ReAttestation:
    capability_id: str
    from_digest: str
    to_digest: str
    signed_by: str
    signature: str


def verify_invocation(
    receipt: DelegationReceipt,
    live_manifest: dict,
    reattestations: list,
    invocation: dict,
) -> str:
    live: Optional[CapabilityContract] = live_manifest.get(receipt.capability_id)
    if live is None:
        raise ContractDriftError(
            f"capability {receipt.capability_id} no longer resolvable; "
            f"receipt committed {receipt.capability_digest}"
        )

    if live.digest() == receipt.capability_digest:
        return _apply_constraints(receipt, invocation, live)

    # Digest mismatch: look for a signed bridge from committed -> live.
    bridge = next(
        (
            r
            for r in reattestations
            if r.capability_id == receipt.capability_id
            and r.from_digest == receipt.capability_digest
            and r.to_digest == live.digest()
        ),
        None,
    )
    if bridge is None:
        # Fail closed into a third state, not PASS and not FAIL.
        raise ContractDriftError(
            f"unbridged contract drift for {receipt.capability_id}: "
            f"receipt={receipt.capability_digest} live={live.digest()}; "
            f"invocation quarantined as UNVERIFIABLE"
        )

    # Re-attested: verify against the new contract but annotate drift.
    verdict = _apply_constraints(receipt, invocation, live)
    return f"{verdict}|CONTRACT_DRIFT_ANNOTATED:{bridge.signed_by}"


def _apply_constraints(
    receipt: DelegationReceipt,
    invocation: dict,
    contract: CapabilityContract,
) -> str:
    # Constraints are re-applied against the *current* enforcement path,
    # including any defaults the new contract injects.
    effective = {**contract.defaults, **invocation.get("args", {})}
    for key, ceiling in receipt.constraints.items():
        if key in effective and effective[key] > ceiling:
            return "VIOLATION"
    return "AUTHORIZED"
