# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-transitive-delegation-scope-laundering-across-federated-agent-trust-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-transitive-delegation-scope-laundering-across-federated-agent-trust-boundaries.warrant.json
# Markdown SHA-256:   e95159907f31a7ee7b7a0d20c2f370add1b4385b3eb78e9ac944b257decb42b8
# Code AST SHA-256:   233ecff154a242406091e3f069e7906b597c7180292a3975cd28a1941069f901
# Verified Classes:   ScopeAlgebraMismatch, DelegationToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping


class ScopeAlgebraMismatch(RuntimeError):
    """Raised when a delegation token's scope algebra cannot be faithfully
    evaluated by the relying party. Must fail closed: laundering risk."""


@dataclass(frozen=True)
class DelegationToken:
    issuer_domain: str
    scope_algebra: str          # versioned schema URI, e.g. "x.org/scope/v2"
    scope: Mapping[str, object]
    signature_valid: bool


def attenuate_and_forward(
    inbound: DelegationToken,
    local_algebra: str,
    local_algebra_recognizes: set[str],
    requested_narrowing: Mapping[str, object],
) -> DelegationToken:
    # Signature validity is necessary but never sufficient for forwarding.
    if not inbound.signature_valid:
        raise ScopeAlgebraMismatch(
            f"token from {inbound.issuer_domain} failed signature verification"
        )

    # The laundering primitive is lossy re-encoding of a foreign scope.
    # We may only narrow scopes whose algebra we can represent exactly.
    if inbound.scope_algebra not in local_algebra_recognizes:
        raise ScopeAlgebraMismatch(
            "refusing to attenuate scope under algebra "
            f"{inbound.scope_algebra!r}: not recognized by local algebra "
            f"{local_algebra!r}. Re-encoding would risk widening the effective "
            "authority (dropped filters become no-ops under default-allow)."
        )

    # Narrowing must be a true intersection, never a replacement.
    narrowed = dict(inbound.scope)
    for key, val in requested_narrowing.items():
        if key not in narrowed:
            raise ScopeAlgebraMismatch(
                f"narrowing key {key!r} absent from inbound scope; "
                "cannot intersect, would introduce new authority"
            )
        narrowed[key] = val

    # Re-sign under the originating algebra so the chain stays verifiable.
    return DelegationToken(
        issuer_domain=inbound.issuer_domain,
        scope_algebra=inbound.scope_algebra,
        scope=narrowed,
        signature_valid=True,
    )
