# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-capability-scope-after-a-tool-result-mutates-the-warrant-surface.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-capability-scope-after-a-tool-result-mutates-the-warrant-surface.warrant.json
# Markdown SHA-256:   be6a3d1dcbf8729390bcbd051830f3bfeb54bc40416d358154be3ff1c24e680a
# Code AST SHA-256:   1030386fc8f5f4fcfad5b46841bf4ee3e51f7995a66007c310766cb3045821fe
# Verified Classes:   StaleWarrantError, WarrantEnvelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class StaleWarrantError(RuntimeError):
    """Raised when a call is attempted against a cached warrant envelope
    that a prior tool result has superseded."""


@dataclass
class WarrantEnvelope:
    scopes: set[str]
    principals: dict[str, str] = field(default_factory=dict)  # resource_id -> principal
    version: int = 0

    def adopt(self, delta: dict[str, Any]) -> "WarrantEnvelope":
        new = WarrantEnvelope(set(self.scopes), dict(self.principals), self.version + 1)
        for scope in delta.get("add_scopes", []):
            new.scopes.add(scope)
        for scope in delta.get("drop_scopes", []):
            new.scopes.discard(scope)
        for rid, principal in delta.get("principals", {}).items():
            new.principals[rid] = principal
        return new


WARRANT_BEARING_KEYS = {"grant", "aud", "principal", "expires", "sub_grant"}


def ingest_result(env: WarrantEnvelope, result: dict[str, Any]) -> WarrantEnvelope:
    """Re-derive the envelope from a tool result before the next planning step."""
    delta: dict[str, Any] = {}
    if "grant" in result:
        rid = result.get("id")
        if rid is None:
            raise StaleWarrantError(
                "result carries a grant but no resource id; cannot bind principal"
            )
        delta.setdefault("principals", {})[rid] = result["grant"]
    if "aud" in result:
        delta["drop_scopes"] = list(env.scopes - set(result["aud"]))
    if delta:
        return env.adopt(delta)
    return env


def authorize_call(env: WarrantEnvelope, scope: str, resource_id: str | None) -> None:
    if scope not in env.scopes:
        raise StaleWarrantError(
            f"scope {scope!r} absent from envelope v{env.version}; "
            f"re-derive before retrying"
        )
    if resource_id is not None and resource_id in env.principals:
        # require sub-grant principal for state-gated scopes
        if scope in {"publish", "delete"} and env.principals[resource_id] is None:
            raise StaleWarrantError(
                f"resource {resource_id!r} requires sub-grant principal for {scope!r}"
            )
