# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-quarantine-taint-labels-that-survive-context-window-eviction-but-lose-their-provenance-edge.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-quarantine-taint-labels-that-survive-context-window-eviction-but-lose-their-provenance-edge.warrant.json
# Markdown SHA-256:   5f318f9e8abc7b89fc7e384c17160973c5379b14ed4d58f885c902255ce9dd9f
# Code AST SHA-256:   1465fa33494c459fd0a129bafbd6b592452406e06159241e3a00ef387af0f8b8
# Verified Classes:   ProvenanceDecayError, TaintSpan, ProvenanceStore
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ProvenanceDecayError(RuntimeError):
    """Raised when a taint label survives without a resolvable provenance edge."""


@dataclass
class TaintSpan:
    label: str                      # "clean" | "untrusted" | "unattributable"
    ref: Optional[str] = None       # sha256 of the edge record
    origin_call: Optional[str] = None
    principal: Optional[str] = None


class ProvenanceStore:
    """Out-of-band edge table. Context only carries `ref`; edges live here."""

    def __init__(self) -> None:
        self._edges: dict[str, dict] = {}

    def record(self, call_id: str, principal: str, byte_range: tuple[int, int]) -> str:
        payload = f"{call_id}|{principal}|{byte_range[0]}:{byte_range[1]}"
        ref = "sha256:" + hashlib.sha256(payload.encode()).hexdigest()
        self._edges[ref] = {
            "call_id": call_id,
            "principal": principal,
            "byte_range": byte_range,
        }
        return ref

    def resolve(self, ref: str) -> Optional[dict]:
        return self._edges.get(ref)


def resolve_trust(span: TaintSpan, store: ProvenanceStore) -> str:
    """Resolve a span to a trust level. Missing edge => top of lattice."""
    if span.label == "clean":
        return "clean"
    if span.ref is None:
        # Label present, edge absent: promote, never default to permissive.
        return "unattributable"
    edge = store.resolve(span.ref)
    if edge is None:
        return "unattributable"
    if edge["principal"] != "internal":
        return "untrusted"
    return "clean"


def guard_privileged_compose(spans: list[TaintSpan], store: ProvenanceStore) -> None:
    """Block composition of privileged payloads from tainted or unattributable spans."""
    for span in spans:
        trust = resolve_trust(span, store)
        if trust == "unattributable":
            raise ProvenanceDecayError(
                f"span carries label={span.label!r} but ref={span.ref!r} "
                f"does not resolve; provenance edge lost during compaction"
            )
        if trust == "untrusted":
            raise ProvenanceDecayError(
                f"span from principal={span.principal!r} via call={span.origin_call!r} "
                f"is untrusted; privileged composition denied"
            )


def compact_summary(spans: list[TaintSpan], store: ProvenanceStore) -> list[TaintSpan]:
    """Compaction must preserve edges. If it cannot, promote to unattributable."""
    out: list[TaintSpan] = []
    for span in spans:
        if span.label == "untrusted" and span.ref is None:
            out.append(TaintSpan(label="unattributable", ref=None))
        else:
            out.append(span)
    return out
