# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-delegated-aaif-credential-chain-from-silently-widening-scope-when-an-intermediate-agent-re-signs-a-sub-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-delegated-aaif-credential-chain-from-silently-widening-scope-when-an-intermediate-agent-re-signs-a-sub-warrant.warrant.json
# Markdown SHA-256:   b2b60319ebfeaa1cbd199e7619f312661798def5c828999296a172f7ccf63889
# Code AST SHA-256:   622b6cdd60cd85000ee650996282390dfe80a9247bdf78a9817694ad15f1d483
# Verified Classes:   ScopeWideningError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class ScopeWideningError(RuntimeError):
    """Raised when a delegated warrant's declared scope is not provably a subset
    of its parent's effective (folded) scope, or when containment is undecidable."""
    pass


def fold_effective_scope(chain):
    # chain: list of warrants root-first; each has .declared_scope (dict) and .signature_valid
    if not chain:
        raise ScopeWideningError("empty credential chain")
    effective = dict(chain[0].declared_scope)
    if not chain[0].signature_valid:
        raise ScopeWideningError("root warrant signature invalid")
    for hop in chain[1:]:
        if not hop.signature_valid:
            raise ScopeWideningError(f"hop {hop.id} signature invalid")
        declared = hop.declared_scope
        for key, val in declared.items():
            if key not in effective:
                # a field the parent never granted cannot be introduced downstream
                raise ScopeWideningError(
                    f"hop {hop.id} introduces ungranted field {key!r}"
                )
            relation = subset_relation(val, effective[key])
            if relation is None:
                # incomparable scope elements (e.g. regex vs glob): fail closed
                raise ScopeWideningError(
                    f"hop {hop.id} scope for {key!r} is incomparable with parent; "
                    "cannot prove attenuation"
                )
            if not relation:
                raise ScopeWideningError(
                    f"hop {hop.id} widens {key!r}: {val!r} not subset of {effective[key]!r}"
                )
        # fold: intersection, which for a proven subset is the declared value
        effective = {k: declared.get(k, effective[k]) for k in effective}
    return effective


def subset_relation(child, parent):
    # returns True (subset), False (not subset), or None (undecidable)
    if isinstance(child, str) and isinstance(parent, str):
        if child.endswith("/*") and parent.endswith("/*"):
            return child[:-2].startswith(parent[:-2])
        return child == parent
    if isinstance(child, (int, float)) and isinstance(parent, (int, float)):
        return child <= parent
    if isinstance(child, set) and isinstance(parent, set):
        return child.issubset(parent)
    return None
