# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-artifact-chunk-stream-has-silently-desynchronized-from-its-task-envelope.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-artifact-chunk-stream-has-silently-desynchronized-from-its-task-envelope.warrant.json
# Markdown SHA-256:   4b16be113bcb24fbedefc82052fecaa714f413e824e822928daf21be28e48efb
# Code AST SHA-256:   612a9ca51f712f1c8e46f6493c2a17277764ef7110a7e20de5097fd04876f613
# Verified Classes:   ArtifactStreamDesync, ArtifactReassembler
# Defensive Guards:   7 fail-closed invariants (zero external deps)

class ArtifactStreamDesync(RuntimeError):
    """Raised when an A2A v1.0 artifact chunk stream terminates cleanly
    but the reassembled byte extent is inconsistent with the append chain."""
    pass


class ArtifactReassembler:
    def __init__(self, artifact_id: str):
        self.artifact_id = artifact_id
        self.buffer = bytearray()
        self.expected_offset = 0
        self.sealed = False

    def ingest(self, chunk: dict) -> None:
        if self.sealed:
            raise ArtifactStreamDesync(
                f"chunk arrived after seal for artifact {self.artifact_id}"
            )

        start = chunk["start_offset"]
        end = chunk["end_offset"]
        append = chunk["append"]
        last = chunk["lastChunk"]

        if append:
            if start != self.expected_offset:
                raise ArtifactStreamDesync(
                    f"append chunk start {start} != expected {self.expected_offset} "
                    f"for artifact {self.artifact_id}"
                )
            self.buffer.extend(chunk["data"])
            self.expected_offset = end
        else:
            # Replacement semantics: legal only as a full re-send (end matches
            # prior extent) or as a non-terminal reset from offset 0.
            if start != 0:
                raise ArtifactStreamDesync(
                    f"replacement chunk must start at 0, got {start} "
                    f"for artifact {self.artifact_id}"
                )
            if last and end < self.expected_offset:
                raise ArtifactStreamDesync(
                    f"terminal replacement chunk ends at {end} but append chain "
                    f"reached {self.expected_offset}; truncation, not completion, "
                    f"for artifact {self.artifact_id}"
                )
            self.buffer = bytearray(chunk["data"])
            self.expected_offset = end

        if last:
            if end != self.expected_offset:
                raise ArtifactStreamDesync(
                    f"terminal chunk end {end} != expected {self.expected_offset} "
                    f"for artifact {self.artifact_id}"
                )
            self.sealed = True

    def finalize(self, task_state: str) -> bytes:
        if task_state == "completed" and not self.sealed:
            raise ArtifactStreamDesync(
                f"task completed but artifact {self.artifact_id} never sealed"
            )
        if not self.sealed:
            raise ArtifactStreamDesync(
                f"artifact {self.artifact_id} finalized without terminal chunk"
            )
        return bytes(self.buffer)
