# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-verify-scope-attenuation-across-a-delegated-aaif-credential-chain-when-an-intermediate-agent-silently-widens-a-child-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-verify-scope-attenuation-across-a-delegated-aaif-credential-chain-when-an-intermediate-agent-silently-widens-a-child-warrant.warrant.json
# Markdown SHA-256:   6a0614edc45b2be478ca50dfa0c1321b1d9ba8b23b9fb0e61c5f77080a3b85fc
# Code AST SHA-256:   9d98e7a2766f19feb16b40f35166ecc2935c6bea2529dfca34593cfff635086b
# Verified Classes:   ScopeAttenuationViolation
# Defensive Guards:   7 fail-closed invariants (zero external deps)

class ScopeAttenuationViolation(RuntimeError):
    """Raised when a delegated warrant's effective scope is not a subset of its ancestor's."""
    pass


# Permission lattice: each dimension has a narrowing operator.
# caps attenuate downward; sets attenuate by subset; patterns by subsumption.
CAP_DIMENSIONS = {"max_amount", "max_count", "ttl_seconds"}
SET_DIMENSIONS = {"region", "actions", "resource_allowlist"}


def resolve_scope(warrant: dict, ancestors: list[dict]) -> dict:
    """Synthesize a fully-resolved scope, inheriting absent dims from the nearest ancestor.

    Absence in a child is interpreted as 'inherited', never 'unconstrained'.
    """
    resolved = dict(warrant.get("scope", {}))
    for ancestor in reversed(ancestors):  # nearest ancestor first
        for dim, val in ancestor.get("scope", {}).items():
            if dim not in resolved:
                resolved[dim] = val  # inherit, do NOT default to unconstrained
    return resolved


def check_attenuation(child: dict, parent: dict, request: dict) -> None:
    """Prove effective_scope(child) <= effective_scope(parent) per dimension.

    Raises ScopeAttenuationViolation on any widening, including widening that
    only appears after wildcard expansion against the concrete request.
    """
    c_scope = child["scope"]
    p_scope = parent["scope"]

    for dim in set(p_scope) | set(c_scope):
        c_val = c_scope.get(dim)
        p_val = p_scope.get(dim)

        if p_val is None and c_val is not None:
            # child introduces a dimension the parent never granted
            raise ScopeAttenuationViolation(
                f"child introduces dimension {dim!r} absent from parent"
            )

        if c_val is None:
            # child omits a parent dimension: treat as inherited (narrowest),
            # but flag for the caller to re-resolve; do not silently widen.
            continue

        if dim in CAP_DIMENSIONS:
            if c_val > p_val:
                raise ScopeAttenuationViolation(
                    f"cap {dim!r} widened: child={c_val} parent={p_val}"
                )
        elif dim in SET_DIMENSIONS:
            if not set(c_val).issubset(set(p_val)):
                raise ScopeAttenuationViolation(
                    f"set {dim!r} widened: {set(c_val) - set(p_val)} not in parent"
                )
        elif dim == "resource":
            # pattern subsumption against the concrete request, not string equality
            req_resource = request.get("resource")
            if req_resource is not None:
                if _matches(p_val, req_resource) and not _matches(c_val, req_resource):
                    raise ScopeAttenuationViolation(
                        f"resource pattern {c_val!r} does not subsume request {req_resource!r} "
                        f"under parent {p_val!r}"
                    )
        else:
            raise ScopeAttenuationViolation(f"unknown dimension {dim!r}; refusing to guess")


def _matches(pattern: str, value: str) -> bool:
    if pattern.endswith("/*"):
        return value.startswith(pattern[:-1])
    return pattern == value


def verify_chain(chain: list[dict], request: dict) -> dict:
    """Re-derive attenuation across the full chain at the consuming hop.

    chain[0] is the root warrant; chain[-1] is the presented (child) warrant.
    """
    if len(chain) < 2:
        raise ScopeAttenuationViolation("chain too short to verify attenuation")

    for i in range(1, len(chain)):
        child = chain[i]
        parent = chain[i - 1]
        # resolve child scope against all ancestors so absent dims are inherited
        resolved_child = dict(child)
        resolved_child["scope"] = resolve_scope(child, chain[:i])
        check_attenuation(resolved_child, parent, request)

    # final concrete-request check against the tightest ancestor bound
    effective = resolve_scope(chain[-1], chain[:-1])
    if "max_amount" in effective and request.get("amount", 0) > effective["max_amount"]:
        raise ScopeAttenuationViolation(
            f"request amount {request['amount']} exceeds chain cap {effective['max_amount']}"
        )
    return effective
