# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-derives-a-delegated-aaif-scope-after-a-mid-exchange-context-eviction.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-derives-a-delegated-aaif-scope-after-a-mid-exchange-context-eviction.warrant.json
# Markdown SHA-256:   9a064f6f58190abb42fee8fb54c12e84ca3c651993dae619c4b108e0bf55be42
# Code AST SHA-256:   296be91837ddeba91118e4185907f0e66fa09ae35ae48e2e1dce4a023efbef43
# Verified Classes:   ScopeRederivationError, SignedToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ScopeRederivationError(RuntimeError):
    """Raised when a delegated scope is re-derived from a non-authoritative source."""
    pass


@dataclass
class SignedToken:
    token_id: str
    delegator: str
    delegate: str
    # Concrete literals only. No wildcards in a signed claim.
    scope: frozenset[str]
    signature_valid: bool = True


def expand_literal(claim: str) -> frozenset[str]:
    # A signed claim is a single concrete literal; it never expands to a prefix.
    return frozenset({claim})


def validate_subset(derived: frozenset[str], inbound: SignedToken) -> None:
    if not inbound.signature_valid:
        raise ScopeRederivationError(
            f"inbound token {inbound.token_id} failed signature check"
        )
    authoritative = frozenset().union(*(expand_literal(c) for c in inbound.scope))
    if not derived.issubset(authoritative):
        raise ScopeRederivationError(
            f"derived scope {sorted(derived)} is not a subset of "
            f"authoritative scope {sorted(authoritative)} for token "
            f"{inbound.token_id}; refusing to re-mint"
        )


def remint_from_memory(
    inbound: SignedToken,
    remembered_scope: str,
    source: str,
) -> SignedToken:
    # source must be the literal signed claim, never a summary or normalized cache.
    if source != "signed_claim":
        raise ScopeRederivationError(
            f"refusing to re-mint from source={source!r}; only 'signed_claim' "
            f"is authoritative after context eviction"
        )
    derived = frozenset({remembered_scope})
    validate_subset(derived, inbound)
    return SignedToken(
        token_id=f"{inbound.token_id}:child",
        delegator=inbound.delegate,
        delegate="C",
        scope=derived,
    )


# Reproduces the observed failure: B re-derives "feature-*" from a compaction
# summary after eviction. The guardrail rejects it instead of minting.
if __name__ == "__main__":
    t_b = SignedToken(
        token_id="T_B",
        delegator="A",
        delegate="B",
        scope=frozenset({"read:repo", "write:branch:feature-x"}),
    )
    try:
        remint_from_memory(t_b, remembered_scope="write:branch:feature-*",
                           source="compaction_summary")
    except ScopeRederivationError as e:
        print(f"blocked: {e}")
