# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-lossy-semantic-compression-during-context-budget-accounting-under-token-constraints.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-lossy-semantic-compression-during-context-budget-accounting-under-token-constraints.warrant.json
# Markdown SHA-256:   3330d2de49d4629d569156c4a5371d7dd8f6576f0bd70a7fcbea81673156cf28
# Code AST SHA-256:   79044b7cb69d739e839731109a8f69a57969132a9bc6348681134755b1ccb9d5
# Verified Classes:   ConstraintLedgerMiss, Constraint, ConstraintLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ConstraintLedgerMiss(RuntimeError):
    """Raised when a mutating action targets a resource with no ledger entry.

    Absence of a constraint is not permission to act. After lossy compression,
    'no constraint known' and 'no constraint exists' are indistinguishable, so
    the executor must fail closed and re-derive from source.
    """


@dataclass(frozen=True)
class Constraint:
    resource_id: str
    scope: str
    route: str
    source_span: tuple[int, int]  # offsets into the uncompressed transcript


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

    def ingest(self, constraint: Constraint) -> None:
        # Extraction happens at ingestion, BEFORE compression runs.
        # Conditionals from tool results are promoted here verbatim.
        self._entries[constraint.resource_id] = constraint

    def lookup(self, resource_id: str) -> Optional[Constraint]:
        return self._entries.get(resource_id)

    def render_for_context(self) -> str:
        # Re-injected verbatim at every step; never summarized.
        return "\n".join(
            f"- {c.resource_id}: scope={c.scope} route={c.route}"
            for c in self._entries.values()
        )


def execute_write(ledger: ConstraintLedger, resource_id: str, payload: dict) -> str:
    constraint = ledger.lookup(resource_id)
    if constraint is None:
        # Do NOT default to the production route. Fail closed.
        raise ConstraintLedgerMiss(
            f"no constraint entry for resource {resource_id!r}; "
            f"refusing mutating write — re-fetch source before proceeding"
        )
    route = constraint.route
    # ... issue write to `route` ...
    return f"wrote {resource_id} via {route}"


def compress_context(transcript: str, budget_tokens: int, ledger: ConstraintLedger) -> str:
    ledger_block = ledger.render_for_context()
    reserved = len(ledger_block.split())  # tokenizer-agnostic lower bound
    remaining = budget_tokens - reserved
    if remaining <= 0:
        raise ConstraintLedgerMiss(
            "ledger reservation exceeds budget; compression would evict conditionals"
        )
    summary = _summarize(transcript, max_tokens=remaining)  # lossy, by design
    return ledger_block + "\n---\n" + summary
