# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-delegation-when-the-requestor-s-policy-attestation-is-valid-but-its-provenance-chain-is-trun.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-delegation-when-the-requestor-s-policy-attestation-is-valid-but-its-provenance-chain-is-trun.warrant.json
# Markdown SHA-256:   8142ab76743cffe4910e1f8a6390df78b5b7bb868aa5fd19af247988b7176398
# Code AST SHA-256:   b871f009008f1f88961bdbfe84d0fc539aa01639d8d5747e69202b6607c4fa4e
# Verified Classes:   ProvenanceChainTruncated, ScopeMonotonicityViolation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ProvenanceChainTruncated(RuntimeError):
    """Raised when a federated delegation's provenance chain does not reach a recognized trust root."""
    pass


class ScopeMonotonicityViolation(RuntimeError):
    """Raised when a hop in the provenance chain widens scope relative to its parent."""
    pass


def admit_federated_delegation(
    attestation: dict,
    provenance: list[dict],
    trust_roots: set[str],
    degraded_attribution_allowed: bool = False,
) -> dict:
    """
    Admit a cross-org delegation only if the provenance chain is complete,
    root-reachable, scope-monotone, and temporally contained.

    Returns the audit record to persist. Raises on any invariant violation.
    """
    if not provenance:
        raise ProvenanceChainTruncated(
            f"delegation from {attestation.get('issuer')} carries no provenance chain; "
            f"attestation is valid but authority root is unreachable"
        )

    # Walk the chain backward from the presented attestation.
    chain = list(provenance) + [attestation]
    for i in range(len(chain) - 1, 0, -1):
        child, parent = chain[i], chain[i - 1]

        # C2: edge continuity — the parent's issuer must be the child's principal.
        if parent.get("issuer") != child.get("principal"):
            raise ProvenanceChainTruncated(
                f"edge discontinuity at hop {i}: parent issuer {parent.get('issuer')} "
                f"!= child principal {child.get('principal')}"
            )

        # C3: scope monotonicity — child scope must be subset of parent scope.
        if not set(child.get("scope", [])).issubset(set(parent.get("scope", []))):
            raise ScopeMonotonicityViolation(
                f"scope widened at hop {i}: child {child.get('scope')} "
                f"not subset of parent {parent.get('scope')}"
            )

        # C4: temporal containment.
        if child.get("exp", 0) > parent.get("exp", 0):
            raise ProvenanceChainTruncated(
                f"temporal containment violated at hop {i}: child exp {child.get('exp')} "
                f"exceeds parent exp {parent.get('exp')}"
            )

    # C1: root reachability.
    resolved_root = chain[0].get("issuer")
    if resolved_root not in trust_roots:
        if not degraded_attribution_allowed:
            raise ProvenanceChainTruncated(
                f"chain terminates at {resolved_root}, which is not a recognized trust root; "
                f"refusing admission (fail-closed on truncation)"
            )
        # Degraded path: admit but flag the record for out-of-band root notification.
        return {
            "admitted": True,
            "degraded": True,
            "resolved_root": resolved_root,
            "chain_hash": _hash_chain(chain),
            "flag": "provenance_truncated",
            "notify_root_org": resolved_root,
        }

    return {
        "admitted": True,
        "degraded": False,
        "resolved_root": resolved_root,
        "chain_hash": _hash_chain(chain),
        "principal": attestation.get("principal"),
        "attested_by": attestation.get("issuer"),
    }


def _hash_chain(chain: list[dict]) -> str:
    import hashlib, json
    payload = json.dumps(chain, sort_keys=True).encode()
    return hashlib.sha256(payload).hexdigest()
