# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-aaif-credential-whose-delegation-chain-re-verifies-but-whose-scope-narrowing-proof-has-silen.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-aaif-credential-whose-delegation-chain-re-verifies-but-whose-scope-narrowing-proof-has-silen.warrant.json
# Markdown SHA-256:   da50e7daaf15f390cb2e1973d4aef7061ef64b1ddb29e504304a98ebfb8abb17
# Code AST SHA-256:   929bd483441efc0addcfe8e8c8d82cb41c8c72728140e19fd4d377da55653e28
# Verified Classes:   ScopeMonotonicityCollapse, Caveat, Link
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable, Literal

Decision = Literal["SUBSET", "DISJOINT", "INDETERMINATE"]


class ScopeMonotonicityCollapse(RuntimeError):
    """Raised when a delegated credential re-verifies but its scope-narrowing
    proof cannot be decided, so the leaf authority is not bounded by the root."""


@dataclass(frozen=True)
class Caveat:
    kind: str          # e.g. "path", "path_prefix", "op_in"
    value: object


@dataclass(frozen=True)
class Link:
    parent_scope: frozenset[Caveat]
    child_caveats: frozenset[Caveat]
    signature_valid: bool


# Closed registry: each kind maps to a predicate over the SAME canonical domain.
REGISTRY = {
    "path":        lambda canon, v: canon == v,
    "path_prefix": lambda canon, v: canon == v or canon.startswith(v.rstrip("/") + "/"),
    "op_in":       lambda canon, v: canon[1] in v,
}


def canon(arg: tuple[str, str]) -> tuple[str, str]:
    import os
    path, op = arg
    return (os.path.realpath(path), op)


def decide(parent: Iterable[Caveat], child: Caveat, probe: tuple[str, str]) -> Decision:
    c = canon(probe)
    if child.kind not in REGISTRY:
        return "INDETERMINATE"
    child_ok = REGISTRY[child.kind](c, child.value)
    if not child_ok:
        return "DISJOINT"
    for p in parent:
        if p.kind not in REGISTRY:
            return "INDETERMINATE"          # cannot compare across kinds
        if not REGISTRY[p.kind](c, p.value):
            return "DISJOINT"               # child admits what parent forbids
    return "SUBSET"


def admit(chain: list[Link], probe: tuple[str, str]) -> None:
    if not all(l.signature_valid for l in chain):
        raise ScopeMonotonicityCollapse("signature chain invalid")
    for link in chain:
        for child in link.child_caveats:
            d = decide(link.parent_scope, child, probe)
            if d == "INDETERMINATE":
                raise ScopeMonotonicityCollapse(
                    f"caveat kind {child.kind!r} not comparable to parent scope; "
                    f"monotonicity undecided for {probe!r} — refuse, do not default-pass"
                )
            if d == "DISJOINT":
                raise ScopeMonotonicityCollapse(
                    f"child caveat {child.kind}={child.value!r} widens parent scope for {probe!r}"
                )
    # Only now is the probe authorized.


if __name__ == "__main__":
    root = frozenset({Caveat("path", "/srv/jobs/42"), Caveat("op_in", {"read"})})
    link = Link(root, frozenset({Caveat("path_prefix", "/srv/jobs/42/")}), True)
    admit([link], ("/srv/jobs/42/../../etc/shadow", "read"))  # raises
