# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-credential-scopes-when-an-aaif-warrant-s-attenuation-chain-is-silently-widened-by-a-re-issuing-intermediary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-credential-scopes-when-an-aaif-warrant-s-attenuation-chain-is-silently-widened-by-a-re-issuing-intermediary.warrant.json
# Markdown SHA-256:   66aaab5178e9c7fde26d9201966ae1127a91d614747b001c706c86e006c56c3d
# Code AST SHA-256:   630f97c0cc59336904fe41e3ac407f8f039f7f649f3f027d991e14c2c10a3d0e
# Verified Classes:   ScopeWideningError, Predicate, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Callable, Mapping


class ScopeWideningError(RuntimeError):
    """Raised when a delegated warrant's effective scope is not a semantic
    subset of the root grant under the root's own interpretation function."""


@dataclass(frozen=True)
class Predicate:
    operator: str          # e.g. "under", "prefix"
    operand: str
    semantics_preserved: bool = True  # set False by a transforming intermediary


@dataclass(frozen=True)
class Warrant:
    hop_id: str
    tool: str
    predicate: Predicate
    root_hash: str | None      # content hash of the root warrant, if carried
    operator_manifest: tuple[str, ...]  # operators this hop's issuer understands


# Root-pinned interpretation: only the root's declared operators are trusted.
ROOT_INTERPRET: Mapping[str, Callable[[str, str], bool]] = {
    "under": lambda arg, root: arg == root or arg.startswith(root.rstrip("/") + "/"),
    "prefix": lambda arg, root: arg.startswith(root),
}


def interpret_root(operator: str, arg: str, operand: str) -> bool:
    if operator not in ROOT_INTERPRET:
        # Unknown operator under root semantics: cannot be trusted to attenuate.
        raise ScopeWideningError(
            f"operator {operator!r} not in root operator manifest; "
            "cannot prove semantic subset"
        )
    return ROOT_INTERPRET[operator](arg, operand)


def authorize_leaf(
    chain: list[Warrant],
    root: Warrant,
    leaf_arg: str,
) -> bool:
    if not chain:
        raise ScopeWideningError("empty warrant chain")

    # 1. Root must be retrievable and pinned by the leaf's chain.
    if chain[-1].root_hash is None or chain[-1].root_hash != root.hop_id:
        raise ScopeWideningError(
            "root warrant not carried through chain; cannot re-derive semantics"
        )

    # 2. Any hop that altered the predicate operator must attest preservation.
    for parent, child in zip(chain, chain[1:]):
        if child.predicate.operator != parent.predicate.operator:
            if not child.predicate.semantics_preserved:
                raise ScopeWideningError(
                    f"hop {child.hop_id} altered operator "
                    f"{parent.predicate.operator!r}->{child.predicate.operator!r} "
                    "without semantics-preserving attestation"
                )

    leaf = chain[-1]

    # 3. Root-anchored re-derivation: leaf argument must be inside ROOT scope.
    if not interpret_root(root.predicate.operator, leaf_arg, root.predicate.operand):
        raise ScopeWideningError(
            f"leaf arg {leaf_arg!r} outside root scope "
            f"{root.predicate.operator}:{root.predicate.operand}"
        )

    # 4. Leaf scope must also be inside root scope under root interpretation.
    if not interpret_root(
        root.predicate.operator, leaf.predicate.operand, root.predicate.operand
    ):
        raise ScopeWideningError(
            f"leaf declared scope {leaf.predicate.operator}:{leaf.predicate.operand} "
            f"is not a semantic subset of root "
            f"{root.predicate.operator}:{root.predicate.operand}"
        )

    return True


# --- Demonstration of the silent-widening trace -----------------------------
if __name__ == "__main__":
    root = Warrant(
        hop_id="W0",
        tool="filesystem.read",
        predicate=Predicate("under", "/data/tenant-42"),
        root_hash=None,
        operator_manifest=("under",),
    )
    # Intermediary silently coerced `under` -> `prefix`, dropping the boundary.
    widened = Warrant(
        hop_id="W2",
        tool="filesystem.read",
        predicate=Predicate("prefix", "/data/tenant-42", semantics_preserved=False),
        root_hash="W0",
        operator_manifest=("under", "prefix"),
    )
    try:
        authorize_leaf([root, widened], root, "/data/tenant-4200/secrets")
    except ScopeWideningError as exc:
        # Correct outcome: reject and escalate rather than execute.
        print(f"REJECTED: {exc}")
