# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-a-capability-scoped-aaif-token-mid-task-when-an-mcp-server-s-tool-schema-mutates-between-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-derive-a-capability-scoped-aaif-token-mid-task-when-an-mcp-server-s-tool-schema-mutates-between-negotiation.warrant.json
# Markdown SHA-256:   91ca1eb0f0e9281c28f3f39b5339eaeb6e003751a6f0797856b8a272fbfa0b23
# Code AST SHA-256:   e7781c5c5c9c06cd27be5058e27756ce18474516250436eb03dd29f52defff5a
# Verified Classes:   CapabilitySchemaDriftError, WideningMutationRevokedTokenError, CapabilityToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class CapabilitySchemaDriftError(RuntimeError):
    """Raised when an AAIF token's embedded schema hash no longer matches
    the schema the MCP server is about to execute against."""
    pass


class WideningMutationRevokedTokenError(CapabilitySchemaDriftError):
    """Raised when schema drift widens effective authority; prior token is
    revoked, not merely stale."""
    pass


@dataclass(frozen=True)
class CapabilityToken:
    tool: str
    schema_hash: str
    scope: str
    signature_valid: bool


def schema_hash(schema: dict) -> str:
    canon = repr(sorted(schema.items())).encode()
    return hashlib.sha256(canon).hexdigest()[:8]


def is_widening(old: dict, new: dict) -> bool:
    # widened type or new resource-affecting parameter => authority grant
    if old.get("type") != new.get("type"):
        return True
    old_params = set(old.get("properties", {}))
    new_params = set(new.get("properties", {}))
    return bool(new_params - old_params)


def verify_capability(
    token: CapabilityToken,
    executing_schema: dict,
    prior_schema: dict,
) -> None:
    if not token.signature_valid:
        raise CapabilitySchemaDriftError("signature invalid")

    current_hash = schema_hash(executing_schema)
    if token.schema_hash != current_hash:
        if is_widening(prior_schema, executing_schema):
            raise WideningMutationRevokedTokenError(
                f"token schema {token.schema_hash} vs executing {current_hash}: "
                "widening mutation revokes prior capability; re-derive required"
            )
        raise CapabilitySchemaDriftError(
            f"token schema {token.schema_hash} vs executing {current_hash}: "
            "narrowing drift; re-derive before invoke"
        )


def invoke_with_capability(
    token: CapabilityToken,
    call_args: dict,
    prior_schema: dict,
    executing_schema: dict,
) -> dict:
    # invariant: token.schema_hash == executing schema hash, asserted pre-execution
    verify_capability(token, executing_schema, prior_schema)
    return {"status": "admitted", "tool": token.tool, "args": call_args}
