# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-summary-induced-instruction-drift-after-lossy-context-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-summary-induced-instruction-drift-after-lossy-context-compaction.warrant.json
# Markdown SHA-256:   65ea44929214340493a8c2131baaaa124d7844ca10ab2791a1441d081cfbf032
# Code AST SHA-256:   1bfef25692f86e7cb36d13e9623c29707de9884633c439873d3f26441f4c0049
# Verified Classes:   ConstraintOrphanedError, Constraint, ConstraintLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ConstraintOrphanedError(RuntimeError):
    """Raised when a compaction summary leaves a live constraint unbound to its governed resource."""
    pass


@dataclass
class Constraint:
    cid: str
    governed_token: str      # resource or action the constraint governs
    deontic: str             # e.g. "prohibit", "require", "conditional"
    verbatim: str


@dataclass
class ConstraintLedger:
    constraints: dict[str, Constraint] = field(default_factory=dict)

    def ingest(self, cid: str, token: str, deontic: str, verbatim: str) -> None:
        self.constraints[cid] = Constraint(cid, token, deontic, verbatim)

    def governing(self, token: str) -> list[Constraint]:
        return [c for c in self.constraints.values() if c.governed_token == token]


def assert_compaction_safe(
    ledger: ConstraintLedger,
    retained_window_tokens: set[str],
    active_context_constraint_ids: set[str],
) -> None:
    """
    Reject a compaction result if any token in the retained window is governed
    by a constraint that is not surfaced in the active context.
    """
    orphans: list[str] = []
    for token in retained_window_tokens:
        for c in ledger.governing(token):
            if c.cid not in active_context_constraint_ids:
                orphans.append(f"{c.cid} -> {token} ({c.deontic})")
    if orphans:
        raise ConstraintOrphanedError(
            "compaction would orphan live constraints: " + "; ".join(orphans)
        )


def gate_mutating_call(
    ledger: ConstraintLedger,
    target_token: str,
    active_context_constraint_ids: set[str],
) -> None:
    """
    Refuse a mutating tool call if its target is governed by a constraint
    that is not currently bound in the active context.
    """
    for c in ledger.governing(target_token):
        if c.deontic == "prohibit" and c.cid not in active_context_constraint_ids:
            raise ConstraintOrphanedError(
                f"call to {target_token!r} blocked: governing prohibition {c.cid} "
                f"not present in active context (verbatim: {c.verbatim!r})"
            )


# --- trace of the observed failure, now blocked ---
ledger = ConstraintLedger()
ledger.ingest(
    cid="C-003",
    token="primary-signing-key",
    deontic="prohibit",
    verbatim="do not rotate the primary-signing-key; pinned externally",
)

# step 22: compaction accepted with a summary that dropped C-003.
retained = {"primary-signing-key", "manifest", "bucket-a"}
active_ids = {"C-001", "C-002"}  # C-003 lost in the summary

try:
    assert_compaction_safe(ledger, retained, active_ids)
except ConstraintOrphanedError as e:
    print("compaction rejected:", e)

# step 27: even if compaction had slipped through, the action gate holds.
try:
    gate_mutating_call(ledger, "primary-signing-key", active_ids)
except ConstraintOrphanedError as e:
    print("action blocked:", e)
