# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-provenance-graph-reconstructed-attribution-edges-that-pass-schema-validation-while-silently-re-parenting-the-wr.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-provenance-graph-reconstructed-attribution-edges-that-pass-schema-validation-while-silently-re-parenting-the-wr.warrant.json
# Markdown SHA-256:   0e482e08e124a93feb1309a108b3d72fe661c092b8eacd497eaad06a26bd6c59
# Code AST SHA-256:   680fa4b0bd2d7312eca12d5413edb8ceffc77328d1e126487c30220e87856d6c
# Verified Classes:   ProvenanceAttributionError, RetrievalEvent, PackerEvent, ActionEvent, AttributionEdge
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ProvenanceAttributionError(RuntimeError):
    """Raised when an attribution edge cannot be causally justified."""
    pass


@dataclass
class RetrievalEvent:
    step: int
    item_ids: list[str]
    content_hashes: dict[str, str]  # id -> hash at retrieval time


@dataclass
class PackerEvent:
    step: int
    effective_item_ids: list[str]  # post-truncation, what the model actually saw


@dataclass
class ActionEvent:
    step: int
    tool: str


@dataclass
class AttributionEdge:
    item_id: str
    action_step: int
    edge_type: str  # "attribution" | "co_occurrence" | "stale_source"
    content_hash: Optional[str] = None


def compile_edges(
    retrieval: RetrievalEvent,
    packer: Optional[PackerEvent],
    action: ActionEvent,
    store_hash_now: dict[str, str],
) -> list[AttributionEdge]:
    edges: list[AttributionEdge] = []

    if packer is None:
        # Membership unverified: cannot claim attribution across the gap.
        for item_id in retrieval.item_ids:
            edges.append(AttributionEdge(item_id, action.step, "co_occurrence"))
        return edges

    effective = set(packer.effective_item_ids)
    for item_id in retrieval.item_ids:
        if item_id not in effective:
            # Dropped before the model saw it: record the near-miss, never attribute.
            edges.append(AttributionEdge(item_id, action.step, "co_occurrence"))
            continue
        retrieved_hash = retrieval.content_hashes.get(item_id)
        if retrieved_hash is None or store_hash_now.get(item_id) != retrieved_hash:
            edges.append(AttributionEdge(item_id, action.step, "stale_source"))
            continue
        edges.append(AttributionEdge(item_id, action.step, "attribution", retrieved_hash))
    return edges


def assert_edge_is_attributable(edge: AttributionEdge) -> None:
    if edge.edge_type != "attribution":
        raise ProvenanceAttributionError(
            f"edge {edge.item_id}->a{edge.action_step} is typed {edge.edge_type!r}; "
            f"cannot be used for rollback, quarantine, or memory pinning"
        )
    if edge.content_hash is None:
        raise ProvenanceAttributionError(
            f"attribution edge {edge.item_id}->a{edge.action_step} lacks a content hash; "
            f"mutable-ID edges are invalid under shared-store mutation"
        )


def rollback_targets(edges: list[AttributionEdge], poisoned_hash: str) -> list[int]:
    targets = []
    for e in edges:
        try:
            assert_edge_is_attributable(e)
        except ProvenanceAttributionError:
            continue  # co_occurrence / stale_source never trigger rollback
        if e.content_hash == poisoned_hash:
            targets.append(e.action_step)
    return targets
