# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-federated-agent-identity-attestation-has-silently-degraded-to-a-self-signed-trust-anchor-at-an-organizational-bound.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-federated-agent-identity-attestation-has-silently-degraded-to-a-self-signed-trust-anchor-at-an-organizational-bound.warrant.json
# Markdown SHA-256:   090df3de41c21b131ced5e02246262a09c3535014934aa240b900975f07acfda
# Code AST SHA-256:   9ef6e958d23c6aac2e106c4615ba89bdb85e3a19b5efdf1be4edf87b928166b6
# Verified Classes:   ProvenanceCollapseError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ProvenanceCollapseError(RuntimeError):
    """Raised when a federated warrant's delegation chain cannot be traced
    to an out-of-band federation root, indicating a self-signed fallback."""
    pass


FEDERATION_REGISTRY = {
    "org-a-root": {"depth": 0, "capabilities": {"plan", "delegate"}},
    "org-b-intermediate": {"depth": 1, "capabilities": {"execute", "delegate"}},
    "org-c-leaf": {"depth": 2, "capabilities": {"audit"}},
}

MIN_CHAIN_DEPTH = {"audit": 2, "execute": 1, "plan": 0}


def verify_warrant(warrant: dict, required_capability: str) -> bool:
    """
    warrant = {
        "chain": ["org-a-root", "org-b-intermediate", "org-c-leaf"],
        "capability": "audit",
        "signature_valid": True,
    }
    The signature being valid is necessary but NOT sufficient. We must also
    confirm every issuer in the chain resolves in the out-of-band registry
    and that the chain is deep enough for the requested capability.
    """
    chain = warrant.get("chain", [])
    if not warrant.get("signature_valid"):
        raise ProvenanceCollapseError("signature invalid; reject outright")

    # Invariant 1: every issuer must be a known federation member.
    # A locally-minted issuer like 'org-b-local' is absent here by construction.
    for issuer in chain:
        if issuer not in FEDERATION_REGISTRY:
            raise ProvenanceCollapseError(
                f"issuer {issuer!r} not in federation registry — "
                f"provenance collapsed to a self-signed anchor"
            )

    # Invariant 2: chain depth floor for the requested capability.
    floor = MIN_CHAIN_DEPTH.get(required_capability, 0)
    if len(chain) - 1 < floor:
        raise ProvenanceCollapseError(
            f"chain depth {len(chain) - 1} below floor {floor} for "
            f"capability {required_capability!r}; self-attestation suspected"
        )

    # Invariant 3: the terminal issuer must actually hold the capability.
    terminal = chain[-1]
    if required_capability not in FEDERATION_REGISTRY[terminal]["capabilities"]:
        raise ProvenanceCollapseError(
            f"terminal issuer {terminal!r} does not hold {required_capability!r}"
        )
    return True


def handle_handoff(warrant: dict, required_capability: str) -> str:
    try:
        verify_warrant(warrant, required_capability)
    except ProvenanceCollapseError as e:
        # Fail closed: reject the handoff, do not fall back to local trust.
        return f"REJECTED: {e}"
    return "ACCEPTED"
