# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-delegation-warrant-when-a-downstream-agent-returns-a-result-that-appears-to-satisfy-the-original-request.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-delegation-warrant-when-a-downstream-agent-returns-a-result-that-appears-to-satisfy-the-original-request.warrant.json
# Markdown SHA-256:   358de19cc48d38d21122a8a923aba747f73580e20bd918f2218c2a755d183d8d
# Code AST SHA-256:   228687cdea86cc285b183856ab84041de1337e4c3bc90c74249f807979bca253
# Verified Classes:   AttenuationViolation, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import FrozenSet, Tuple


class AttenuationViolation(RuntimeError):
    """Raised when a delegation chain's authority is not monotonic at consumption."""
    pass


@dataclass(frozen=True)
class Warrant:
    grantee: str
    caps: FrozenSet[Tuple[str, str, str]]  # (resource, verb, constraint)
    nonce: str
    issued_at: float
    ttl_s: float

    def fresh(self, now: float) -> bool:
        return now < self.issued_at + self.ttl_s


def verify_at_consumption(
    op: Tuple[str, str, str],
    terminal: Warrant,
    head: Warrant,
    payload_resource_tokens: FrozenSet[str],
    now: float,
) -> None:
    # 1. Attenuation monotonicity: terminal must be a subset of head.
    if not terminal.caps.issubset(head.caps):
        raise AttenuationViolation(
            f"terminal caps {terminal.caps - head.caps} not granted by head warrant"
        )

    # 2. Operation binding: the op the caller is about to run must be in the terminal warrant.
    if op not in terminal.caps:
        raise AttenuationViolation(
            f"operation {op} not authorized by terminal warrant {terminal.grantee}"
        )

    # 3. Provenance-to-payload binding: any resource the op names must be byte-identical
    #    to a granted resource, not merely mentioned in the payload.
    op_resource = op[0]
    if op_resource not in {c[0] for c in terminal.caps}:
        raise AttenuationViolation(
            f"op resource {op_resource!r} is not a granted resource; "
            f"payload mention is not a capability"
        )

    # 4. Freshness at consumption, not at issuance.
    if not head.fresh(now):
        raise AttenuationViolation(
            f"head warrant nonce {head.nonce!r} expired at consumption time"
        )

    # 5. Confusable-name rejection: payload tokens that lexically resemble granted
    #    resources but are not byte-identical must not be promoted to operations.
    granted_resources = {c[0] for c in terminal.caps}
    for tok in payload_resource_tokens:
        if tok in granted_resources:
            continue
        if any(tok.startswith(g) or g.startswith(tok) for g in granted_resources):
            raise AttenuationViolation(
                f"payload token {tok!r} confusable with granted resource; reject"
            )


# Example: the observed failure, now gated.
head = Warrant(
    grantee="O",
    caps=frozenset({("fs:/data", "read", "none"), ("fs:/tmp/out", "write", "none")}),
    nonce="n-0", issued_at=1000.0, ttl_s=600.0,
)
terminal = Warrant(
    grantee="E",
    caps=frozenset({("fs:/data", "read", "none")}),  # note: no write
    nonce="n-2", issued_at=1010.0, ttl_s=300.0,
)
payload_tokens = frozenset({"fs:/data", "fs:/tmp/out"})  # E merely *named* /tmp/out

try:
    verify_at_consumption(
        op=("fs:/tmp/out", "write", "none"),
        terminal=terminal,
        head=head,
        payload_resource_tokens=payload_tokens,
        now=1050.0,
    )
except AttenuationViolation as e:
    print("BLOCKED:", e)
    # BLOCKED: operation ('fs:/tmp/out', 'write', 'none') not authorized by terminal warrant E
