# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-hierarchical-compaction-has-silently-dropped-a-live-constraint-before-resuming-a-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-hierarchical-compaction-has-silently-dropped-a-live-constraint-before-resuming-a-task.warrant.json
# Markdown SHA-256:   d44150426b9a32bbfd03cad3e8da99dac02cade2fa325c1ae5149c9f1e34f259
# Code AST SHA-256:   8c57de5584fa19d703d086a7a62aef371f85f2be8fa22b4fab331310ce26d6ab
# Verified Classes:   ConstraintManifestError, ConstraintRecord, Checkpoint
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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

Modality = Literal["must_not", "halt_on_conflict", "pinned", "obligation"]


class ConstraintManifestError(RuntimeError):
    """Raised when a checkpoint's constraint manifest cannot be trusted to
    authorize an irreversible action after resume."""


@dataclass(frozen=True)
class ConstraintRecord:
    obj: str                      # e.g. "migrations/"
    modality: Modality
    halt_condition: str | None    # e.g. "schema_change_required"
    provenance_turn: int
    status: Literal["live", "discharged"] = "live"
    discharged_by_turn: int | None = None


@dataclass
class Checkpoint:
    summary_prose: str
    manifest: list[ConstraintRecord] = field(default_factory=list)
    verified_at: float = 0.0
    merged_at: float = 0.0


def assert_admissible(
    cp: Checkpoint,
    action_target: str,
    action_is_irreversible: bool,
    now: float | None = None,
) -> None:
    """Fail closed if the checkpoint cannot prove the action is permitted."""
    now = time.time() if now is None else now

    # Invariant 1: manifest must postdate the last merge, else it is stale.
    if cp.verified_at <= cp.merged_at:
        raise ConstraintManifestError(
            f"manifest verified_at={cp.verified_at} does not postdate "
            f"merged_at={cp.merged_at}; checkpoint is lossy and unverifiable"
        )

    # Invariant 2: no live must_not / halt_on_conflict may cover the target.
    for rec in cp.manifest:
        if rec.status != "live":
            continue
        if rec.modality not in ("must_not", "halt_on_conflict"):
            continue
        if action_target == rec.obj or action_target.startswith(rec.obj.rstrip("/") + "/"):
            if action_is_irreversible:
                raise ConstraintManifestError(
                    f"action on {action_target!r} blocked by live {rec.modality} "
                    f"constraint on {rec.obj!r} (provenance turn {rec.provenance_turn}, "
                    f"halt_condition={rec.halt_condition!r}); halt and seek operator"
                )

    # Invariant 3: ambiguous provenance on an irreversible action is binding.
    for rec in cp.manifest:
        if rec.status == "live" and rec.provenance_turn <= 0 and action_is_irreversible:
            raise ConstraintManifestError(
                f"constraint on {rec.obj!r} has ambiguous provenance; "
                f"treating as binding per fail-closed policy"
            )


def merge_checkpoint(
    parent: Checkpoint,
    child_summary: str,
    child_manifest: list[ConstraintRecord],
    now: float | None = None,
) -> Checkpoint:
    """Append-only merge: constraints may be discharged, never silently dropped."""
    now = time.time() if now is None else now
    parent_objs = {(r.obj, r.modality) for r in parent.manifest if r.status == "live"}
    child_objs = {(r.obj, r.modality) for r in child_manifest}

    dropped = parent_objs - child_objs
    # A dropped constraint is only legal if the child explicitly discharged it.
    discharged = {
        (r.obj, r.modality)
        for r in child_manifest
        if r.status == "discharged" and r.discharged_by_turn is not None
    }
    silent = dropped - discharged
    if silent:
        raise ConstraintManifestError(
            f"compaction silently dropped live constraints {sorted(silent)}; "
            f"refusing to emit lossy checkpoint"
        )

    return Checkpoint(
        summary_prose=child_summary,
        manifest=child_manifest,
        verified_at=now,
        merged_at=now,
    )
