# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-jit-elevation-grants-as-invalid-across-a-checkpoint-resume-boundary-in-aaif-scoped-agent-workflows.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-jit-elevation-grants-as-invalid-across-a-checkpoint-resume-boundary-in-aaif-scoped-agent-workflows.warrant.json
# Markdown SHA-256:   14671d24cdca179977b56a6f05dc73b337250e9588880459c9248fcd842e4466
# Code AST SHA-256:   0f3c12fbae6ae6c2b75f04e066acd4761105082f1817e87b717ecdf5e6ef97bd
# Verified Classes:   OrphanedElevationError, JitGrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class OrphanedElevationError(RuntimeError):
    """Raised when a JIT grant is presented outside its originating episode
    or against parameters that do not match the grant's intent hash."""
    pass


@dataclass(frozen=True)
class JitGrant:
    principal: str
    tool: str
    scope: str
    episode_id: str
    intent_hash: str
    expiry_epoch: int


def compute_intent_hash(tool: str, params: dict) -> str:
    canonical = json.dumps({"tool": tool, "params": params}, sort_keys=True)
    return hashlib.sha256(canonical.encode()).hexdigest()


def authorize_execution(
    grant: Optional[JitGrant],
    current_episode_id: str,
    tool: str,
    params: dict,
    now_epoch: int,
) -> None:
    if grant is None:
        raise OrphanedElevationError("no elevation grant present at execution time")

    if now_epoch >= grant.expiry_epoch:
        raise OrphanedElevationError(
            f"grant expired at {grant.expiry_epoch}, now {now_epoch}"
        )

    if grant.episode_id != current_episode_id:
        raise OrphanedElevationError(
            f"grant minted in episode {grant.episode_id!r} but presented in "
            f"episode {current_episode_id!r}; resume boundary orphaned the intent"
        )

    if grant.tool != tool or grant.scope != tool:
        raise OrphanedElevationError(
            f"grant tool/scope {grant.tool}/{grant.scope} does not cover {tool}"
        )

    expected = compute_intent_hash(tool, params)
    if expected != grant.intent_hash:
        raise OrphanedElevationError(
            "intent hash mismatch: resumed instance re-derived parameters that "
            "diverge from the elevation request's justification"
        )


def resume_with_grants(
    carried_grants: list[JitGrant],
    new_episode_id: str,
    checkpoint_kind: str,
) -> list[JitGrant]:
    if checkpoint_kind == "episode_breaking":
        # Revoke all JIT grants; force re-request against current state.
        return []
    if checkpoint_kind == "episode_preserving":
        # Re-stamp grants into the continuing episode only if already bound to it.
        survivors = [g for g in carried_grants if g.episode_id == new_episode_id]
        return survivors
    raise OrphanedElevationError(f"unknown checkpoint kind {checkpoint_kind!r}")
