# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-plugin-manifest-s-declared-capability-scopes-as-non-authoritative-at-load-time-and-re-derive-effective.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-plugin-manifest-s-declared-capability-scopes-as-non-authoritative-at-load-time-and-re-derive-effective.warrant.json
# Markdown SHA-256:   7d862669d1120345353f22465a64e69d5fbae2a9eebf677e1658ec61f61e7b65
# Code AST SHA-256:   740587acff8c2e34fc9617ac352b296294eb7556021b37c16d3d8bee9d850f32
# Verified Classes:   ClosureScopeWidening
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ClosureScopeWidening(RuntimeError):
    """Raised when a plugin's transitive dependency closure grants
    capability categories the top-level manifest did not declare,
    and the runtime cannot guarantee per-plugin authority isolation."""
    pass


SCOPE_CATEGORIES = ("read", "write", "exec", "net", "secret", "tool")


def resolve_closure_scope(manifest, registry, _seen=None):
    """Compute the union of declared scope categories across the
    transitive dependency closure. Cycles are tolerated via _seen."""
    _seen = _seen or set()
    if manifest["id"] in _seen:
        return set()
    _seen.add(manifest["id"])
    scope = set(manifest.get("scopes", []))
    for dep_id in manifest.get("dependencies", []):
        dep = registry[dep_id]
        scope |= resolve_closure_scope(dep, registry, _seen)
    return scope


def authorize_load(parent_manifest, registry, isolation_guaranteed: bool):
    """Enforce the closure-scope invariant before instantiation.

    Per-manifest scope is authoritative ONLY if the closure is
    instantiated into isolated authority domains. Otherwise the
    effective authority is the union over the closure, and any
    widening beyond the parent's reviewed scope is a load-blocking
    event — because the unmediated tool->llm->tool path inside a
    shared context is the actual injection channel.
    """
    parent_scope = set(parent_manifest.get("scopes", []))
    closure_scope = resolve_closure_scope(parent_manifest, registry)
    widening = closure_scope - parent_scope

    if not widening:
        return closure_scope

    if isolation_guaranteed:
        # Separate processes / FDs / caches: per-plugin scope is real.
        return parent_scope

    # Shared execution context: composition widens authority.
    offending = sorted(widening)
    raise ClosureScopeWidening(
        f"parent={parent_manifest['id']!r} reviewed_scope={sorted(parent_scope)} "
        f"closure_scope={sorted(closure_scope)} widened_by={offending} "
        f"deps={parent_manifest.get('dependencies', [])} "
        f"reason=shared-context tool->llm->tool channel is unmediated; "
        f"refusing load until isolation or re-review of the union scope"
    )
