# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-model-driven-context-prune-as-non-idempotent-and-re-validate-the-residual-window-before-any-further-too.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-model-driven-context-prune-as-non-idempotent-and-re-validate-the-residual-window-before-any-further-too.warrant.json
# Markdown SHA-256:   da69ad1e9ac7b14f15d65e17b03bb9687563d8e4b698d6ebfe75d9dc085ab07e
# Code AST SHA-256:   eaba3cc9f479a4d5b45dabfcf2b29e3b99aa298d890b288c6cc88cbe825d4484
# Verified Classes:   PruneIntegrityError, ResidualWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class PruneIntegrityError(RuntimeError):
    """Raised when a tool argument is not grounded verbatim in the residual window,
    indicating a summary-derived (and therefore unverified) value."""
    pass


class ResidualWindow:
    def __init__(self, spans, evidence_log):
        self.spans = spans                # residual window after prune
        self.evidence_log = evidence_log  # append-only external store

    def contains_verbatim(self, token: str) -> bool:
        return any(token in span for span in self.spans)

    def rehydrate(self, token: str) -> str:
        for record in reversed(self.evidence_log):
            if token in record.payload:
                return record.payload
        raise PruneIntegrityError(
            f"token {token!r} absent from residual window and evidence log; "
            "cannot ground tool argument"
        )


def guard_tool_call(window: ResidualWindow, tool_name: str, arguments: dict) -> dict:
    """Every string argument that looks like a dereferenceable identifier must be
    verbatim-grounded in the residual window or rehydrated from the evidence log.
    Otherwise the call is a summary-derived mutation and must not be emitted."""
    grounded = {}
    for key, value in arguments.items():
        if isinstance(value, str) and ("/" in value or ":" in value or value.startswith("id-")):
            if not window.contains_verbatim(value):
                # Either rehydrate the authoritative span, or fail closed.
                try:
                    window.rehydrate(value)
                except PruneIntegrityError as exc:
                    raise PruneIntegrityError(
                        f"refusing {tool_name}: argument {key}={value!r} is not "
                        "grounded in residual window; prune evicted its source span. "
                        "Re-run discovery for this subgoal before emitting effects."
                    ) from exc
        grounded[key] = value
    return grounded
