# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scope-escalation-during-aaif-delegated-credential-issuance-when-a-sub-agent-re-derives-its-own-attenuation-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scope-escalation-during-aaif-delegated-credential-issuance-when-a-sub-agent-re-derives-its-own-attenuation-chain.warrant.json
# Markdown SHA-256:   85bb4b5ad3132fa12707b0f3a1d53eb4345d04df5c1d85127397acdad29c9397
# Code AST SHA-256:   3395e5098aabd047101ccb23f3b857de45a309a13744ee1796af7844f97ce638
# Verified Classes:   WitnessContinuityError, WitnessBudgetExceeded, Scope, Witness
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class WitnessContinuityError(RuntimeError):
    """Raised when an attenuation witness does not chain to root issuance."""
    pass


class WitnessBudgetExceeded(RuntimeError):
    """Raised when a witness cannot be carried intact across a tool boundary."""
    pass


@dataclass(frozen=True)
class Scope:
    fs_read: frozenset
    fs_write: frozenset
    net_egress: frozenset

    def is_subset_of(self, other: "Scope") -> bool:
        return (
            self.fs_read <= other.fs_read
            and self.fs_write <= other.fs_write
            and self.net_egress <= other.net_egress
        )

    def canonical_hash(self) -> str:
        payload = "|".join(
            [
                ",".join(sorted(self.fs_read)),
                ",".join(sorted(self.fs_write)),
                ",".join(sorted(self.net_egress)),
            ]
        )
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass(frozen=True)
class Witness:
    child_scope_hash: str
    parent_scope_hash: str
    parent_witness_hash: Optional[str]  # None only at root issuance
    signer: str


def verify_chain(
    witness: Witness,
    presented_scope: Scope,
    root_pubkey: str,
    max_hops: int = 4,
) -> None:
    """
    Enforce witness continuity and recompute the subset relation from the
    signed witness payload. Never trust the presented scope string alone.
    """
    if witness.child_scope_hash != presented_scope.canonical_hash():
        raise WitnessContinuityError(
            "presented scope does not match witness-bound child scope"
        )

    hops = 0
    cursor: Optional[Witness] = witness
    while cursor is not None:
        hops += 1
        if hops > max_hops:
            raise WitnessContinuityError("witness chain exceeds max_hops")
        if cursor.child_scope_hash == cursor.parent_scope_hash:
            raise WitnessContinuityError("degenerate attenuation hop")
        if cursor.parent_witness_hash is None:
            if cursor.signer != root_pubkey:
                raise WitnessContinuityError(
                    "chain terminates at non-root signer"
                )
            return
        # In a real implementation the next witness is resolved from the
        # chain store and its hash compared to parent_witness_hash; here we
        # assert the binding exists and is non-empty.
        if not cursor.parent_witness_hash:
            raise WitnessContinuityError("broken parent witness binding")
        cursor = _resolve(cursor.parent_witness_hash)


def _resolve(witness_hash: str) -> Optional[Witness]:
    # Placeholder for chain-store lookup; returning None models a lost hop.
    return None


def delegate(
    parent_scope: Scope,
    child_scope: Scope,
    parent_witness: Witness,
    budget_bytes: int,
    signer: str,
) -> Witness:
    if not child_scope.is_subset_of(parent_scope):
        raise WitnessContinuityError("child scope not a subset of parent scope")

    projected = Witness(
        child_scope_hash=child_scope.canonical_hash(),
        parent_scope_hash=parent_scope.canonical_hash(),
        parent_witness_hash=hashlib.sha256(
            repr(parent_witness).encode()
        ).hexdigest(),
        signer=signer,
    )
    serialized_len = len(repr(projected).encode())
    if serialized_len > budget_bytes:
        # Fail closed. Do NOT re-derive from the scope header.
        raise WitnessBudgetExceeded(
            f"witness requires {serialized_len}B > budget {budget_bytes}B; "
            "issue a narrower scope at a higher hop instead of re-deriving"
        )
    return projected
