# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-capability-tokens-when-an-upstream-agent-s-audit-trail-is-truncated-mid-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-capability-tokens-when-an-upstream-agent-s-audit-trail-is-truncated-mid-chain.warrant.json
# Markdown SHA-256:   0c4ee6565cc5d28b00d405a8a157a2ba850224dee00dcc1e6fb74c95f4a68f22
# Code AST SHA-256:   ab2d0e8646f7f57e0a6f19cbf52397e0975520b547976b012b4fd287d4d67c90
# Verified Classes:   UnreconstructableWarrantChain, Token, AuditRecord
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class UnreconstructableWarrantChain(RuntimeError):
    """Raised when a delegated capability token cannot be bound to a fully
    reconstructable, signed parent-link audit record at every hop."""
    pass


@dataclass(frozen=True)
class Token:
    hop: int
    scope: frozenset
    parent_record_hash: str  # hash of the audit record that authorized THIS token
    signature_ok: bool


@dataclass(frozen=True)
class AuditRecord:
    hop: int
    parent_token_hash: str
    child_token_hash: str
    signed_at: float
    parent_live_at_mint: bool


def verify_delegation_chain(
    tokens: list[Token],
    records: dict,  # hop -> AuditRecord, keyed by the hop whose parent-link it is
    now: float,
    ttl: float,
) -> bool:
    if not tokens:
        raise UnreconstructableWarrantChain("empty delegation chain")

    # Root token must be independently live-checked; it has no parent record.
    for i, tok in enumerate(tokens):
        if not tok.signature_ok:
            raise UnreconstructableWarrantChain(
                f"hop {tok.hop}: token signature invalid"
            )

        if i > 0:
            prev = tokens[i - 1]
            # Invariant 1: scope must monotonically narrow.
            if not tok.scope.issubset(prev.scope):
                raise UnreconstructableWarrantChain(
                    f"hop {tok.hop}: scope {tok.scope} not subset of {prev.scope}"
                )

            # Invariant 2: the parent-link audit record MUST exist and bind
            # this exact token to the parent token. Absence is a hard fail.
            rec: Optional[AuditRecord] = records.get(tok.hop)
            if rec is None:
                raise UnreconstructableWarrantChain(
                    f"hop {tok.hop}: parent-link audit record missing; "
                    f"token is cryptographically valid but provenance is "
                    f"unreconstructable (truncation and pruning are "
                    f"indistinguishable, so deny)"
                )

            # Invariant 3: record must commit to this token and its parent.
            expected = hashlib.sha256(
                f"{prev.hop}:{sorted(prev.scope)}".encode()
            ).hexdigest()
            if rec.parent_token_hash != expected:
                raise UnreconstructableWarrantChain(
                    f"hop {tok.hop}: audit record does not bind parent token"
                )
            if rec.child_token_hash != tok.parent_record_hash:
                raise UnreconstructableWarrantChain(
                    f"hop {tok.hop}: token does not commit to its audit record "
                    f"(sign-before-audit ordering detected)"
                )

            # Invariant 4: parent grant must have been live at mint time.
            if not rec.parent_live_at_mint:
                raise UnreconstructableWarrantChain(
                    f"hop {tok.hop}: parent grant was revoked/expired at mint"
                )

            # Invariant 5: record freshness within token TTL.
            if now - rec.signed_at > ttl:
                raise UnreconstructableWarrantChain(
                    f"hop {tok.hop}: audit record stale beyond TTL"
                )

    return True
