# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-hierarchical-auto-compaction-has-silently-inverted-the-provenance-ordering-of-a-resumed-agent-s-context.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-hierarchical-auto-compaction-has-silently-inverted-the-provenance-ordering-of-a-resumed-agent-s-context.warrant.json
# Markdown SHA-256:   e9298426c0108598aa1cabcc7eaf51300053f1aa3d451f2e77698b0343fd1aaf
# Code AST SHA-256:   b186d2fbd55501ac31881b4254dc83cf9168843288cc3a5832e0b4bf0e5c29ea
# Verified Classes:   ProvenanceInversionError, Fact, SummaryNode
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import List


class ProvenanceInversionError(RuntimeError):
    """Raised when a re-hydrated context presents a superseded fact
    with greater recency-weight than the fact that supersedes it."""


@dataclass
class Fact:
    key: str
    value: str
    epoch: int          # source-turn timestamp; monotonic
    supersedes: str = ""  # key of the fact this one replaces, if any


@dataclass
class SummaryNode:
    node_id: str
    children: List["SummaryNode"] = field(default_factory=list)
    facts: List[Fact] = field(default_factory=list)


def expand(node: SummaryNode) -> List[Fact]:
    """Depth-first expansion; order follows tree position (the bug)."""
    out: List[Fact] = []
    for child in node.children:
        out.extend(expand(child))
    out.extend(node.facts)
    return out


def rehydrate_and_verify(root: SummaryNode) -> List[Fact]:
    raw = expand(root)

    # Build supersession map: superseded_key -> superseding Fact
    superseders = {f.supersedes: f for f in raw if f.supersedes}
    position = {id(f): i for i, f in enumerate(raw)}

    for key, newer in superseders.items():
        older = next((f for f in raw if f.key == key), None)
        if older is None:
            continue
        if position[id(older)] < position[id(newer)]:
            raise ProvenanceInversionError(
                f"fact {key!r} (epoch {older.epoch}) appears before its "
                f"superseder {newer.key!r}={newer.value!r} "
                f"(epoch {newer.epoch}) in re-hydrated buffer; "
                f"compaction inverted provenance ordering"
            )

    # Safe path: sort by epoch descending so recency dominates position.
    return sorted(raw, key=lambda f: f.epoch, reverse=True)


def safe_fold(children: List[SummaryNode], parent_id: str) -> SummaryNode:
    """Fold children in descending epoch order to align summarizer
    positional bias with recency, preventing inversion at synthesis."""
    ordered = sorted(
        children,
        key=lambda n: max((f.epoch for f in expand(n)), default=-1),
        reverse=True,
    )
    return SummaryNode(node_id=parent_id, children=ordered)


if __name__ == "__main__":
    s1 = SummaryNode("S1b", facts=[Fact("region", "us-east", epoch=9)])
    s2 = SummaryNode("S2a", facts=[Fact("region", "eu-west", epoch=22,
                                        supersedes="region")])
    # Buggy fold: insertion order puts the stale node first.
    bad_root = SummaryNode("R", children=[s1, s2])
    try:
        rehydrate_and_verify(bad_root)
    except ProvenanceInversionError as e:
        print("caught:", e)

    # Correct fold: epoch-ordered children, verified clean.
    good_root = safe_fold([s1, s2], "R")
    print([f.value for f in rehydrate_and_verify(good_root)])
