# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-a2a-artifact-whose-audit-receipt-is-valid-but-whose-policy-scope-envelope-has-silently-widened.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-a2a-artifact-whose-audit-receipt-is-valid-but-whose-policy-scope-envelope-has-silently-widened.warrant.json
# Markdown SHA-256:   74f39caa33afb69bae598942b91c8bcae8c16bdaf8a48f363103805c16774af9
# Code AST SHA-256:   0e9c8547990a6bd0b3dbeb1d225dc7fcad92e14529fdfaf525dfc54c7f1fdc46
# Verified Classes:   ScopeWideningError, Envelope, Receipt
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class ScopeWideningError(RuntimeError):
    """Raised when a federated artifact's receipt is valid but its resolved
    policy scope is not a subset of the scope authorized on the inbound task."""


# Fields whose defaulting divergence is the trigger condition.
DEFAULT_SENSITIVE_FIELDS = ("purpose", "retention", "recipient_set")


@dataclass
class Envelope:
    policy_ref: str
    declared: dict            # fields actually present in the wire document
    resolver_profile: str     # org id whose defaulting rules produced `declared`


@dataclass
class Receipt:
    producer: str
    artifact_hash: str
    policy_ref: str
    signature_ok: bool


def resolve_scope(env: Envelope, local_profile: str, local_defaults: dict) -> dict:
    """Resolve a possibly-sparse envelope under a named resolver profile.

    Resolution is the load-bearing step: omitted fields fall back to
    `local_defaults`, and two profiles with different defaults resolve
    byte-identical envelopes to different scopes.
    """
    resolved = dict(local_defaults)
    resolved.update(env.declared)
    return resolved


def scope_digest(scope: dict) -> str:
    canon = json.dumps(scope, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canon.encode()).hexdigest()


def admit_federated_artifact(
    receipt: Receipt,
    inbound_env: Envelope,
    local_profile: str,
    local_defaults: dict,
    hop_count: int,
) -> dict:
    # Gate 1: receipt authenticity (necessary, not sufficient).
    if not receipt.signature_ok:
        raise ScopeWideningError(f"receipt from {receipt.producer} failed signature")
    if receipt.policy_ref != inbound_env.policy_ref:
        raise ScopeWideningError("receipt policy_ref does not bind inbound envelope")

    # Gate 2: scope containment under LOCAL resolution.
    local_scope = resolve_scope(inbound_env, local_profile, local_defaults)

    # If the envelope is sparse on a default-sensitive field and we are past
    # the first hop, resolution is ambiguous -> cannot admit on receipt alone.
    sparse = [f for f in DEFAULT_SENSITIVE_FIELDS if f not in inbound_env.declared]
    if hop_count > 1 and sparse:
        # Require a pinned resolved-scope digest committed by the emitter.
        pinned = inbound_env.declared.get("__resolved_scope_digest__")
        if pinned is None:
            raise ScopeWideningError(
                f"hop_count={hop_count} envelope sparse on {sparse}; "
                f"no resolved-scope digest to disambiguate defaulting"
            )
        if pinned != scope_digest(local_scope):
            raise ScopeWideningError(
                f"resolved-scope digest mismatch at hop {hop_count}: "
                f"emitter profile {inbound_env.resolver_profile} resolved to a "
                f"different scope than local profile {local_profile}; "
                f"scope has widened or narrowed across the hop"
            )

    return local_scope
