# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-shared-memory-provenance-chain-after-a-multi-hop-write-and-how-does-the-provenance-laundering-boundary-m.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-distrust-a-shared-memory-provenance-chain-after-a-multi-hop-write-and-how-does-the-provenance-laundering-boundary-m.warrant.json
# Markdown SHA-256:   31a2a783a17a19b4cdbf12ef9ab56ec89de7a087118b304ed912bc060b6c06c7
# Code AST SHA-256:   08fda893b9ec13ab48fe882f3799b2e2d01173bcc6cf8bb87fc84a6dcaf3a221
# Verified Classes:   ProvenanceLaunderingError, ProvenanceEdge
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ProvenanceLaunderingError(RuntimeError):
    """Raised when a shared-memory provenance chain fails edge-level fidelity checks."""
    pass


@dataclass(frozen=True)
class ProvenanceEdge:
    parent_id: str
    parent_origin: str
    parent_content_hash: str
    child_id: str
    child_content: str
    written_by: str
    writer_scopes: frozenset          # namespaces this writer may write into
    transform_descriptor: str
    transform_commitment: str | None  # H(parent_hash, child_hash, descriptor), origin-signed
    epoch: int


def _commitment(parent_hash: str, child_content: str, descriptor: str) -> str:
    h = hashlib.sha256()
    h.update(parent_hash.encode())
    h.update(hashlib.sha256(child_content.encode()).digest())
    h.update(descriptor.encode())
    return h.hexdigest()


def validate_edge(edge: ProvenanceEdge, parent_epoch: int, fanout: int, k_max: int = 8) -> None:
    # 1. Edge authorship must be authorized in the parent's origin namespace.
    if edge.parent_origin not in edge.writer_scopes:
        raise ProvenanceLaunderingError(
            f"edge {edge.parent_id}->{edge.child_id}: writer '{edge.written_by}' "
            f"lacks scope on parent origin '{edge.parent_origin}' (laundered edge)"
        )

    # 2. Transformation commitment must exist and recompute.
    if edge.transform_commitment is None:
        raise ProvenanceLaunderingError(
            f"edge {edge.parent_id}->{edge.child_id}: missing transform commitment"
        )
    expected = _commitment(edge.parent_content_hash, edge.child_content, edge.transform_descriptor)
    if expected != edge.transform_commitment:
        raise ProvenanceLaunderingError(
            f"edge {edge.parent_id}->{edge.child_id}: transform commitment mismatch "
            f"(expected {expected[:12]}..., got {edge.transform_commitment[:12]}...)"
        )

    # 3. Epoch must strictly advance.
    if edge.epoch <= parent_epoch:
        raise ProvenanceLaunderingError(
            f"edge {edge.parent_id}->{edge.child_id}: epoch inversion "
            f"({edge.epoch} <= parent {parent_epoch})"
        )

    # 4. Fan-out anomaly.
    if fanout > k_max:
        raise ProvenanceLaunderingError(
            f"edge {edge.parent_id}->{edge.child_id}: fan-out {fanout} exceeds bound {k_max}"
        )
