# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-resumed-a2a-task-whose-taskstatus-state-is-terminal-but-whose-artifact-stream-is-non-final-the-terminal-state-artifact.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-resumed-a2a-task-whose-taskstatus-state-is-terminal-but-whose-artifact-stream-is-non-final-the-terminal-state-artifact.warrant.json
# Markdown SHA-256:   bc78406572e47eb720d479869a171b8c37959543d3839dd0342b2c2f57f93327
# Code AST SHA-256:   38ce551394c5e37ce094204cc3f3d548b1ce0e5ce590cb5c57f6d664a0f3537a
# Verified Classes:   TaskState, TaskClosureViolation, TaskRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import enum
from dataclasses import dataclass
from typing import Optional


class TaskState(enum.Enum):
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"

    @property
    def is_terminal(self) -> bool:
        return self in (TaskState.COMPLETED, TaskState.FAILED, TaskState.CANCELED)


class TaskClosureViolation(RuntimeError):
    """Raised when a terminal task's artifact stream is open or of unknown closure."""


@dataclass(frozen=True)
class TaskRecord:
    task_id: str
    state: TaskState
    # Durable closure marker: True iff a final artifact chunk + final status
    # event were committed. None means the store could not be read.
    stream_closed: Optional[bool]


def handle_resume(record: TaskRecord) -> str:
    """Decide whether a tasks/resume for `record` may be served idempotently.

    Returns "idempotent-noop" for terminal+closed and "resume-from-checkpoint"
    for in-flight states. Raises TaskClosureViolation for terminal+open and
    terminal+unknown, forcing the caller into explicit reconciliation.
    """
    if not record.state.is_terminal:
        # In-flight: re-drive from checkpoint is allowed and append-only.
        return "resume-from-checkpoint"

    if record.stream_closed is True:
        # Terminal and durably closed: safe idempotent replay.
        return "idempotent-noop"

    # Terminal + open, or terminal + unknown. Unknown is treated as open:
    # a spurious refusal costs one reconcile; a spurious adoption costs
    # silent truncation or duplicated artifacts.
    closure = "open" if record.stream_closed is False else "unknown"
    raise TaskClosureViolation(
        f"task {record.task_id}: state={record.state.value} but artifact "
        f"stream closure={closure}; refusing idempotent resume. "
        f"Require tasks/reconcile (adopt-partial or restart-new-id)."
    )


def resume_or_reconcile(record: TaskRecord) -> str:
    try:
        return handle_resume(record)
    except TaskClosureViolation as exc:
        # Surface to the orchestrator as a non-retryable reconcile trigger.
        return f"RECONCILE_REQUIRED: {exc}"
