# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-validate-a-delegated-scope-after-a-token-refresh-and-why-oidc-sub-continuity-is-not-scope-continuity.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-validate-a-delegated-scope-after-a-token-refresh-and-why-oidc-sub-continuity-is-not-scope-continuity.warrant.json
# Markdown SHA-256:   0108fae270e82df930a856d0d79286d2c7eb61b606695a08f9ddcd2de721c992
# Code AST SHA-256:   839b48a5d52271f0cacf117cf7d1b94c88f160af3a5b615a2b057a7d26d76205
# Verified Classes:   ScopeContinuityViolation, DelegationToken, PlanStep, Plan, AgentSession
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeContinuityViolation(RuntimeError):
    """Raised when a refreshed token no longer covers the remaining plan."""
    pass


@dataclass(frozen=True)
class DelegationToken:
    jti: str
    sub: str
    scopes: FrozenSet[str]
    issued_at: float
    ttl: float

    def expired(self, now: float | None = None) -> bool:
        return (now or time.time()) >= self.issued_at + self.ttl


@dataclass
class PlanStep:
    name: str
    required: FrozenSet[str]


@dataclass
class Plan:
    steps: list[PlanStep]
    cursor: int = 0

    def remaining(self) -> list[PlanStep]:
        return self.steps[self.cursor:]


@dataclass
class AgentSession:
    token: DelegationToken
    plan: Plan
    # Snapshots that a naive executor might fall back to. Must be cleared on narrowing.
    stale_snapshots: list[DelegationToken] = field(default_factory=list)

    def refresh(self, new_token: DelegationToken) -> None:
        if new_token.sub != self.token.sub:
            raise ScopeContinuityViolation(
                f"principal drift on refresh: {self.token.sub} -> {new_token.sub}"
            )
        old_scopes = self.token.scopes
        new_scopes = new_token.scopes

        if not new_scopes.issuperset(old_scopes):
            uncovered = {
                s.name: (s.required - new_scopes)
                for s in self.plan.remaining()
                if not new_scopes.issuperset(s.required)
            }
            if uncovered:
                # Narrowing invalidates the remainder: abort and re-plan.
                # Also purge snapshots so no stale-token fallback is reachable.
                self.stale_snapshots.clear()
                self.token = new_token
                raise ScopeContinuityViolation(
                    f"refresh narrowed scopes {sorted(old_scopes - new_scopes)}; "
                    f"remaining steps uncovered: {uncovered}"
                )
        # Superset or equal: safe to resume.
        self.stale_snapshots.clear()
        self.token = new_token

    def execute_next(self) -> str:
        if self.plan.cursor >= len(self.plan.steps):
            return "done"
        step = self.plan.steps[self.plan.cursor]
        # Re-check at use time against the *current* token, never a snapshot.
        if not self.token.scopes.issuperset(step.required):
            raise ScopeContinuityViolation(
                f"step {step.name!r} requires {sorted(step.required)} "
                f"not in current token {sorted(self.token.scopes)}"
            )
        self.plan.cursor += 1
        return step.name


def run_session(sess: AgentSession, refreshed: DelegationToken) -> list[str]:
    executed = []
    try:
        sess.refresh(refreshed)
    except ScopeContinuityViolation:
        # Re-plan signal propagates; do not resume on stale authority.
        raise
    while True:
        try:
            executed.append(sess.execute_next())
        except ScopeContinuityViolation:
            raise
        if sess.plan.cursor >= len(sess.plan.steps):
            break
    return executed
