# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-the-compaction-boundary-has-already-been-crossed-in-lossy-long-horizon-agent-sessions.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-the-compaction-boundary-has-already-been-crossed-in-lossy-long-horizon-agent-sessions.warrant.json
# Markdown SHA-256:   446b2c70c888e0a1d1f7e2b944a62e3c307eaec281d05fbce9deb3960503242d
# Code AST SHA-256:   7ad2de248a14941b47744f7a13285a34c0613a068a274c6b10e5f9905f3e759c
# Verified Classes:   CompactionBoundaryViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CompactionBoundaryViolation(RuntimeError):
    """Raised when a step consumes a precondition from a lossy summary
    instead of the pinned ledger or a live re-verification."""
    pass


PRECONDITION_CLASSES = {"idempotency_guard", "negation", "pinned_id", "ordering", "completion_marker"}


def resolve_precondition(fact_id: str, source: str, pinned_ledger: dict, summary_text: str) -> str:
    """
    source is 'pinned' or 'summary'. A precondition-bearing fact may only be
    resolved from the pinned ledger. Resolving it from a summary is the
    boundary violation this record exists to prevent.
    """
    if fact_id not in pinned_ledger:
        raise CompactionBoundaryViolation(
            f"precondition {fact_id!r} absent from pinned ledger; "
            f"cannot be satisfied from lossy summary"
        )
    if source == "summary":
        raise CompactionBoundaryViolation(
            f"precondition {fact_id!r} resolved from summary text; "
            f"summary is a hypothesis, not a record — read the ledger or re-verify live"
        )
    return pinned_ledger[fact_id]


def reconcile_seam(summary_claims: dict, tail_claims: dict) -> dict:
    """
    On rehydration, tail (recent raw observation) outranks summary.
    Returns merged view with conflicts demoted to the tail value.
    """
    merged = dict(summary_claims)
    for k, v in tail_claims.items():
        if k in merged and merged[k] != v:
            # summary is stale relative to a fresher raw observation
            merged[k] = v
        else:
            merged[k] = v
    return merged


def guarded_apply(migration_id: str, pinned_ledger: dict, summary_text: str) -> None:
    guard_key = f"migration:{migration_id}:applied"
    already = resolve_precondition(guard_key, source="pinned", pinned_ledger=pinned_ledger, summary_text=summary_text)
    if already == "true":
        # correct behavior: skip, do not re-run
        return
    # ... perform migration ...
    pinned_ledger[guard_key] = "true"
