# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-silently-escalate-scope-when-an-aaif-delegation-token-is-co-signed-by-a-downstream-agent-it-spawned.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-silently-escalate-scope-when-an-aaif-delegation-token-is-co-signed-by-a-downstream-agent-it-spawned.warrant.json
# Markdown SHA-256:   da4266f173ed22b5f3be8e0b0541c07eb5e024dae8cf2096624c8414b30b505e
# Code AST SHA-256:   c48caf86105362c570415508badc4cc614bc8973ca111150ca1860a9536c22b1
# Verified Classes:   ScopeEscalationError, Principal, DelegationToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ScopeEscalationError(RuntimeError):
    """Raised when a co-signed AAIF token's effective scope exceeds its declared scope."""


@dataclass
class Principal:
    name: str
    scope: frozenset


@dataclass
class DelegationToken:
    declared_scope: frozenset
    act_chain: list            # principals in the act chain, root-first
    co_signers: list = field(default_factory=list)


def compute_effective_scope(token: DelegationToken) -> frozenset:
    # Correct rule: meet over the act chain only. Co-signers contribute zero authority.
    effective = token.declared_scope
    for principal in token.act_chain:
        effective = effective & principal.scope
    return effective


def verify_token(token: DelegationToken) -> frozenset:
    effective = compute_effective_scope(token)
    # Invariant: monotonic attenuation. Effective must be a subset of declared.
    if not effective <= token.declared_scope:
        raise ScopeEscalationError(
            f"effective scope {sorted(effective)} exceeds declared "
            f"{sorted(token.declared_scope)}; co-signers={[c.name for c in token.co_signers]}"
        )
    # Guard against the union-widening bug: any co-signer whose ambient scope
    # leaks into the effective set is a verifier defect, not a valid grant.
    for cosigner in token.co_signers:
        leaked = (cosigner.scope & effective) - token.declared_scope
        if leaked:
            raise ScopeEscalationError(
                f"co-signer {cosigner.name} laundered scope {sorted(leaked)} "
                f"into token declared as {sorted(token.declared_scope)}"
            )
    return effective


def invoke_tool(token: DelegationToken, required: str) -> None:
    effective = verify_token(token)
    if required not in effective:
        raise ScopeEscalationError(
            f"tool requires {required!r}; effective scope is {sorted(effective)}"
        )


if __name__ == "__main__":
    orchestrator = Principal("O", frozenset({"repo:read", "repo:write", "deploy:staging"}))
    subagent = Principal("S", frozenset({"repo:read", "build:execute"}))

    token = DelegationToken(
        declared_scope=frozenset({"repo:read", "build:execute"}),
        act_chain=[orchestrator, subagent],
        co_signers=[subagent],
    )

    # Correct verifier: deploy:staging is NOT reachable despite the co-signature.
    try:
        invoke_tool(token, "deploy:staging")
    except ScopeEscalationError as exc:
        print(f"blocked as expected: {exc}")
