# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-lossy-context-compaction-to-preserve-a-fidelity-invariant-across-a-mid-task-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-lossy-context-compaction-to-preserve-a-fidelity-invariant-across-a-mid-task-checkpoint.warrant.json
# Markdown SHA-256:   b4cdabbf59dd4e6ec5509da65c387a37418ab254329e0c709af620f191407d38
# Code AST SHA-256:   e3ca1c44425c3079b3a15dac6854ed32e5ff99b3ec7527e9da580fc9a954bc07
# Verified Classes:   CompactionFidelityError, PendingCall, CompactionRequest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class CompactionFidelityError(RuntimeError):
    """Raised when lossy compaction would drop a non-idempotent continuation fact."""


@dataclass
class PendingCall:
    tool: str
    args: dict[str, Any]
    # Provenance per argument: True if the value can be re-derived by a
    # deterministic lookup; False if it is single-use / irreversible / ephemeral.
    idempotent: dict[str, bool] = field(default_factory=dict)


@dataclass
class CompactionRequest:
    context_tokens: int
    window_tokens: int
    pending_calls: list[PendingCall]
    pinned_side_channel: dict[str, Any] = field(default_factory=dict)


def decide_compaction(req: CompactionRequest) -> str:
    pressure = req.context_tokens / req.window_tokens
    if pressure < 0.80:
        return "no_compaction"

    non_idempotent_fields: list[tuple[str, str]] = []
    for call in req.pending_calls:
        for arg_name, value in call.args.items():
            is_idem = call.idempotent.get(arg_name, False)
            if not is_idem and arg_name not in req.pinned_side_channel:
                non_idempotent_fields.append((f"{call.tool}.{arg_name}", repr(value)[:48]))

    if not non_idempotent_fields:
        return "compact_freely"

    # Attempt verbatim pinning only if the field is cleanly extractable.
    # Free-form blobs (e.g. a warrant embedded in prose) are not extractable.
    unpinnable = [
        (name, val) for (name, val) in non_idempotent_fields
        if not _is_structured(req, name)
    ]
    if unpinnable:
        raise CompactionFidelityError(
            "Refusing lossy compaction: non-idempotent continuation facts are not "
            "cleanly extractable for verbatim pinning. Checkpoint raw context and "
            f"escalate. Unpinnable: {unpinnable}"
        )

    return "compact_with_pinning"


def _is_structured(req: CompactionRequest, field_name: str) -> bool:
    # A real implementation checks the field against a schema (signed token,
    # absolute timestamp, integer counter). Free-form text is not structured.
    tool, _, arg = field_name.partition(".")
    for call in req.pending_calls:
        if call.tool == tool and arg in call.args:
            return not isinstance(call.args[arg], str) or _looks_like_token(call.args[arg])
    return False


def _looks_like_token(value: str) -> bool:
    # Heuristic: base64-ish signed blobs, not natural-language summaries.
    return len(value) >= 32 and all(c.isalnum() or c in "-_=+/" for c in value)


def compact(req: CompactionRequest) -> dict[str, Any]:
    decision = decide_compaction(req)
    if decision == "compact_with_pinning":
        # Summarizer runs only over the unpinned region; pinned facts are
        # re-injected verbatim after summarization.
        return {"mode": "pinned", "pinned": req.pinned_side_channel}
    if decision == "compact_freely":
        return {"mode": "lossy", "pinned": {}}
    raise CompactionFidelityError(f"unexpected decision: {decision}")
