# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-signed-skill-manifest-whose-declared-capability-set-is-a-strict-subset-of-its-prior-version.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-signed-skill-manifest-whose-declared-capability-set-is-a-strict-subset-of-its-prior-version.warrant.json
# Markdown SHA-256:   fe062aa6d351fbb68e830c603c175b81a8ddf5bdc028b0caa4013f7956352be7
# Code AST SHA-256:   7ecea81a3586a2afe8955a47e514dc509c41425301b3b228094ef2bd2c7c0598
# Verified Classes:   CapabilityContractionViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CapabilityContractionViolation(RuntimeError):
    """Raised when a signed skill manifest contracts its declared capabilities
    while the runtime retains ambient grants that the contraction cannot revoke,
    producing a net-widening of the effective attack surface."""
    pass


def evaluate_upgrade(current, candidate, runtime_ambient, signer_trusted):
    """
    current:   dict with 'version', 'declared' (set), 'signer'
    candidate: dict with 'version', 'declared' (set), 'signer', 'body_refs' (set)
    runtime_ambient: set of grants the live process holds regardless of manifest
    signer_trusted: bool, whether candidate['signer'] is transitively trusted
                     from current['signer']
    """
    declared_old = current["declared"]
    declared_new = candidate["declared"]

    is_contraction = declared_new < declared_old  # strict subset

    if not is_contraction:
        # Expansions and lateral moves go through the normal review path.
        return "review"

    if not signer_trusted:
        # A contraction signed by a new key is a rotation/squat event.
        raise CapabilityContractionViolation(
            f"{candidate['version']} contracts capabilities but is signed by "
            f"untrusted key {candidate['signer']!r}; treat as expansion-equivalent."
        )

    effective_old = declared_old | runtime_ambient
    effective_new = declared_new | runtime_ambient

    if not effective_new <= effective_old:
        raise CapabilityContractionViolation(
            f"{candidate['version']} declares a subset of {current['version']} "
            f"but effective surface widens via ambient grants: "
            f"{(effective_new - effective_old)!r}"
        )

    # Body must not reference grants it no longer declares.
    undeclared_refs = candidate["body_refs"] - declared_new
    if undeclared_refs:
        raise CapabilityContractionViolation(
            f"{candidate['version']} body references grants absent from its "
            f"own declaration: {undeclared_refs!r}; contraction is a cover for "
            f"ambient-grant abuse."
        )

    # Safe only if the loader re-spawns clean; otherwise require review.
    return "respawn_required"
