# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-aaif-delegated-credentials-from-silently-widening-scope-across-agent-to-agent-hops.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-aaif-delegated-credentials-from-silently-widening-scope-across-agent-to-agent-hops.warrant.json
# Markdown SHA-256:   20e14232ecbb1515ee345f204289fe123b88f82ac7a443da0d592b2fe8cad6ad
# Code AST SHA-256:   3dd14ff2aba534d3ffd4c4f3f0ab11577cb716d999afab67e781570fce460244
# Verified Classes:   ScopeAmplificationError, Atom
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ScopeAmplificationError(RuntimeError):
    """Raised when a delegated scope is not a semantic subset of its parent."""


@dataclass(frozen=True)
class Atom:
    kind: str          # e.g. "tool:read_file"
    resource: str      # e.g. "/tenant/acme/reports"


def namespace_covers(parent: Atom, child: Atom) -> bool:
    """True iff parent's resource namespace strictly contains child's.

    Ground truth is the namespace authority, not string prefixes. Here we
    model it as: same kind, and child.resource is under parent.resource
    with a real path-segment boundary (not a raw startswith).
    """
    if parent.kind != child.kind:
        return False
    p = parent.resource.rstrip("/")
    c = child.resource.rstrip("/")
    return c == p or c.startswith(p + "/")


def assert_attenuating(parent_scope: list[Atom], child_scope: list[Atom]) -> None:
    """Enforce directional containment: every child atom covered by some parent atom.

    The quantifier order is load-bearing. Swapping it turns attenuation
    into amplification while still returning a bool.
    """
    uncovered = [
        c for c in child_scope
        if not any(namespace_covers(p, c) for p in parent_scope)
    ]
    if uncovered:
        raise ScopeAmplificationError(
            f"delegation widens scope; uncovered child atoms: {uncovered}"
        )


def delegate(parent_scope: list[Atom], requested: list[Atom]) -> list[Atom]:
    # A normalizing adapter that collapses tenant segments must fail here,
    # not proceed and launder the widened atom downstream.
    assert_attenuating(parent_scope, requested)
    return requested


if __name__ == "__main__":
    parent = [
        Atom("tool:read_file", "/tenant/acme"),
        Atom("tool:read_file", "/tenant/beta/reports"),
    ]
    # Adapter collapsed /tenant/acme and /tenant/beta into /tenant.
    widened = [Atom("tool:read_file", "/tenant")]
    try:
        delegate(parent, widened)
    except ScopeAmplificationError as e:
        print(f"hop rejected: {e}")
        raise
