# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a2a-v1-0-terminal-state-divergence-when-a-peer-s-task-reports-completed-but-its-artifact-stream-never-closes-the-working.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a2a-v1-0-terminal-state-divergence-when-a-peer-s-task-reports-completed-but-its-artifact-stream-never-closes-the-working.warrant.json
# Markdown SHA-256:   8350134b8cf8d7dc2d8ee716a44d87899bef1819d5b55d2ef10985bb39d1a0c0
# Code AST SHA-256:   f6e85fbef6b95278f7dff2492f9458ddc21b0da4c55fbb9c761888a9ad32ca42
# Verified Classes:   ArtifactClosureViolation
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ArtifactClosureViolation(RuntimeError):
    """Raised when a task reports completed before all artifact streams close."""
    pass


def reconcile_terminal_task(
    task_id: str,
    observed_artifacts: dict[str, bool],   # artifact_id -> saw_last_chunk
    final_status_seen: bool,
    remote_artifacts: dict[str, bytes],
) -> str:
    """
    Promote a task to 'completed' only if every opened artifact stream
    closed with lastChunk before the terminal status frame.
    """
    if not final_status_seen:
        return "working"

    open_ids = {aid for aid, closed in observed_artifacts.items() if not closed}
    if not open_ids:
        return "completed"

    # Status says done, artifact channel disagrees. Reconcile against tasks/get.
    missing_remote = open_ids - remote_artifacts.keys()
    if missing_remote:
        raise ArtifactClosureViolation(
            f"task {task_id}: status=completed but artifact streams "
            f"{sorted(missing_remote)} never emitted lastChunk and are "
            f"absent from tasks/get; refusing to promote to completed"
        )

    # Remote has the bytes but the stream truncated: repair locally, still flag.
    return "completed_unverified_artifacts"
