# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-causal-attribution-failure-when-tool-outputs-mutate-the-agent-context-across-multi-hop-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-causal-attribution-failure-when-tool-outputs-mutate-the-agent-context-across-multi-hop-traces.warrant.json
# Markdown SHA-256:   a8da693b5276e41c67ef52c50635d819dd83acc066a75066ba906364737502fc
# Code AST SHA-256:   64e9982f8eefee583204a361dfc16dd89e5421fc8227756d69d90cb58f496060
# Verified Classes:   MutationOpacityError, Hop
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class MutationOpacityError(RuntimeError):
    """Raised when a hop mutates context without emitting a delta record,
    making downstream causal attribution unsound."""
    pass


@dataclass
class Hop:
    hop_id: str
    input_tokens: int
    output_tokens: int
    effective_context_hash: str
    mutation_event: dict | None = None  # {'inserted': [...], 'removed': [...]}
    compaction_threshold: float = 0.85


def verify_attribution_chain(hops: list[Hop]) -> list[tuple[str, str]]:
    """Return sound causal edges. Refuse to draw edges through opaque lossy hops."""
    edges: list[tuple[str, str]] = []
    for prev, cur in zip(hops, hops[1:]):
        ratio = cur.output_tokens / max(prev.output_tokens, 1)
        lossy = ratio < cur.compaction_threshold or cur.output_tokens < prev.output_tokens
        if lossy and cur.mutation_event is None:
            raise MutationOpacityError(
                f"hop {cur.hop_id} reduced context "
                f"({prev.output_tokens}->{cur.output_tokens}, ratio={ratio:.2f}) "
                f"with no mutation_event; effective_context_hash="
                f"{cur.effective_context_hash[:12]} is not derivable from "
                f"{prev.effective_context_hash[:12]}. Downstream edges unsound."
            )
        if cur.mutation_event is not None:
            # Recompute hash from prev hash + recorded delta; must match.
            manifest = repr(sorted(cur.mutation_event.get("removed", []))) + \
                       repr(sorted(cur.mutation_event.get("inserted", [])))
            derived = hashlib.sha256(
                (prev.effective_context_hash + manifest).encode()
            ).hexdigest()
            if derived != cur.effective_context_hash:
                raise MutationOpacityError(
                    f"hop {cur.hop_id}: recorded delta does not derive "
                    f"effective_context_hash; attribution chain broken."
                )
        edges.append((prev.hop_id, cur.hop_id))
    return edges
