# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-lossy-hierarchical-context-compaction-when-the-summary-tier-silently-discards-the-constraint-that-authorized.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-lossy-hierarchical-context-compaction-when-the-summary-tier-silently-discards-the-constraint-that-authorized.warrant.json
# Markdown SHA-256:   5adfd3a716b33324e073278d3698fa20035406179957d53ab7be8f179b155a14
# Code AST SHA-256:   6a65310d2647cdfddfc2fe56b5d19fa2d533a794908a3ad27e30467cbc27c833
# Verified Classes:   ConstraintLedgerIntegrityError, Constraint, CheckpointEnvelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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

class ConstraintLedgerIntegrityError(RuntimeError):
    """Raised when a restored checkpoint cannot vouch for the constraints
    that authorized its own tool calls."""
    pass

@dataclass
class Constraint:
    cid: str
    scope: str            # e.g. "migrations/", "prod_*"
    rule: str
    expires_at: Optional[float] = None

@dataclass
class CheckpointEnvelope:
    summary_tree: dict                      # lossy, event-oriented
    ledger: list[Constraint]                # verbatim, never summarized
    ledger_last_verified: float
    last_compaction_at: float

def restore_and_authorize(
    env: CheckpointEnvelope,
    tool_name: str,
    target: str,
    now: Optional[float] = None,
) -> str:
    now = now or time.time()

    # Invariant: the ledger must be at least as fresh as the last compaction.
    # If compaction ran after the ledger was verified, constraints may have
    # been abstracted away between verification and checkpoint.
    if env.ledger_last_verified < env.last_compaction_at:
        raise ConstraintLedgerIntegrityError(
            f"ledger verified at {env.ledger_last_verified} predates "
            f"compaction at {env.last_compaction_at}; restored authority is "
            f"degraded — refuse irreversible action on {tool_name}:{target}"
        )

    active = [c for c in env.ledger if c.expires_at is None or c.expires_at > now]

    # Constraint-authority mode: any matching constraint gates the call.
    for c in active:
        if _matches(c.scope, target):
            if tool_name in ("DROP", "ALTER", "DELETE") and "prod" in target:
                raise ConstraintLedgerIntegrityError(
                    f"tool {tool_name} on {target} blocked by active constraint "
                    f"{c.cid} ({c.rule}); operator re-confirmation token required"
                )

    # Degraded-authority mode: no ledger, no irreversible action.
    if not active:
        if tool_name in ("DROP", "ALTER", "DELETE"):
            raise ConstraintLedgerIntegrityError(
                f"no active constraints in ledger but {tool_name} on {target} "
                f"requested; absence of constraint is not authorization — "
                f"re-derive from operator before proceeding"
            )

    return "authorized"

def _matches(scope: str, target: str) -> bool:
    if scope.endswith("*"):
        return target.startswith(scope[:-1])
    return target.startswith(scope)
