# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-capability-token-whose-attenuation-chain-is-valid-but-whose-scope-narrowing-is-non-monotonic-acr.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-capability-token-whose-attenuation-chain-is-valid-but-whose-scope-narrowing-is-non-monotonic-acr.warrant.json
# Markdown SHA-256:   a9fc300e6faffadaea2d5dd5bf1c3c149d9a9c250c6ee4c52394f5326f35b33a
# Code AST SHA-256:   963d936bc424ab4194b4b19fc8b9e7f78ed278577d1d194685be426619f36e9f
# Verified Classes:   NonMonotonicDelegationError, Scope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class NonMonotonicDelegationError(RuntimeError):
    """Raised when a delegated token's scope is not a subset of its parent's
    scope under absent-as-top semantics. The token may be cryptographically
    valid; the authority is not attenuated."""
    pass


@dataclass
class Scope:
    tool: str
    fields: dict[str, Any] = field(default_factory=dict)

    def field_names(self) -> set[str]:
        return set(self.fields.keys())


def _is_subset_value(child_val: Any, parent_val: Any) -> bool:
    # Globs, ranges, and sets are represented as dicts with a 'kind' tag.
    if isinstance(parent_val, dict) and isinstance(child_val, dict):
        pk, ck = parent_val.get("kind"), child_val.get("kind")
        if pk == ck == "glob":
            # child glob must be contained in parent glob; conservative check
            return child_val["pattern"].startswith(parent_val["pattern"].rstrip("*"))
        if pk == ck == "range":
            return (child_val["lo"] >= parent_val["lo"]
                    and child_val["hi"] <= parent_val["hi"])
        if pk == ck == "set":
            return set(child_val["members"]).issubset(set(parent_val["members"]))
    return child_val == parent_val


def verify_monotonic(parent: Scope, child: Scope) -> None:
    if parent.tool != child.tool:
        raise NonMonotonicDelegationError(
            f"tool mismatch: parent={parent.tool} child={child.tool}"
        )
    parent_fields = parent.field_names()
    child_fields = child.field_names()

    # Case (a): child omits a field the parent constrained.
    # Absent-as-top means the child is WIDER, not inheriting.
    omitted = parent_fields - child_fields
    if omitted:
        raise NonMonotonicDelegationError(
            f"non-monotonic widening: child omits parent-constrained "
            f"field(s) {sorted(omitted)}; absent is top, not inherited"
        )

    # Case (b): shared field where child value is not a subset.
    for name in parent_fields & child_fields:
        if not _is_subset_value(child.fields[name], parent.fields[name]):
            raise NonMonotonicDelegationError(
                f"non-monotonic widening on field {name!r}: "
                f"child={child.fields[name]!r} not subset of "
                f"parent={parent.fields[name]!r}"
            )


def admit_delegated_token(parent: Scope, child: Scope) -> bool:
    verify_monotonic(parent, child)
    return True


# Reproduction of the observed failure: summarizer drops max_bytes and
# require_audit because its schema predates them.
if __name__ == "__main__":
    orchestrator = Scope(
        tool="fs.write",
        fields={
            "paths": {"kind": "glob", "pattern": "/workspace/**"},
            "max_bytes": {"kind": "range", "lo": 0, "hi": 65536},
            "require_audit": True,
        },
    )
    summarizer = Scope(
        tool="fs.write",
        fields={"paths": {"kind": "glob", "pattern": "/workspace/cache/**"}},
    )
    try:
        admit_delegated_token(orchestrator, summarizer)
    except NonMonotonicDelegationError as e:
        print(f"REFUSED at admission: {e}")
