# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-federated-peer-s-trust-warrant-has-silently-degraded-from-delegation-authoritative-to-discovery-only-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-federated-peer-s-trust-warrant-has-silently-degraded-from-delegation-authoritative-to-discovery-only-mid-task.warrant.json
# Markdown SHA-256:   c725d64f0aebd34e19a4a8420c00a6bf6b19efa17577816e599824cbc985dbc9
# Code AST SHA-256:   88e18c7a73441f0ff58a5e8d3101ae54b36564e9f0473841c13fb521aa97fffc
# Verified Classes:   AuthorityDegradedError, AuthorityUnconfirmedError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class AuthorityDegradedError(RuntimeError):
    """Raised when a federated peer's response proves a narrower scope than the
    delegator's warrant asserted, indicating silent policy attenuation."""
    pass


class AuthorityUnconfirmedError(RuntimeError):
    """Raised when a peer response carries no signed authority assertion and the
    delegator cannot confirm the scope the operation executed under."""
    pass


REQUIRED_SCOPE = "task.execute"


def dispatch_and_confirm(peer, task_payload, warrant, require_assertion=True):
    """Dispatch a task and confirm the peer executed it under the asserted scope.

    Fails closed: a response that does not prove its scope is never treated as
    success, regardless of HTTP status or envelope schema.
    """
    response = peer.dispatch(task_payload, warrant=warrant)

    # A 200 with a partial envelope is NOT success. Authority is proven by the
    # assertion, not by the status code.
    assertion = response.get("authority_assertion")

    if assertion is None:
        if require_assertion:
            raise AuthorityUnconfirmedError(
                f"peer {peer.domain} returned no authority_assertion; "
                f"cannot confirm scope for {REQUIRED_SCOPE}"
            )
        # Conservative fallback: treat as unconfirmed, do not advance.
        return {"status": "authority_unconfirmed", "response": response}

    applied_scope = assertion.get("scope")
    if not _scope_covers(applied_scope, REQUIRED_SCOPE):
        raise AuthorityDegradedError(
            f"warrant valid but degraded: peer {peer.domain} applied scope "
            f"{applied_scope!r} < required {REQUIRED_SCOPE!r}; "
            f"warrant not_after={warrant.not_after} still unexpired"
        )

    if not _verify_assertion_signature(assertion, peer.trust_broker_pubkey):
        raise AuthorityUnconfirmedError(
            f"authority_assertion from {peer.domain} failed signature check"
        )

    return {"status": "confirmed", "response": response}


def _scope_covers(applied, required):
    # Scope lattice: execute ⊃ discover; a narrower applied scope does not cover.
    order = {"task.discover": 0, "task.execute": 1, "task.commit": 2}
    return order.get(applied, -1) >= order.get(required, 99)


def _verify_assertion_signature(assertion, pubkey):
    return assertion.get("signed_by") == pubkey and assertion.get("sig") is not None
