# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-warrant-signature-re-binding-from-silently-widening-authority-in-federated-a2a-v1-0-delegation-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-warrant-signature-re-binding-from-silently-widening-authority-in-federated-a2a-v1-0-delegation-chains.warrant.json
# Markdown SHA-256:   81c5fe904c14afdd7d689158cf0ddedcb9f2c1c12f2fc9d163428b6ab4caa941
# Code AST SHA-256:   cd0d91b8a6798c42d943add05a90c2433197c27674df402182f0fd96e9f41a4e
# Verified Classes:   WarrantSubsumptionError, GenesisWarrant, ReboundWarrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class WarrantSubsumptionError(RuntimeError):
    """Raised when a re-bound warrant is not provably subsumed by its genesis warrant."""


@dataclass(frozen=True)
class GenesisWarrant:
    issuer: str
    scope_paths: frozenset[str]      # canonical, absolute, symlink-resolved
    max_ops: int                     # chain-global ceiling
    expires_at_utc: float            # absolute epoch seconds


@dataclass(frozen=True)
class ReboundWarrant:
    signer: str
    genesis_hash: str
    scope_paths: frozenset[str]
    remaining_ops: int
    expires_at_utc: float


def _hash_genesis(g: GenesisWarrant) -> str:
    body = f"{g.issuer}|{sorted(g.scope_paths)}|{g.max_ops}|{g.expires_at_utc}"
    return hashlib.sha256(body.encode()).hexdigest()


def verify_rebound_at_boundary(
    genesis: GenesisWarrant,
    rebound: ReboundWarrant,
    prior_consumed_ops: int,
    now_utc: float,
) -> None:
    """Enforce the subsumption invariant at a trust-domain boundary.

    Rejects any re-bound warrant that widens scope, resets budget,
    extends lifetime, or detaches from the genesis body.
    """
    if rebound.genesis_hash != _hash_genesis(genesis):
        raise WarrantSubsumptionError(
            f"genesis hash mismatch: rebound signs {rebound.genesis_hash!r}, "
            f"genesis hashes to {_hash_genesis(genesis)!r}; chain is detached"
        )

    widened = rebound.scope_paths - genesis.scope_paths
    if widened:
        raise WarrantSubsumptionError(
            f"scope widening across trust boundary: {sorted(widened)} "
            f"not within genesis scope {sorted(genesis.scope_paths)}"
        )

    chain_remaining = genesis.max_ops - prior_consumed_ops
    if rebound.remaining_ops > chain_remaining:
        raise WarrantSubsumptionError(
            f"budget reset: hop advertises {rebound.remaining_ops} ops, "
            f"chain allows {chain_remaining} after {prior_consumed_ops} consumed"
        )

    if rebound.expires_at_utc > genesis.expires_at_utc:
        raise WarrantSubsumptionError(
            f"lifetime extension: hop expiry {rebound.expires_at_utc} exceeds "
            f"genesis expiry {genesis.expires_at_utc}"
        )

    if now_utc >= genesis.expires_at_utc:
        raise WarrantSubsumptionError(
            f"genesis warrant expired at {genesis.expires_at_utc}, now={now_utc}"
        )


def accept_or_reauthorize(
    genesis: GenesisWarrant,
    rebound: ReboundWarrant,
    prior_consumed_ops: int,
    has_subsumption_oracle: bool,
) -> str:
    """Decision boundary: accept the re-bound warrant, or force re-authorization."""
    if not has_subsumption_oracle:
        return "REAUTHORIZE"  # no oracle -> treat as request, not grant
    verify_rebound_at_boundary(
        genesis, rebound, prior_consumed_ops, now_utc=time.time()
    )
    return "ACCEPT"
