# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-attenuated-scope-resurrection-in-delegated-capability-chains-when-a-downstream-agent-re-derives-a-parent-warrant-from-cach.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-attenuated-scope-resurrection-in-delegated-capability-chains-when-a-downstream-agent-re-derives-a-parent-warrant-from-cach.warrant.json
# Markdown SHA-256:   149edfbab3114e7c775c6be7621886131d5f9e9790bde1708c2ccd40db8ee74d
# Code AST SHA-256:   0d231d9d3897618ebeca6b84d0ddac3923fd535a1d8b94b5eda5b450c16098c4
# Verified Classes:   ScopeResurrectionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ScopeResurrectionError(RuntimeError):
    """Raised when a derived capability set exceeds the leaf warrant's scope."""


def derive_effective_scope(warrant, provenance_summary: str, reconstructed: set[str]) -> set[str]:
    """
    Compute the authority an agent may exercise.

    Authority is a function of the signed leaf warrant ONLY. The provenance
    summary and any reconstruction derived from it are admissible as audit
    evidence, never as a source of authority. If a reconstruction claims more
    than the warrant grants, the reconstruction has resurrected an attenuated
    scope and must be rejected.
    """
    warrant_scope = set(warrant.parsed_scope)

    # Reconstruction is allowed to exist for narration, but must never widen.
    leaked = reconstructed - warrant_scope
    if leaked:
        raise ScopeResurrectionError(
            f"reconstruction from provenance resurrected attenuated scope {sorted(leaked)}; "
            f"leaf warrant grants only {sorted(warrant_scope)}; "
            f"provenance_summary={provenance_summary!r}"
        )

    # Authority is the warrant, full stop.
    return warrant_scope


def authorize(warrant, operation: str, provenance_summary: str, reconstructed: set[str]) -> None:
    effective = derive_effective_scope(warrant, provenance_summary, reconstructed)
    if operation not in effective:
        raise ScopeResurrectionError(
            f"operation {operation!r} not within leaf warrant scope {sorted(effective)}"
        )
