# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-summary-shadowed-tool-call-resurrection-during-auto-compaction-of-long-horizon-transcripts.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-summary-shadowed-tool-call-resurrection-during-auto-compaction-of-long-horizon-transcripts.warrant.json
# Markdown SHA-256:   a8a138aef27f165e2e3bf5011198fe02bbf1c33a73f671ce2c9b8cb45a559e03
# Code AST SHA-256:   7afb169ad8017723e7eb88ad82875311b3abed7ec45590a9ae9d4ae70642c33d
# Verified Classes:   ProvenanceGapError, Witness, PostCompactionGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ProvenanceGapError(RuntimeError):
    """Raised when a side-effecting call lacks a surviving completion witness
    after auto-compaction. Fail-closed: never re-issue on a prose summary alone."""
    pass


@dataclass(frozen=True)
class Witness:
    tool: str
    args_hash: str
    completion_epoch: int
    call_id: str


SIDE_EFFECTING = {"request_quote", "submit_po", "send_email", "transfer_funds"}


def _args_hash(name: str, args: dict) -> str:
    payload = name + "|" + "|".join(f"{k}={args[k]}" for k in sorted(args))
    return hashlib.sha256(payload.encode()).hexdigest()[:16]


class PostCompactionGate:
    """Gate that every tool call passes through after a compaction event.
    A side-effecting call is allowed only if a machine-checkable completion
    witness survives in the structured ledger. Prose summaries never qualify."""

    def __init__(self, ledger: list[Witness], current_epoch: int):
        self._ledger = {(_w.tool, _w.args_hash): _w for _w in ledger}
        self._epoch = current_epoch

    def authorize(self, tool: str, args: dict) -> None:
        if tool not in SIDE_EFFECTING:
            return  # re-derivable; safe to re-issue from summary
        key = (tool, _args_hash(tool, args))
        witness = self._ledger.get(key)
        if witness is None:
            raise ProvenanceGapError(
                f"side-effecting call {tool}({args}) has no completion witness "
                f"post-compaction; summary text is not a license to act"
            )
        if witness.completion_epoch >= self._epoch:
            raise ProvenanceGapError(
                f"witness epoch {witness.completion_epoch} not strictly prior to "
                f"current epoch {self._epoch}; epoch monotonicity violated"
            )
        # witness present and prior -> call already executed, skip re-issue
        raise ProvenanceGapError(
            f"call {tool} already completed at epoch {witness.completion_epoch} "
            f"(call_id={witness.call_id}); refusing resurrection"
        )
