# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-warrant-scope-collapse-when-federated-agents-re-derive-policy-from-partial-context.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-delegated-warrant-scope-collapse-when-federated-agents-re-derive-policy-from-partial-context.warrant.json
# Markdown SHA-256:   d5abae99d0d9c01ee8beef2e6ff823e03bfd59ef821d02fd82a0bc4cb6d4bdac
# Code AST SHA-256:   40bce174e976dee108de75f13c2c7358278f7cfe00afa11994923c42325454c3
# Verified Classes:   ResolutionVerdict, ScopeCollapseError, ScopeHashMismatchError, Constraint, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Callable


class ResolutionVerdict(Enum):
    SATISFIED = "satisfied"
    VIOLATED = "violated"
    UNKNOWN = "unknown"


class ScopeCollapseError(RuntimeError):
    """Raised when a warrant's effective scope cannot be soundly re-derived
    by the receiver, i.e. a load-bearing constraint is unevaluable."""


class ScopeHashMismatchError(RuntimeError):
    """Raised when a sub-warrant's claimed parent-scope hash does not match
    the delegator's precomputed evaluated-scope hash."""


@dataclass(frozen=True)
class Constraint:
    predicate: str
    load_bearing: bool  # removal widens the permitted resource/action set


@dataclass
class Warrant:
    constraints: list[Constraint]
    parent_scope_hash: str | None = None


def evaluate_scope(
    warrant: Warrant,
    resolver: Callable[[str], ResolutionVerdict],
) -> str:
    """Re-derive effective scope. Returns the evaluated-scope hash.

    Invariant: a load-bearing constraint that resolves to UNKNOWN must NOT be
    pruned. It must raise, forcing intake rejection or evaluation-time denial.
    """
    kept: list[str] = []
    for c in warrant.constraints:
        verdict = resolver(c.predicate)
        if verdict is ResolutionVerdict.SATISFIED:
            kept.append(c.predicate)
        elif verdict is ResolutionVerdict.VIOLATED:
            # Constraint is definitively not met: the warrant is inapplicable.
            raise ScopeCollapseError(
                f"constraint {c.predicate!r} resolved VIOLATED; warrant inapplicable"
            )
        else:  # UNKNOWN
            if c.load_bearing:
                raise ScopeCollapseError(
                    f"load-bearing constraint {c.predicate!r} unevaluable; "
                    f"pruning would widen effective scope"
                )
            # Auxiliary guard: safe to drop, does not widen reachable set.
            continue
    canonical = "|".join(sorted(kept))
    return hashlib.sha256(canonical.encode()).hexdigest()


def verify_subwarrant(
    parent_evaluated_hash: str,
    subwarrant: Warrant,
    resolver: Callable[[str], ResolutionVerdict],
) -> str:
    """Verify a sub-warrant's parent hash matches, then re-derive its scope."""
    if subwarrant.parent_scope_hash != parent_evaluated_hash:
        raise ScopeHashMismatchError(
            f"sub-warrant claims parent scope {subwarrant.parent_scope_hash!r}, "
            f"delegator precomputed {parent_evaluated_hash!r}; "
            f"scope collapse detected at sub-delegation hop"
        )
    return evaluate_scope(subwarrant, resolver)


# --- Demonstration of the failure trace ---

def org_b_resolver(predicate: str) -> ResolutionVerdict:
    if "tenant" in predicate:
        return ResolutionVerdict.UNKNOWN  # Org B lacks Org C tenant schema
    return ResolutionVerdict.SATISFIED


def demo() -> None:
    warrant = Warrant(constraints=[
        Constraint("tenant in {t-441,t-442}", load_bearing=True),
        Constraint("action in {read,summarize}", load_bearing=True),
        Constraint("max_depth <= 1", load_bearing=False),
    ])
    # Correct behavior: refuse to re-derive, do not prune the tenant bound.
    try:
        evaluate_scope(warrant, org_b_resolver)
    except ScopeCollapseError as e:
        print(f"intake rejected: {e}")
        return
    raise ScopeCollapseError("unreachable: tenant constraint should have blocked")


if __name__ == "__main__":
    demo()
