# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-forward-an-a2a-task-warrant-whose-mcp-tool-scope-was-silently-narrowed-by-an-intermediate-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-forward-an-a2a-task-warrant-whose-mcp-tool-scope-was-silently-narrowed-by-an-intermediate-agent.warrant.json
# Markdown SHA-256:   32ae7aef0864070db4f50024a458c7db3d062d15bd875544a8adb239b309ef64
# Code AST SHA-256:   a47bfd7cfb6344079016cd087cab4e3c2a41a059d2f88b61f9b48bfebeea62f0
# Verified Classes:   WarrantAttenuationError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class WarrantAttenuationError(RuntimeError):
    """Raised when a forwarding agent cannot prove that an outbound
    A2A warrant's effective MCP authority is a subset of the inbound
    warrant's effective authority against the receiving server's manifest."""


def forward_warrant(
    w_in: dict,
    w_out_scope: set[str],
    manifest_digest: dict | None,
    manifest_fresh: bool,
    delegation_covers_audience: bool,
) -> dict:
    """
    w_in: inbound warrant with keys scope (set[str]), audience, issued_at.
    w_out_scope: the scope the forwarder intends to send downstream.
    manifest_digest: signed manifest mapping scope strings -> tool bindings,
        or None if the forwarder could not fetch it.
    manifest_fresh: whether manifest_digest is within w_in's expiry window.
    delegation_covers_audience: whether the forwarder's delegation cert
        authorizes it to re-sign for the downstream audience.
    """
    # Case 1: verbatim forward is always sound.
    if w_out_scope == w_in["scope"]:
        if not delegation_covers_audience:
            raise WarrantAttenuationError(
                "verbatim forward requires delegation coverage for audience "
                f"{w_in['audience']!r}; forwarder cert does not cover it"
            )
        return {"scope": set(w_out_scope), "audience": w_in["audience"]}

    # Case 2: attenuation attempted. Require a fresh, signed manifest.
    if manifest_digest is None:
        raise WarrantAttenuationError(
            "cannot attenuate without downstream manifest digest; "
            "forward verbatim or escalate for origin re-issuance"
        )
    if not manifest_fresh:
        raise WarrantAttenuationError(
            "manifest digest is stale relative to warrant issued_at; "
            "effective-authority subset cannot be established"
        )

    # Case 3: re-derive effective authority on both sides.
    eff_in = _effective(w_in["scope"], manifest_digest)
    eff_out = _effective(w_out_scope, manifest_digest)
    extra = eff_out - eff_in
    if extra:
        # This is the observed failure: dropping a scope string triggered
        # a default-triggering branch and *added* a binding.
        raise WarrantAttenuationError(
            f"attenuation adds bindings {sorted(extra)} not present in inbound "
            f"warrant; scope removal is not monotone under this manifest"
        )

    if not delegation_covers_audience:
        raise WarrantAttenuationError(
            "forwarder delegation does not cover downstream audience; "
            "re-signed warrant would be a forgery despite valid signature"
        )

    return {
        "scope": set(w_out_scope),
        "audience": w_in["audience"],
        "manifest_digest": manifest_digest["digest"],
    }


def _effective(scope: set[str], manifest: dict) -> set[str]:
    """Resolve scope strings to concrete bindings via the manifest ACL,
    including default-triggering branches keyed on scope *absence*."""
    bindings: set[str] = set()
    acl = manifest["acl"]
    for s in scope:
        bindings |= set(acl.get(s, {}).get("grants", []))
    # Absence-triggered defaults: the failure mode observed in the field.
    for absent_trigger, grant in acl.get("defaults_on_absence", {}).items():
        if absent_trigger not in scope:
            bindings.add(grant)
    return bindings
