# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-capability-grant-when-its-own-observation-set-cannot-falsify-the-grantor-s-preconditions.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-capability-grant-when-its-own-observation-set-cannot-falsify-the-grantor-s-preconditions.warrant.json
# Markdown SHA-256:   a428ca3f237fac1a9b60a01dd7cc1bf1398f26a49c6eecc1aee8fffcc0ffaabd
# Code AST SHA-256:   a87bdf1720cb6f16ce88e67e4534060d89899e01298afc966ae7a1fb8f0ecf74
# Verified Classes:   UnwitnessedPreconditionError, Witnessed, Asserted, Grant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable, Any


class UnwitnessedPreconditionError(RuntimeError):
    """Raised when a grantee is asked to accept an irreversible grant
    whose load-bearing precondition cannot be tested before commitment."""
    pass


@dataclass(frozen=True)
class Witnessed:
    value: Any
    provenance: str          # e.g. "grantor:P@commit:a1b2c3"
    local_test: Callable[[Any], bool]


@dataclass(frozen=True)
class Asserted:
    predicate: str


@dataclass
class Grant:
    capability: str
    preconditions: list = field(default_factory=list)
    irreversible: bool = True


def accept_grant(grant: Grant, local_view: dict) -> str:
    """Accept, refuse, or accept-provisionally per the decision boundary."""
    untestable = []
    for pre in grant.preconditions:
        if isinstance(pre, Witnessed):
            if not pre.local_test(pre.value):
                raise UnwitnessedPreconditionError(
                    f"witnessed precondition failed for {grant.capability}: "
                    f"{pre.provenance} value={pre.value!r}"
                )
        elif isinstance(pre, Asserted):
            untestable.append(pre.predicate)

    if untestable and grant.irreversible:
        raise UnwitnessedPreconditionError(
            f"refusing irreversible grant {grant.capability!r}: "
            f"untestable preconditions {untestable}; "
            f"grantor must re-offer with witnesses"
        )
    if untestable:
        return "provisional"
    return "accepted"


# Trace of the observed failure:
stale_head = "a1b2c3"          # grantee's checkpoint view
grantor_head = "d4e5f6"        # actual head after grantor's prior call

bad_grant = Grant(
    capability="apply_patch(repo, branch, base_commit)",
    preconditions=[Asserted("base_commit == current_head(repo)")],
    irreversible=True,
)

try:
    accept_grant(bad_grant, local_view={"head": stale_head})
except UnwitnessedPreconditionError as e:
    # Correct behavior: refuse, name the predicate, force re-negotiation.
    print(f"REFUSED: {e}")

# Grantor re-offers with a witness the grantee can test locally:
good_grant = Grant(
    capability="apply_patch(repo, branch, base_commit)",
    preconditions=[
        Witnessed(
            value=grantor_head,
            provenance="grantor:P@head:d4e5f6",
            local_test=lambda v: v == local_view_head(),
        )
    ],
    irreversible=True,
)


def local_view_head() -> str:
    return stale_head  # grantee's own fresh read; mismatch is caught here


try:
    accept_grant(good_grant, local_view={"head": stale_head})
except UnwitnessedPreconditionError as e:
    print(f"WITNESS MISMATCH, safe refusal: {e}")
