# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-mid-task-and-the-summary-silently-drops-the-tool-call-argument-schema.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-mid-task-and-the-summary-silently-drops-the-tool-call-argument-schema.warrant.json
# Markdown SHA-256:   7f79573325d10920722f53ac4976277b116c099bb159581847d7db388eadfc30
# Code AST SHA-256:   d41155f99188f7d5f2d2746fca5a292248d7cc388381c94066c53e353121f02c
# Verified Classes:   CompactionDriftError, ConstraintLedger
# Defensive Guards:   5 fail-closed invariants (zero external deps)

"""Pre-emit guard against schema-blind compaction drift.

Runs after any compaction event, before a mutating tool call is emitted.
The constraint tier is the source of truth; the summary is never consulted.
"""

from dataclasses import dataclass, field
from typing import Any


class CompactionDriftError(RuntimeError):
    """Raised when a post-compaction call cannot be reconciled to the constraint ledger."""


@dataclass
class ConstraintLedger:
    # Append-only, never summarized. Keyed by (resource, field).
    entries: dict[tuple[str, str], Any] = field(default_factory=dict)

    def record(self, resource: str, field_name: str, value: Any) -> None:
        self.entries[(resource, field_name)] = value

    def get(self, resource: str, field_name: str) -> Any:
        key = (resource, field_name)
        if key not in self.entries:
            raise CompactionDriftError(
                f"constraint {key} absent from ledger after compaction; "
                f"re-fetch required, do not reconstruct from summary"
            )
        return self.entries[key]


def verify_pre_emit(
    ledger: ConstraintLedger,
    resource: str,
    call_args: dict[str, Any],
    required_fields: list[str],
) -> None:
    # 1. Required-field presence (catches dropped idempotency_key).
    for f in required_fields:
        if f not in call_args:
            raise CompactionDriftError(
                f"required field '{f}' missing from call to {resource}; "
                f"summary likely dropped it — re-fetch constraint, do not retry blindly"
            )

    # 2. Value conformance against the ledger (catches USD vs EUR drift).
    for f, emitted in call_args.items():
        try:
            authoritative = ledger.get(resource, f)
        except CompactionDriftError:
            # Field not constrained; allow but flag for audit.
            continue
        if isinstance(authoritative, list):
            if emitted not in authoritative:
                raise CompactionDriftError(
                    f"{resource}.{f}={emitted!r} violates ledger {authoritative!r}; "
                    f"post-compaction drift suspected"
                )
        elif isinstance(authoritative, (int, float)):
            if emitted > authoritative:
                raise CompactionDriftError(
                    f"{resource}.{f}={emitted} exceeds ceiling {authoritative}"
                )
        elif emitted != authoritative:
            raise CompactionDriftError(
                f"{resource}.{f}={emitted!r} != ledger {authoritative!r}"
            )


def emit_transfer(ledger: ConstraintLedger, account: str, args: dict[str, Any]) -> str:
    verify_pre_emit(
        ledger,
        resource=account,
        call_args=args,
        required_fields=["idempotency_key", "po_reference", "amount", "currency"],
    )
    return f"settled {args['amount']} {args['currency']} on {account}"


if __name__ == "__main__":
    ledger = ConstraintLedger()
    ledger.record("AP-7734", "currency", ["EUR"])
    ledger.record("AP-7734", "amount", 5000)

    # Post-compaction reconstruction that drifted to USD and dropped the key.
    drifted = {"amount": 4800, "currency": "USD", "po_reference": "PO-9"}
    try:
        emit_transfer(ledger, "AP-7734", drifted)
    except CompactionDriftError as e:
        print(f"BLOCKED: {e}")
