# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-hierarchical-context-folding-when-a-child-summary-s-provenance-anchors-have-been-evicted-from-the-parent.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-hierarchical-context-folding-when-a-child-summary-s-provenance-anchors-have-been-evicted-from-the-parent.warrant.json
# Markdown SHA-256:   74ff1fa589aaa988e15adecfa441807e546d8a13a3050d25087c16ab178eac78
# Code AST SHA-256:   d2b58dcd9795c6dab886ffc31c9176928304da195c3a1e4e0d50ee2aed4e9efe
# Verified Classes:   ProvenanceEvictionError, Segment, Summary
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceEvictionError(RuntimeError):
    """Raised when a fold would evict anchors still cited by a retained summary."""
    pass


@dataclass
class Segment:
    seg_id: str
    turn_ids: set[str]
    tokens: int


@dataclass
class Summary:
    summary_id: str
    cites_anchors: set[str]          # turn IDs / receipts referenced by its claims
    claims: list[str] = field(default_factory=list)
    unverified_derived: bool = False


def commit_fold(
    summary: Summary,
    eviction_set: list[Segment],
    retained_anchors: set[str],
    durable_store_anchors: set[str],
) -> Summary:
    """
    Enforce the provenance-continuity invariant before inserting a child summary.

    A fold is valid iff every anchor the summary cites is either retained in the
    live window or resolvable from a durable store. Otherwise the summary must be
    demoted to unverified-derived (source turn IDs preserved as strings) or the
    fold must be refused.
    """
    evicted_turn_ids: set[str] = set()
    for seg in eviction_set:
        evicted_turn_ids |= seg.turn_ids

    resolvable = retained_anchors | durable_store_anchors
    orphaned = summary.cites_anchors - resolvable

    if not orphaned:
        return summary

    # Anchors the summary cites are being evicted with no durable backing.
    # Attempt demotion: keep the claim, keep the source IDs as opaque strings.
    if all(a in evicted_turn_ids for a in orphaned):
        summary.unverified_derived = True
        summary.claims = [
            f"{c} [unverified-derived; source={sorted(orphaned)}]"
            for c in summary.claims
        ]
        return summary

    # Orphaned anchors that are neither evicted here nor resolvable: the
    # reference graph is already broken and cannot be repaired by this fold.
    raise ProvenanceEvictionError(
        f"Summary {summary.summary_id} cites anchors {sorted(orphaned)} that are "
        f"neither retained, durably stored, nor part of this eviction pass. "
        f"Refusing fold: the claim would outlive its warrant and become "
        f"unfalsifiable in the retained window."
    )


def reconcile_contradiction(
    claim_anchors: set[str],
    retained_anchors: set[str],
    live_value: str,
    remembered_value: str,
) -> str:
    """
    When a live tool result contradicts a retained claim, the anchor test
    decides whether to reconcile or to defer to the live value.
    """
    if claim_anchors <= retained_anchors:
        # Anchors survive: normal reconciliation is permitted.
        return f"reconcile({remembered_value}, {live_value})"

    # Anchors gone: the remembered value is unfalsifiable. Live value wins;
    # never average an unanchored memory against a verified observation.
    return live_value
