# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-task-whose-a2a-agent-card-signature-verifies-but-whose-capability-manifest-silently-resolves-against-the-wrong.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-task-whose-a2a-agent-card-signature-verifies-but-whose-capability-manifest-silently-resolves-against-the-wrong.warrant.json
# Markdown SHA-256:   4a1f6e418c1d9c849bbd2079fd149bd1b9e60dbf3c2f7b4298a0df32c5f90e6c
# Code AST SHA-256:   0127d8991f39bc1f56218316914e03ac081d4f7ee2a899e02a538fb5c11c6737
# Verified Classes:   SchemaGraphDivergence
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from typing import Any


class SchemaGraphDivergence(RuntimeError):
    """Raised when a delegated task's resolved schema graph does not match
    the schema digest carried in the task envelope, or when the envelope
    omits the digest entirely. Fail closed: never fall back to card-declared
    schema resolution against a process-local registry."""
    pass


def _jcs_canonicalize(obj: Any) -> bytes:
    # RFC 8785 JCS: sorted keys, minimal separators, UTF-8.
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


def _digest_resolved_schema(schema: dict) -> str:
    # The caller MUST pass a fully dereferenced schema (no $ref, no $id-keyed
    # cache lookup, no dialect fallback). We assert that precondition here
    # rather than silently resolving, because lazy resolution is the bug.
    if "$ref" in json.dumps(schema):
        raise SchemaGraphDivergence(
            "refusing to digest schema containing unresolved $ref; "
            "dereference before signing or digesting"
        )
    return "sha256:" + hashlib.sha256(_jcs_canonicalize(schema)).hexdigest()


def validate_delegated_task(
    task_envelope: dict,
    local_dereferenced_schema: dict,
    card_signature_verified: bool,
) -> None:
    # Signature verification is necessary but NOT sufficient. A verified card
    # with a divergent resolved schema graph is exactly the failure mode.
    if not card_signature_verified:
        raise SchemaGraphDivergence("card JWS did not verify; reject task")

    envelope_digest = task_envelope.get("schemaDigest")
    if not envelope_digest:
        # Do NOT fall back to the card's declared schema. Fail closed.
        raise SchemaGraphDivergence(
            "task envelope omits schemaDigest; cannot prove schema-graph "
            "identity across vendor runtimes; reject"
        )

    local_digest = _digest_resolved_schema(local_dereferenced_schema)
    if envelope_digest != local_digest:
        raise SchemaGraphDivergence(
            f"schema-graph divergence: envelope={envelope_digest} "
            f"local={local_digest}; delegatee registry resolved a different "
            f"graph than delegator serialized against; reject"
        )


def dispatch_delegated_task(task_envelope: dict, local_dereferenced_schema: dict) -> dict:
    validate_delegated_task(
        task_envelope=task_envelope,
        local_dereferenced_schema=local_dereferenced_schema,
        card_signature_verified=task_envelope.get("cardSignatureVerified", False),
    )
    # Only reached when schema-graph identity is proven.
    return {"state": "working", "taskId": task_envelope["taskId"]}
