# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-reject-a-delegated-warrant-after-a-legitimate-re-signing-a-boundary-analysis-of-aaif-delegation-chain-continuity-under-credential.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-reject-a-delegated-warrant-after-a-legitimate-re-signing-a-boundary-analysis-of-aaif-delegation-chain-continuity-under-credential.warrant.json
# Markdown SHA-256:   e121b5aaac98320135bff1141aef096c9e85dbdb45d94c40b1687a0f5319ba60
# Code AST SHA-256:   1bc17d9bfa2a3dfe5677e77c09f8ddb7a243041dcc8892237f460124f360f6b7
# Verified Classes:   ChainContinuityError, Warrant
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ChainContinuityError(RuntimeError):
    """Raised when a presented AAIF delegation chain fails the
    lineage-continuity invariant: every re-issued link must carry a
    `replaces` pointer, monotone scope, and a parent digest that points
    to the re-issued parent (not the stale original)."""


@dataclass
class Warrant:
    digest: str
    subject: str
    scope: frozenset
    parent: Optional[str]
    replaces: Optional[str] = None


def _digest(w: Warrant) -> str:
    h = hashlib.sha256()
    h.update(w.subject.encode())
    h.update(b"|")
    h.update(",".join(sorted(w.scope)).encode())
    h.update(b"|")
    h.update((w.parent or "").encode())
    return h.hexdigest()


def verify_chain_continuity(
    presented: list[Warrant],
    authorized_snapshot: dict[str, Warrant],
) -> None:
    """Walk the presented chain and assert it is a continuity-preserving
    supersession of the authorized snapshot. Raises ChainContinuityError
    on any violation. Returns None on success."""
    if not presented:
        raise ChainContinuityError("empty chain")

    # Root must be either identical or a replaces-linked supersession.
    root = presented[0]
    snap_root = authorized_snapshot.get(root.digest)
    if snap_root is None:
        if root.replaces is None:
            raise ChainContinuityError(
                f"root {root.digest} unknown and carries no replaces pointer"
            )
        prior = authorized_snapshot.get(root.replaces)
        if prior is None:
            raise ChainContinuityError(
                f"root {root.digest} replaces unknown digest {root.replaces}"
            )
        if not root.scope <= prior.scope:
            raise ChainContinuityError(
                f"root scope widened: {prior.scope} -> {root.scope}"
            )

    # Every non-root link: if it differs from the snapshot, it must
    # carry a replaces pointer to the snapshot link, monotone scope,
    # and a parent pointing to the *presented* parent (not the stale one).
    for i in range(1, len(presented)):
        link = presented[i]
        parent = presented[i - 1]
        if link.parent != parent.digest:
            raise ChainContinuityError(
                f"link {link.digest} parent {link.parent} != presented "
                f"parent {parent.digest} (stale lineage)"
            )
        snap = authorized_snapshot.get(link.digest)
        if snap is not None:
            continue  # byte-identical to authorized snapshot
        if link.replaces is None:
            raise ChainContinuityError(
                f"link {link.digest} differs from snapshot but has no "
                f"replaces pointer; cannot distinguish supersession "
                f"from substitution"
            )
        prior = authorized_snapshot.get(link.replaces)
        if prior is None:
            raise ChainContinuityError(
                f"link {link.digest} replaces unknown digest {link.replaces}"
            )
        if not link.scope <= prior.scope:
            raise ChainContinuityError(
                f"link {link.digest} scope widened: {prior.scope} -> {link.scope}"
            )


# --- Demonstration of the observed failure ---

def _make(digest, subject, scope, parent, replaces=None):
    w = Warrant(digest=digest, subject=subject, scope=frozenset(scope),
                parent=parent, replaces=replaces)
    return w


# Authorized snapshot at t0: W0 (root) -> W1 (to B).
w0 = _make("d0", "authority.example", ["read:dataset/*", "write:scratch/*"], None)
w1 = _make("d1", "B", ["read:dataset/42"], parent="d0")
snapshot = {"d0": w0, "d1": w1}

# At t+22min: authority re-issues W0' with replaces=d0.
w0p = _make("d0p", "authority.example", ["read:dataset/*", "write:scratch/*"],
            None, replaces="d0")
# A re-signs W1 as W1' with parent=d0p but NO replaces pointer (the bug).
w1p = _make("d1p", "B", ["read:dataset/42"], parent="d0p", replaces=None)

try:
    verify_chain_continuity([w0p, w1p], snapshot)
except ChainContinuityError as e:
    print("REJECTED:", e)

# Correctly re-issued W1' with replaces=d1 passes.
w1p_ok = _make("d1p2", "B", ["read:dataset/42"], parent="d0p", replaces="d1")
verify_chain_continuity([w0p, w1p_ok], snapshot)
print("ACCEPTED: continuity-preserving rotation")
