# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-validly-signed-mcp-manifest-whose-skill-provenance-was-re-signed-by-a-compromised-intermediary-at-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-validly-signed-mcp-manifest-whose-skill-provenance-was-re-signed-by-a-compromised-intermediary-at-handoff.warrant.json
# Markdown SHA-256:   95a05bb40db0c74bb0143ede1fca2c11965c4869d85ef6b0a33dfade736b33f4
# Code AST SHA-256:   cc426de3faf7e8fb24da7a601b650e7c611180ba55d86b4a6deae5c0e0ad66b8
# Verified Classes:   ProvenanceChainError, Scope, Delegation, Manifest, DelegationCache
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ProvenanceChainError(RuntimeError):
    """Raised when a manifest's authority cannot be established from its full chain."""
    pass


@dataclass(frozen=True)
class Scope:
    capability: str
    root: str

    def is_subset_of(self, other: "Scope") -> bool:
        return (
            self.capability == other.capability
            and (self.root == other.root or self.root.startswith(other.root.rstrip("/") + "/"))
        )


@dataclass(frozen=True)
class Delegation:
    issuer: str
    intermediary: str
    scope: Scope
    expires_at: int
    signature: bytes


@dataclass(frozen=True)
class Manifest:
    skill: str
    declared: Scope
    signer: str
    signature: bytes
    chain_hash: str


@dataclass
class DelegationCache:
    records: dict = field(default_factory=dict)

    def get(self, issuer: str, intermediary: str):
        return self.records.get((issuer, intermediary))


def admit(manifest: Manifest, delegations: list[Delegation], cache: DelegationCache, now: int) -> Scope:
    # Enforce fail-closed: a missing delegation record is an admission failure,
    # never a fallback to leaf-trust.
    if not delegations:
        raise ProvenanceChainError(
            f"manifest {manifest.skill!r} has no retrievable delegation chain; "
            "refusing leaf-trust admission (downgrade surface)"
        )

    effective = manifest.declared
    for d in delegations:
        if d.expires_at <= now:
            raise ProvenanceChainError(
                f"delegation {d.issuer}->{d.intermediary} expired at {d.expires_at}"
            )
        cached = cache.get(d.issuer, d.intermediary)
        if cached is None:
            # Cache miss must fail closed, not downgrade.
            raise ProvenanceChainError(
                f"delegation record {d.issuer}->{d.intermediary} not in cache; "
                "cannot compute scope intersection"
            )
        if not effective.is_subset_of(cached.scope):
            raise ProvenanceChainError(
                f"scope inflation: {manifest.skill!r} declares {effective.root!r} "
                f"but {d.issuer}->{d.intermediary} authorized {cached.scope.root!r}"
            )
        effective = Scope(effective.capability, cached.scope.root)

    # Recompute chain hash and compare to the manifest's claimed hash.
    h = hashlib.sha256()
    for d in delegations:
        h.update(d.signature)
    if h.hexdigest() != manifest.chain_hash:
        raise ProvenanceChainError(
            f"chain hash mismatch for {manifest.skill!r}: manifest claims "
            f"{manifest.chain_hash[:12]}..., recomputed {h.hexdigest()[:12]}..."
        )

    return effective


def build_sandbox_boundary(admitted: Scope) -> str:
    # The sandbox boundary MUST be derived from the intersected scope,
    # never from the leaf manifest's declared root.
    return admitted.root
