# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-torn-context-mutation-log-when-self-editing-policies-reconcile-against-a-stale-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-torn-context-mutation-log-when-self-editing-policies-reconcile-against-a-stale-checkpoint.warrant.json
# Markdown SHA-256:   acbb428655ec60a22c1e00cadf9ce699c33cedd1e2e3f98d953ed5ba5b548fe2
# Code AST SHA-256:   8a6fe0f31e1384eca28c38cb64d8ca328adbb0a47290a37d7979966d1969eac8
# Verified Classes:   TornPolicyLogError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TornPolicyLogError(RuntimeError):
    """Raised when a context-mutation log tail is not contiguous with its checkpoint."""
    pass


def reconcile_policy(checkpoint: dict, log_tail: list[dict]) -> dict:
    """
    Reconcile a self-editing context policy against its checkpoint.

    checkpoint: {"epoch": int, "absorbed_through_epoch": int, "policy": dict}
    log_tail:   [{"epoch": int, "forward_delta": dict, "inverse_delta": dict}, ...]

    Invariant: log_tail[0].epoch must equal checkpoint.absorbed_through_epoch + 1.
    A gap means lost entries; an overlap means double-counted entries. Neither
    may be silently repaired by synthesizing or inverting entries.
    """
    absorbed = checkpoint["absorbed_through_epoch"]

    if not log_tail:
        return dict(checkpoint["policy"])

    first_epoch = log_tail[0]["epoch"]

    if first_epoch > absorbed + 1:
        raise TornPolicyLogError(
            f"Log gap: checkpoint absorbed through epoch {absorbed}, "
            f"but tail begins at epoch {first_epoch}. "
            f"{first_epoch - absorbed - 1} mutation(s) lost. "
            f"Refusing to roll forward; replay from last known-good base."
        )

    if first_epoch <= absorbed:
        raise TornPolicyLogError(
            f"Log overlap: checkpoint absorbed through epoch {absorbed}, "
            f"but tail begins at epoch {first_epoch}. "
            f"{absorbed - first_epoch + 1} entry(ies) double-counted. "
            f"Refusing to invert; truncate tail to epoch > {absorbed} and log truncation."
        )

    # Contiguity holds: apply forward deltas in strict epoch order.
    policy = dict(checkpoint["policy"])
    prev = absorbed
    for entry in log_tail:
        if entry["epoch"] != prev + 1:
            raise TornPolicyLogError(
                f"Non-contiguous tail at epoch {entry['epoch']} "
                f"(expected {prev + 1}). Log is torn mid-sequence."
            )
        policy.update(entry["forward_delta"])
        prev = entry["epoch"]

    return policy
