# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-scope-chain-has-silently-widened-across-an-aaif-re-delegation-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-scope-chain-has-silently-widened-across-an-aaif-re-delegation-hop.warrant.json
# Markdown SHA-256:   7b4b929d4584602da6378fe22c2a84e9423034f872f3e15318b36c3ab4588b53
# Code AST SHA-256:   58cc65819e26564ac60e4ab136477245b9d03a8e17ee65197c3c2135b7880bc9
# Verified Classes:   ScopeChainWideningError, ScopeRegistry
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Optional


class ScopeChainWideningError(RuntimeError):
    """Raised when a delegated credential's effective scope exceeds the root grant
    at evaluation time, despite structurally valid signatures and hashes."""
    pass


@dataclass
class ScopeRegistry:
    # Authoritative, post-reduction scope per issuer, keyed by issuer id.
    current_scope: dict
    canonical_version: str
    reduction_epoch: int


def canonicalize(scope: dict, version: str) -> bytes:
    # Issuer and verifier MUST agree on this. Version mismatch is itself a refusal.
    if version != "aaif-canon-2":
        raise ScopeChainWideningError(
            f"canonicalization version mismatch: verifier=aaif-canon-2 issuer={version}"
        )
    return json.dumps(scope, sort_keys=True, separators=(",", ":")).encode()


def verify_delegated_call(
    leaf_scope: dict,
    leaf_parent_hash: str,
    leaf_parent_epoch: int,
    issuer_id: str,
    registry: ScopeRegistry,
) -> None:
    # 1. Freshness gate: parent scope must be resolved from authoritative registry,
    #    not from any hop-local cache.
    parent_scope = registry.current_scope.get(issuer_id)
    if parent_scope is None:
        raise ScopeChainWideningError(f"no authoritative scope for issuer {issuer_id}")

    # 2. Reduction-epoch gate: if the issuer has advanced past the epoch the leaf
    #    was issued against, the leaf's parent hash is stale by construction.
    if registry.reduction_epoch > leaf_parent_epoch:
        raise ScopeChainWideningError(
            f"leaf bound to epoch {leaf_parent_epoch}, issuer at "
            f"{registry.reduction_epoch}; parent scope may have been narrowed"
        )

    # 3. Recompute parent hash under issuer's canonical form.
    recomputed = hashlib.sha256(
        canonicalize(parent_scope, registry.canonical_version)
    ).hexdigest()
    if recomputed != leaf_parent_hash:
        raise ScopeChainWideningError(
            "parent_scope_hash does not match current canonical parent scope; "
            "chain was bound to a pre-reduction serialization"
        )

    # 4. Subset test against *effective* parent scope at evaluation time.
    for op in leaf_scope.get("ops", []):
        if op not in parent_scope.get("ops", []):
            raise ScopeChainWideningError(
                f"leaf op {op!r} not in current parent ops {parent_scope.get('ops')}"
            )
    for res in leaf_scope.get("resources", []):
        if not any(res.startswith(p.rstrip("*")) for p in parent_scope.get("resources", [])):
            raise ScopeChainWideningError(
                f"leaf resource {res!r} not covered by parent {parent_scope.get('resources')}"
            )


def execute_shell(svc: str, registry: ScopeRegistry) -> str:
    leaf = {"tool": "shell", "resources": [f"repo:acme/{svc}"], "ops": ["exec"]}
    verify_delegated_call(
        leaf_scope=leaf,
        leaf_parent_hash="deadbeef" * 8,  # stale hash from pre-reduction planner cache
        leaf_parent_epoch=7,
        issuer_id="orchestrator-01",
        registry=registry,
    )
    return f"executed on {svc}"
