# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-delegated-aaif-credential-from-silently-widening-its-scope-when-the-delegating-agent-re-derives-a-sub-warrant-from-a-lossy.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-delegated-aaif-credential-from-silently-widening-its-scope-when-the-delegating-agent-re-derives-a-sub-warrant-from-a-lossy.warrant.json
# Markdown SHA-256:   c20e9b275a4ec79926c9d572393cef86a25cf3104a43dad8e46badc6d20a5a72
# Code AST SHA-256:   82123787bd1cf8cea78b9943715992b8b856fb45294af5d24913a1037d076f12
# Verified Classes:   ScopeWideningError, GrantSet
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ScopeWideningError(RuntimeError):
    """Raised when a re-derived child warrant is not a strict subset of the parent."""


@dataclass
class GrantSet:
    actions: set[str] = field(default_factory=set)
    resource_prefixes: list[str] = field(default_factory=list)
    constraints: dict[str, int] = field(default_factory=dict)


def _prefix_subset(child: str, parent: str) -> bool:
    # child prefix must fall under a parent prefix; wildcard '*' only matches within parent
    if parent.endswith("/*"):
        base = parent[:-1]  # keep trailing slash
        return child.startswith(base) or child == parent
    return child == parent


def assert_child_scope_subset(parent: GrantSet, child: GrantSet,
                              relaxations: Optional[dict[str, int]] = None) -> None:
    relaxations = relaxations or {}

    # (S) exact-token action subset
    widened_actions = child.actions - parent.actions
    if widened_actions:
        raise ScopeWideningError(
            f"child actions not in parent: {sorted(widened_actions)}"
        )

    # (M) resource prefix containment against canonical parent bytes
    for c in child.resource_prefixes:
        if not any(_prefix_subset(c, p) for p in parent.resource_prefixes):
            raise ScopeWideningError(
                f"child resource {c!r} escapes all parent prefixes "
                f"{parent.resource_prefixes!r}"
            )

    # (C) constraint carriage: every parent constraint present or explicitly relaxed
    for key, pval in parent.constraints.items():
        if key in child.constraints:
            if child.constraints[key] > pval:
                raise ScopeWideningError(
                    f"constraint {key} widened: child={child.constraints[key]} > parent={pval}"
                )
        elif key in relaxations:
            if relaxations[key] > pval:
                raise ScopeWideningError(
                    f"relaxation of {key} exceeds parent ceiling {pval}"
                )
        else:
            raise ScopeWideningError(
                f"constraint {key} silently dropped from child scope"
            )


def issue_delegated_warrant(parent: GrantSet, proposed_child: GrantSet) -> GrantSet:
    assert_child_scope_subset(parent, proposed_child)
    return proposed_child


if __name__ == "__main__":
    parent = GrantSet(
        actions={"fs.read", "fs.list", "http.get"},
        resource_prefixes=["s3://corpus/inbox/*", "s3://corpus/derived/*"],
        constraints={"max_bytes": 10485760, "ttl": 900},
    )
    # Simulates prose-mediated re-derivation that collapsed wildcards and dropped constraints
    drifted = GrantSet(
        actions={"fs.read", "http.request"},
        resource_prefixes=["s3://corpus/*"],
        constraints={},
    )
    try:
        issue_delegated_warrant(parent, drifted)
    except ScopeWideningError as e:
        print(f"issuance rejected: {e}")
