# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-silent-artifact-schema-drift-between-an-a2a-agent-card-s-declared-defaultoutputmodes-and-the-artifact-parts-actually-emitt.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-silent-artifact-schema-drift-between-an-a2a-agent-card-s-declared-defaultoutputmodes-and-the-artifact-parts-actually-emitt.warrant.json
# Markdown SHA-256:   f0ba548240d338027a26245313e996d9acf647bd984c69c9741a12fbdd80d892
# Code AST SHA-256:   0e1ea6a11d42354ef9b0cd33bbd25aa37b88830dd92bbad10a0c84b5726b93e6
# Verified Classes:   ArtifactNegotiationViolation, TaskSchemaViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ArtifactNegotiationViolation(RuntimeError):
    """Raised when a server-completed A2A task emits an artifact whose
    mimeType or shape violates the mode negotiated at task creation.

    Distinct from transport failures: retrying will not fix this, because
    the divergence originates in the remote model's nondeterministic
    adherence to the negotiated output mode, not in infrastructure.
    """
    def __init__(self, task_id: str, negotiated_mode: str,
                 emitted_mode: str, part_index: int):
        self.task_id = task_id
        self.negotiated_mode = negotiated_mode
        self.emitted_mode = emitted_mode
        self.part_index = part_index
        super().__init__(
            f"task {task_id}: negotiated {negotiated_mode!r} but part "
            f"[{part_index}] emitted {emitted_mode!r}"
        )


class TaskSchemaViolation(RuntimeError):
    """Raised when an artifact matches the negotiated mimeType but fails
    validation against the skill's declared outputSchema."""
    def __init__(self, task_id: str, schema_uri: str, detail: str):
        self.task_id = task_id
        self.schema_uri = schema_uri
        self.detail = detail
        super().__init__(
            f"task {task_id}: artifact violates outputSchema {schema_uri}: {detail}"
        )


def verify_completed_task(task: dict, negotiated: dict, schema_validator) -> dict:
    """Enforce the invariant: a client-side 'completed' transition requires
    every emitted artifact part to match the negotiated mode and schema.

    `negotiated` carries the mode chosen at task creation and the resolved
    outputSchema (or None). `schema_validator` is a callable(payload, schema)
    that raises on mismatch.
    """
    task_id = task["id"]
    if task["status"]["state"] != "completed":
        return task  # invariant only binds the terminal transition

    negotiated_mode = negotiated["mimeType"]
    schema = negotiated.get("outputSchema")

    artifacts = task.get("artifacts", [])
    status_parts = task["status"].get("message", {}).get("parts", [])

    for source, parts in (("artifacts", [p for a in artifacts for p in a["parts"]]),
                          ("status.message", status_parts)):
        for idx, part in enumerate(parts):
            emitted_mode = part.get("metadata", {}).get("mimeType")
            if emitted_mode != negotiated_mode:
                raise ArtifactNegotiationViolation(
                    task_id, negotiated_mode, emitted_mode, idx
                )
            if schema is not None and emitted_mode == "application/json":
                try:
                    schema_validator(part["text"], schema)
                except Exception as e:  # validator-specific
                    raise TaskSchemaViolation(
                        task_id, negotiated.get("schemaUri", "<inline>"), str(e)
                    ) from e

    return task


def run_task_with_invariant(client, card, skill_id, prompt, max_transport_retries=3):
    """Retry budget applies only to transport failures. Negotiation and
    schema violations are terminal and surfaced as client-side 'failed'
    with a structured record, preserving reconcilability with the server log.
    """
    negotiated = {
        "mimeType": card["defaultOutputModes"][0],
        "outputSchema": next(
            (s.get("outputSchema") for s in card["skills"] if s["id"] == skill_id),
            None,
        ),
        "schemaUri": None,
    }
    transport_attempts = 0
    while True:
        try:
            task = client.create_and_wait(skill_id, prompt, negotiated["mimeType"])
            return verify_completed_task(task, negotiated, client.validate_schema)
        except (ArtifactNegotiationViolation, TaskSchemaViolation) as violation:
            client.record_failed(
                task_id=getattr(violation, "task_id", None),
                reason=type(violation).__name__,
                detail=str(violation),
                negotiated=negotiated,
            )
            raise  # terminal; do not consume transport retry budget
        except TransportError:
            transport_attempts += 1
            if transport_attempts > max_transport_retries:
                raise
