# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-retrieved-memory-provenance-decay-and-the-poisoned-fragment-admission-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-retrieved-memory-provenance-decay-and-the-poisoned-fragment-admission-boundary.warrant.json
# Markdown SHA-256:   0bc59e1212a84613925f816b4c41bd5c6fd6895e9789b817fcfd2f8a922b80c5
# Code AST SHA-256:   177e91357f3de62e9433dcafd9faf6889da0efdb39f25ea865b94ab38cd66dea
# Verified Classes:   ProvenanceResidualError, Fragment
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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

TIER_RANK = {"WEB_SCRAPE": 0, "PEER_AGENT": 1, "TOOL_FETCH": 2, "USER_DIRECT": 3}


class ProvenanceResidualError(RuntimeError):
    """Raised when a fragment's provenance record is inconsistent with its bytes
    or its lineage, at the point of admission to an action-bearing context."""


@dataclass
class Fragment:
    fragment_id: str
    content: str
    content_hash: str
    ingest_tier: str
    derived_from: list[str] = field(default_factory=list)
    distilled_at: Optional[str] = None


def _h(s: str) -> str:
    return hashlib.sha256(s.encode("utf-8")).hexdigest()


def admission_gate(frag: Fragment, lineage: dict[str, Fragment],
                   action_bearing: bool) -> None:
    """Enforce content-scoped provenance before admitting frag to context.

    Raises ProvenanceResidualError if any residual is nonzero and the context
    is action-bearing. Logs (returns) otherwise.
    """
    hash_residual = 0 if frag.content_hash == _h(frag.content) else 1

    # tier_residual: tier must equal the minimum over the origin set.
    # A derived fragment with no lineage is the worst case: lineage_residual.
    if frag.derived_from:
        origin_tiers = []
        for fid in frag.derived_from:
            origin = lineage.get(fid)
            if origin is None:
                raise ProvenanceResidualError(
                    f"fragment {frag.fragment_id} claims derived_from {fid} "
                    f"but no such origin exists in lineage store"
                )
            origin_tiers.append(TIER_RANK[origin.ingest_tier])
        implied_tier = min(origin_tiers)
        tier_residual = max(0, TIER_RANK[frag.ingest_tier] - implied_tier)
        lineage_residual = 0
    else:
        tier_residual = 0
        # A distilled fragment with no derived_from was written by an
        # unaudited path; its hash may have been recomputed to match laundered
        # content, so hash equality is NOT exculpatory here.
        lineage_residual = 1 if frag.distilled_at is not None else 0

    residual = hash_residual + tier_residual + lineage_residual
    if residual == 0:
        return
    if action_bearing:
        raise ProvenanceResidualError(
            f"fragment {frag.fragment_id} blocked from action-bearing context: "
            f"hash_residual={hash_residual} tier_residual={tier_residual} "
            f"lineage_residual={lineage_residual}; route to re-derivation"
        )
    # Read-only context: admit but record. Caller is responsible for logging.
    return
