# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-streamed-a2a-artifact-whose-schema-hash-matches-but-whose-multipart-part-ordering-violates-the-producer-s-canonicalizati.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-streamed-a2a-artifact-whose-schema-hash-matches-but-whose-multipart-part-ordering-violates-the-producer-s-canonicalizati.warrant.json
# Markdown SHA-256:   3a9cd237aa728846953dcc4732df7c0f5299c0774f1b1e1b7ecf4f9be6fe84b1
# Code AST SHA-256:   04e31ad3edb14eabaa0d64af31b0b7fc64326f83c44bc7f03cc29dbce2a7b8ac
# Verified Classes:   ScopeCommitmentError, Part, StreamState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Dict, List, Optional


class ScopeCommitmentError(RuntimeError):
    """Raised when a streamed A2A artifact's scope set is not closed before token exchange."""
    pass


@dataclass
class Part:
    index: int
    kind: str
    body: dict


@dataclass
class StreamState:
    parts_seen: Dict[int, Part] = field(default_factory=dict)
    scopes_declared: List[str] = field(default_factory=list)
    scope_commitment: Optional[str] = None
    tokens_minted: List[str] = field(default_factory=list)


def canonical_scope_hash(scopes: List[str]) -> str:
    canonical = json.dumps(sorted(set(scopes)), separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def on_part_arrived(state: StreamState, part: Part, *, streaming: bool) -> None:
    state.parts_seen[part.index] = part
    if part.kind == "manifest":
        state.scope_commitment = part.body.get("scope_commitment")
        state.scopes_declared.extend(part.body.get("required_scopes", []))
    elif part.kind == "scope_extension":
        state.scopes_declared.extend(part.body.get("required_scopes", []))

    # The boundary: a scope-bearing part arrived, and we are about to mint.
    # If we are streaming and the commitment is not yet verified against the
    # union seen so far, we must not mint — the scope set is not closed.
    if streaming and part.kind in ("manifest", "scope_extension"):
        if state.scope_commitment is None:
            raise ScopeCommitmentError(
                f"part[{part.index}] ({part.kind}) arrived under stream-and-exchange "
                f"but manifest carries no scope_commitment; scope set is not closed. "
                f"Fall back to buffer-and-exchange or refuse the task."
            )
        observed = canonical_scope_hash(state.scopes_declared)
        if observed != state.scope_commitment:
            raise ScopeCommitmentError(
                f"scope_commitment mismatch after part[{part.index}]: "
                f"declared union hashes to {observed}, manifest committed to "
                f"{state.scope_commitment}. A scope-bearing part is missing or "
                f"out of canonical order; token exchange would authorize against "
                f"a partial scope set."
            )
    state.tokens_minted.append(f"token:{part.kind}")


def drive_stream(parts: List[Part], *, streaming: bool) -> StreamState:
    state = StreamState()
    for p in parts:
        on_part_arrived(state, p, streaming=streaming)
    # End-of-stream: content hash would verify here, but authorization already drifted.
    return state


if __name__ == "__main__":
    # Producer canonical order is 2,0,3,1; transport emits 0,1,2,3.
    stream = [
        Part(0, "manifest", {"required_scopes": ["artifact:read"]}),  # no scope_commitment
        Part(1, "payload", {}),
        Part(2, "scope_extension", {"required_scopes": ["artifact:read", "artifact:write", "vault:export"]}),
        Part(3, "attestation", {}),
    ]
    try:
        drive_stream(stream, streaming=True)
    except ScopeCommitmentError as e:
        print(f"BLOCKED: {e}")
