# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-treat-a-terminal-a2a-task-state-as-authoritative-when-signed-artifacts-are-still-in-flight-across-an-orga.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-treat-a-terminal-a2a-task-state-as-authoritative-when-signed-artifacts-are-still-in-flight-across-an-orga.warrant.json
# Markdown SHA-256:   020b6c2515d04298193bb5528767dc2a1ee2212097923b60f1d4ec407862b405
# Code AST SHA-256:   ebc9f76c993d133135d980a0c0449e5a8990dd299cdffe06d31097bd1ed74de5
# Verified Classes:   ArtifactIntegrityError, TaskView, SignedArtifact, TaskState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class ArtifactIntegrityError(RuntimeError):
    """Raised when artifact quiescence cannot be established safely."""
    pass


class TaskView(Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"
    AWAITING_QUIESCENCE = "awaiting-artifact-quiescence"
    INDETERMINATE = "indeterminate"


@dataclass
class SignedArtifact:
    artifact_id: str
    content: bytes
    signature: Optional[bytes]
    expected_signer: str


@dataclass
class TaskState:
    task_id: str
    remote_state: TaskView
    declared_artifacts: list[str] = field(default_factory=list)
    received: dict[str, SignedArtifact] = field(default_factory=dict)
    quiescence_deadline_sec: float = 300.0


def _content_hash(art: SignedArtifact) -> str:
    return hashlib.sha256(art.content).hexdigest()


def verify_and_quiesce(state: TaskState, elapsed_sec: float,
                       verifier) -> TaskView:
    """
    Transition the local view of a task toward terminal ONLY after every
    declared artifact (including detached signatures) has been received,
    signature-verified, and content-deduplicated.

    Must be called instead of trusting a remote terminal state directly.
    """
    if state.remote_state not in (
        TaskView.COMPLETED, TaskView.FAILED, TaskView.CANCELED
    ):
        return state.remote_state

    # Terminal state observed; do NOT finalize. Enter quiescence gate.
    seen_hashes: dict[str, str] = {}
    for ref in state.declared_artifacts:
        art = state.received.get(ref)
        if art is None:
            if elapsed_sec >= state.quiescence_deadline_sec:
                # Not a failure: provider may still be replicating.
                return TaskView.INDETERMINATE
            return TaskView.AWAITING_QUIESCENCE

        if art.signature is None:
            raise ArtifactIntegrityError(
                f"task {state.task_id}: artifact {ref} has no signature; "
                f"refusing to trust unverified cross-org artifact"
            )
        if not verifier(art.content, art.signature, art.expected_signer):
            raise ArtifactIntegrityError(
                f"task {state.task_id}: signature verification failed for "
                f"artifact {ref} (expected signer {art.expected_signer})"
            )

        h = _content_hash(art)
        prior = seen_hashes.get(h)
        if prior is not None and prior != ref:
            # Same content under two logical refs: collapse, do not double-count.
            continue
        if prior is not None and prior == ref:
            # Same ref, same content, duplicate delivery: idempotent.
            continue
        seen_hashes[h] = ref

    # All declared artifacts quiesced and verified.
    return state.remote_state
