# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-accept-a-federated-peer-s-attestation-chain-when-the-trust-anchor-is-co-resident-with-the-attested-worklo.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-accept-a-federated-peer-s-attestation-chain-when-the-trust-anchor-is-co-resident-with-the-attested-worklo.warrant.json
# Markdown SHA-256:   6905221113ab0a7a5f0054012fc6e587e45b3cc01d8e0e480a8767f29b1059ee
# Code AST SHA-256:   c729e66798a9ead608827ba787840f21ab09ed8636d85d58e620109dd8d6c06b
# Verified Classes:   AnchorIndependenceViolation, AnchorProvenance
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class AnchorIndependenceViolation(RuntimeError):
    """Raised when a federated peer's attestation chain verifies but its
    trust anchor cannot be shown independent of the attested workload."""
    pass


class AnchorProvenance:
    OUT_OF_BAND = "out_of_band_enrollment"   # anchor obtained during onboarding
    RUNTIME_FETCH = "runtime_fetch"           # anchor fetched at handshake -> untrusted


def admit_federated_peer(
    peer_id: str,
    chain_verifies: bool,
    anchor_provenance: str,
    anchor_principal: str,
    workload_principal: str,
    measurement: str,
    expected_measurements: set[str],
    requested_capabilities: list[str],
    mutating_capabilities: set[str],
) -> dict:
    if not chain_verifies:
        raise AnchorIndependenceViolation(
            f"{peer_id}: chain does not verify; refuse outright"
        )

    # Anchor independence is the load-bearing check, not chain validity.
    anchor_independent = (
        anchor_provenance == AnchorProvenance.OUT_OF_BAND
        and anchor_principal != workload_principal
    )

    if not anchor_independent:
        # Chain is a self-assertion. Downgrade to probationary.
        granted = [c for c in requested_capabilities if c not in mutating_capabilities]
        denied = [c for c in requested_capabilities if c in mutating_capabilities]
        return {
            "peer_id": peer_id,
            "class": "probationary",
            "granted": granted,
            "denied": denied,
            "reason": "anchor co-resident with workload principal; "
                      "no state-mutating capability without out-of-band confirmation",
        }

    if measurement not in expected_measurements:
        raise AnchorIndependenceViolation(
            f"{peer_id}: independent anchor verified measurement {measurement!r} "
            f"not in allowlist; refusing admission"
        )

    return {
        "peer_id": peer_id,
        "class": "trusted",
        "granted": requested_capabilities,
        "denied": [],
        "reason": "anchor independent, measurement allowlisted",
    }
