# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-trust-brokered-peer-s-policy-capability-claim-before-task-routing-and-how-does-warrant-scope-drift-cause-s.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-trust-brokered-peer-s-policy-capability-claim-before-task-routing-and-how-does-warrant-scope-drift-cause-s.warrant.json
# Markdown SHA-256:   2c11dc7b0727b8d58629358c6696384decea2a2886fdfd2611f1efd8d82bcf25
# Code AST SHA-256:   923e5a36e19fdb1c7dd59cf814508b706d9d758e1c0605b9348ed44cb7ae9f98
# Verified Classes:   WarrantScopeDriftError, SovereigntyViolationRisk
# Defensive Guards:   7 fail-closed invariants (zero external deps)

class WarrantScopeDriftError(RuntimeError):
    """Raised when broker attestation and peer manifest are not bound to the same warrant scope."""
    pass


class SovereigntyViolationRisk(RuntimeError):
    """Raised when a conditional manifest clause cannot be verified against operational state."""
    pass


def compose_routing_warrant(
    task: dict,
    broker_attestation: dict,
    peer_manifest: dict,
    operational_state: dict | None,
) -> dict:
    """
    Compose the effective warrant for a federated task route.
    Returns the intersected warrant or raises. Never returns a permissive
    default for a dimension any source is silent on.
    """
    # 1. Warrant binding: manifest digest must match what the broker attested.
    attested_digest = broker_attestation.get("manifest_digest")
    actual_digest = peer_manifest.get("digest")
    if attested_digest is None or actual_digest is None:
        raise WarrantScopeDriftError(
            f"missing manifest digest binding: broker={attested_digest!r} manifest={actual_digest!r}"
        )
    if attested_digest != actual_digest:
        raise WarrantScopeDriftError(
            f"broker attested manifest {attested_digest} but peer serves {actual_digest}; "
            "attestation is stale with respect to manifest"
        )

    # 2. Silence is not permission: every task dimension must be covered by both sources.
    for dim in ("data_class", "jurisdiction"):
        if dim not in broker_attestation.get("scope", {}):
            raise WarrantScopeDriftError(
                f"broker attestation silent on required dimension {dim!r}; cannot route"
            )
        if dim not in peer_manifest.get("scope", {}):
            raise WarrantScopeDriftError(
                f"peer manifest silent on required dimension {dim!r}; cannot route"
            )

    # 3. Conditional clauses must be evaluated against operational state, not merely listed.
    for clause in peer_manifest.get("conditional_clauses", []):
        if not _clause_triggered(clause, task):
            continue
        if operational_state is None:
            raise SovereigntyViolationRisk(
                f"task triggers condition {clause['name']!r} but no operational-state attestation available"
            )
        if not _clause_satisfied(clause, operational_state):
            raise SovereigntyViolationRisk(
                f"peer advertises {clause['name']!r} but operational state violates it: "
                f"{operational_state}"
            )

    # 4. Effective warrant is the intersection, not a union of permissives.
    effective = {}
    for dim in ("data_class", "jurisdiction"):
        broker_set = set(broker_attestation["scope"][dim])
        manifest_set = set(peer_manifest["scope"][dim])
        effective[dim] = broker_set & manifest_set
        if task[dim] not in effective[dim]:
            raise WarrantScopeDriftError(
                f"task {dim}={task[dim]!r} not in intersected warrant {effective[dim]!r}"
            )
    return effective


def _clause_triggered(clause: dict, task: dict) -> bool:
    return task.get("data_class") in clause.get("applies_to", [])


def _clause_satisfied(clause: dict, state: dict) -> bool:
    for key, bound in clause.get("constraints", {}).items():
        if state.get(key) != bound:
            return False
    return True
