# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-capability-downgrade-during-a2a-v1-0-cross-organization-task-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-capability-downgrade-during-a2a-v1-0-cross-organization-task-delegation.warrant.json
# Markdown SHA-256:   997aee994c7f52c03aaa7763187647a75ea940f0fba6483875575a7cda92292f
# Code AST SHA-256:   5f8f2d9cfab5843bdcd02ca1aceaef44d2d8fe4fa8bfef9f7ef121cb9a20b625
# Verified Classes:   CapabilityDowngradeError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CapabilityDowngradeError(RuntimeError):
    """Raised when a callee's completed artifact does not entail the caller's required capability predicate."""
    pass


def verify_capability_entailment(
    artifact: dict,
    required_predicate,
    task_handle: str,
) -> None:
    """
    Gate a delegated A2A task's transition to 'completed' on response-side entailment.

    artifact: parsed JSON returned by the callee.
    required_predicate: callable(artifact) -> bool, encoding the caller's true
        downstream requirement (NOT the transport schema).
    task_handle: retained A2A task id, kept resumable until this passes.
    """
    if not isinstance(artifact, dict):
        raise CapabilityDowngradeError(
            f"task {task_handle}: artifact is not a JSON object; cannot evaluate entailment"
        )

    try:
        satisfied = bool(required_predicate(artifact))
    except Exception as exc:
        # A predicate that cannot even be evaluated is a downgrade, not a pass.
        raise CapabilityDowngradeError(
            f"task {task_handle}: capability predicate raised {type(exc).__name__}: {exc}; "
            f"retaining handle for re-delegation"
        ) from exc

    if not satisfied:
        raise CapabilityDowngradeError(
            f"task {task_handle}: callee returned TaskState.completed but artifact does not "
            f"entail caller's required capability predicate; "
            f"refusing completion, task handle retained for re-delegation with tightened requirement"
        )


def obligations_have_ledger_fields(artifact: dict) -> bool:
    """Example predicate: every obligation carries the fields the compliance ledger joins on."""
    obligations = artifact.get("obligations")
    if not isinstance(obligations, list) or not obligations:
        return False
    required = {"party", "deadline", "clause_ref"}
    return all(
        isinstance(o, dict) and required.issubset(o.keys()) and all(o[k] is not None for k in required)
        for o in obligations
    )


# Usage at the A2A completion boundary:
# verify_capability_entailment(artifact, obligations_have_ledger_fields, task_handle="a2a-task-7f3c")
