# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-capability-negotiation-when-a-delegated-aaif-scope-is-narrower-than-the-requesting-agent-s-advertised-capability-set.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-capability-negotiation-when-a-delegated-aaif-scope-is-narrower-than-the-requesting-agent-s-advertised-capability-set.warrant.json
# Markdown SHA-256:   79b8197ada09a32facfd42b286904a4fc17686eb28a7a13fba12df78c135683d
# Code AST SHA-256:   95518a075974d9587cf45218051d4f01391010cb723d65c23e7d9506805865f1
# Verified Classes:   ScopeReductionRejected
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ScopeReductionRejected(RuntimeError):
    """Raised when a delegated AAIF scope is a strict subset of the caller's
    advertised capabilities and the caller has not opted into partial execution."""
    pass


def negotiate(caller_card: dict, token_scope: set, frame: dict) -> dict:
    advertised = set(caller_card.get("capabilities", []))
    granted = set(token_scope)
    effective = advertised & granted

    if effective == advertised:
        return {"status": "accepted", "scope": sorted(effective)}

    if effective and frame.get("allow_partial") is True:
        required = set(frame.get("required_capabilities", []))
        if not required.issubset(effective):
            raise ScopeReductionRejected(
                f"required={sorted(required)} not within effective={sorted(effective)}"
            )
        return {"status": "accepted_with_reduction", "scope": sorted(effective)}

    if not effective:
        raise ScopeReductionRejected(
            f"disjoint scope: advertised={sorted(advertised)} granted={sorted(granted)}"
        )

    raise ScopeReductionRejected(
        "strict subset of advertised capabilities granted "
        f"(missing={sorted(advertised - granted)}) and allow_partial is not set"
    )
